forked from knipknap/exscript
/
exscript
executable file
·558 lines (497 loc) · 19.6 KB
/
exscript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
#!/usr/bin/env python
# Copyright (C) 2007-2010 Samuel Abels.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys
import os
import re
import imp
import getpass
import Exscript.protocols.drivers
from optparse import OptionParser, Option, OptionValueError
from Exscript import Queue, Account, PrivateKey, __version__
from Exscript.protocols import protocol_map
from Exscript.util import template
from Exscript.util.sigint import SigIntWatcher
from Exscript.util.cast import to_list, to_host
from Exscript.util.interact import get_login
from Exscript.util.log import log_to_file
from Exscript.util.file import get_accounts_from_file, \
get_hosts_from_file, \
get_hosts_from_csv
from Exscript.util.decorator import autologin
bracket_expression_re = re.compile(r'^\{([^\]]*)\}$')
def expand_bracket(value_name, value):
match = bracket_expression_re.match(value)
if match is None:
return value
prompt = match.group(1) or 'a value for "%s"' % value_name
if prompt.startswith('!'):
value = getpass.getpass('Please enter %s: ' % prompt[1:])
else:
value = raw_input('Please enter %s: ' % prompt)
return value
def expand_host_variables(host):
# Define host-specific variables.
for key, value in host.get_all().iteritems():
if isinstance(value, str):
value = expand_bracket(key, value)
elif hasattr(value, '__iter__'):
for n in range(len(value)):
if not isinstance(value[n], str):
continue
value[n] = expand_bracket(key, value[n])
host.set(key, value)
def run():
# Parse options.
options, args = parser.parse_args(sys.argv)
args.pop(0)
def mkhost(name):
return to_host(name,
default_protocol = options.protocol,
default_domain = options.default_domain)
def mkhosts_from_file(filename):
return get_hosts_from_file(options.hosts,
default_protocol = options.protocol,
default_domain = options.default_domain)
def mkhosts_from_csv(filename):
return get_hosts_from_csv(options.csv_hosts,
default_protocol = options.protocol,
default_domain = options.default_domain)
# Extract the hostnames out of the command line arguments.
filename = None
if not options.execute:
try:
filename = args.pop(0)
except IndexError, e:
parser.error('Missing filename')
hosts = [mkhost(h) for h in args]
# If a filename containing hostnames AND VARIABLES was given, read it.
if options.csv_hosts:
try:
csv_hosts = mkhosts_from_csv(options.csv_hosts)
except IOError, e:
parser.error(str(e))
if not csv_hosts:
print 'Warning: %s is empty.' % options.csv_hosts
hosts += csv_hosts
# If a filename containing hostnames was given, read it.
if options.hosts:
try:
txt_hosts = mkhosts_from_file(options.hosts)
except IOError, e:
parser.error(str(e))
except ValueError, e:
parser.error(e)
if not txt_hosts:
print 'Warning: %s is empty.' % options.hosts
hosts += txt_hosts
# If a filename of an Exscript driver was given, import it.
if options.load_driver:
print 'Searching drivers in %s...' % options.load_driver
name = os.path.splitext(os.path.basename(options.load_driver))[0]
try:
driver_module = imp.load_source(name, options.load_driver)
except IOError, e:
parser.error(str(e))
except Exception, e:
sys.stderr.write('Error in driver ' + options.load_driver + '\n')
raise
for name, obj in driver_module.__dict__.iteritems():
if Exscript.protocols.drivers.isdriver(obj):
Exscript.protocols.drivers.add_driver(obj)
print 'Driver ' + repr(name) + ' added.'
# Make sure that all mandatory options are present.
if not hosts:
parser.error('No hosts to connect to')
# Set host options.
for host in hosts:
host.set_option('debug', options.protocol_verbose)
host.set_option('verify_fingerprint', not options.ssh_auto_verify)
# Read the Exscript.
if options.execute:
script_content = options.execute
else:
file = open(filename, 'r')
script_content = file.read()
file.close()
# Prepare the code that is executed after the user script has completed.
#FIXME: Move into the library, then use read_template_from_file instead of read_template().
if not options.no_auto_logout:
script_content += r'''
## Exscript generated commands. ##
{if connection.guess_os() is "vrp"}
{connection.sendline("quit")}
{else}
{connection.sendline("exit")}
{end}'''
# Test whether the template compiles.
vars = options.define.copy()
if filename:
vars['__filename__'] = filename
vars.update(hosts[0].get_all())
try:
template.test(script_content, **vars)
except Exception, e:
if options.parser_verbose > 0:
raise
parser.error(str(e))
# Create Exscript.
queue = Queue(domain = options.default_domain,
mode = 'multiprocessing',
verbose = options.verbose,
max_threads = options.connections)
default_pool = queue.account_manager.default_pool
# Read the account pool file.
try:
if options.account_pool:
accounts = get_accounts_from_file(options.account_pool)
default_pool.add_account(accounts)
except IOError, e:
parser.error(str(e))
if options.account_pool and default_pool.n_accounts() == 0:
msg = r'WARNING: No accounts found in account pool file (%s)!'
print msg % options.account_pool
# Read username and password.
if options.non_interactive or default_pool.n_accounts() > 0:
user = None
password = None
password2 = None
else:
try:
user, password = get_login()
except KeyboardInterrupt:
sys.exit(1)
if options.authorization:
prompt = 'Please enter your authorization password: '
password2 = getpass.getpass(prompt)
else:
password2 = password
# Read the SSH key.
if options.ssh_key:
print "Reading key from", options.ssh_key
try:
key = PrivateKey.from_file(options.ssh_key, password)
except ValueError, e:
parser.error(str(e))
if user is None:
user = getpass.getuser()
else:
key = None
# Add the account to the pool.
if user is not None:
account = Account(user, password, password2, key = key)
default_pool.add_account(account)
# Ask for values of marked variables.
for host in hosts:
expand_host_variables(host)
for key, val in options.define.iteritems():
options.define[key] = expand_bracket(key, val)
# Choose the template processing type.
tmpl_vars = options.define
if options.no_prompt:
def function(job, host, conn, **kwargs):
kwargs.update(tmpl_vars)
kwargs.update(host.get_all())
return template.paste(conn, script_content, **kwargs)
else:
strip = not options.no_strip
def function(job, host, conn, **kwargs):
kwargs.update(tmpl_vars)
kwargs.update(host.get_all())
return template.eval(conn, script_content, strip, **kwargs)
# Wrap the template processor such that the login procedure is automated.
if not options.no_authentication:
attempts = options.retry_login + 1
decorator = autologin(attempts = attempts)
function = decorator(function)
# Wrap the template processor such that logging is enabled.
if options.logdir:
# Create the log directory.
if not os.path.exists(options.logdir):
print 'Creating log directory (%s)...' % options.logdir
try:
os.makedirs(options.logdir)
except IOError, e:
parser.error(str(e))
# Enable logging.
mode = options.overwrite_logs and 'w' or 'a'
decorator = log_to_file(options.logdir, mode, options.delete_logs)
function = decorator(function)
# Wait until the specified time. We are using os.system because
# it allows for specifying absolute times, not just the number
# of seconds like Python's time.sleep().
if options.sleep:
print "Waiting for %s..." % options.sleep,
sys.stdout.flush()
os.system('sleep %s' % options.sleep)
print "time expired, starting script."
# Run the template.
for host in hosts:
queue.run(host, function, attempts = options.retry + 1)
queue.join()
failed = queue.failed
queue.destroy()
return failed
# Define command line option value types.
def check_assignment(option, opt, value):
if not re.match(r'\S+=\S+', value):
raise OptionValueError('option %s: invalid value: %r' % (opt, value))
return value
def check_protocol(option, opt, value):
if value not in protocol_map:
raise OptionValueError('option %s: invalid value: %r' % (opt, value))
return value
class AssignmentOption(Option):
# Define a new 'assignment' type for the '--define' command line option.
TYPES = Option.TYPES + ('assignment', 'protocol')
TYPE_CHECKER = Option.TYPE_CHECKER.copy()
TYPE_CHECKER['assignment'] = check_assignment
TYPE_CHECKER['protocol'] = check_protocol
# Define a new store action that parses 'assignment' values.
ACTIONS = Option.ACTIONS + ('store_dict',)
STORE_ACTIONS = Option.STORE_ACTIONS + ('store_dict',)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ('store_dict',)
def take_action(self, action, dest, opt, value, values, parser):
if action == "store_dict":
left, right = value.split("=")
values.ensure_value(dest, {})[left] = right
return
Option.take_action(self,
action,
dest,
opt,
value,
values,
parser)
# Define the command line syntax.
usage = '%prog [options] filename [hostname [hostname ...]]'
usage += '\nCopyright (C) 2007-2010 by Samuel Abels.'
parser = OptionParser(usage = usage,
version = __version__,
option_class = AssignmentOption)
parser.add_option('--account-pool',
dest = 'account_pool',
metavar = 'FILE',
help = '''
Reads the user/password combination from the given file
instead of prompting on the command line. The file may
also contain more than one user/password combination, in
which case the accounts are used round robin.
'''.strip())
parser.add_option('--connections', '-c',
dest = 'connections',
type = 'int',
metavar = 'NUM',
default = 1,
help = '''
Maximum number of concurrent connections.
NUM is a number between 1 and 20, default is 1.
'''.strip())
parser.add_option('--csv-hosts',
dest = 'csv_hosts',
metavar = 'FILE',
help = '''
Loads a list of hostnames and definitions from the given file.
The first line of the file must have the column headers in the
following syntax: "hostname [variable] [variable] ...", where
the fields are separated by tabs, "hostname" is the keyword
"hostname" and "variable" is a unique name under which the
column is accessed in the script.
The following lines contain the hostname in the first column,
and the values of the variables in the following columns.
'''.strip())
parser.add_option('--define', '-d',
dest = 'define',
type = 'assignment',
action = 'store_dict',
default = {},
metavar = 'PAIR',
help = '''
Defines a variable that is passed to the script.
PAIR has the following syntax: STRING=STRING.
'''.strip())
parser.add_option('--default-domain',
dest = 'default_domain',
metavar = 'STRING',
default = '',
help = '''
The IP domain name that is used if a given hostname has no domain appended.
'''.strip())
parser.add_option('--delete-logs',
dest = 'delete_logs',
action = 'store_true',
default = False,
help = 'Delete logs of successful operations when done.')
parser.add_option('--load-driver',
dest = 'load_driver',
metavar = 'FILE',
help = '''
A python file containing an Exscript driver class.
'''.strip())
parser.add_option('--execute', '-e',
dest = 'execute',
metavar = 'EXSCRIPT',
help = 'Interprets the given string as the script.')
parser.add_option('--hosts',
dest = 'hosts',
metavar = 'FILE',
help = '''
Loads a list of hostnames from the given file (one host per line).
'''.strip())
parser.add_option('--non-interactive', '-i',
dest = 'non_interactive',
action = 'store_true',
default = False,
help = '''
Do not ask for a username or password, but still try to authenticate.
May be used if the login credentials are passed as part of a URI formatted
hostname.
'''.strip())
parser.add_option('--logdir', '-l',
dest = 'logdir',
metavar = 'DIR',
help = '''
Logs any communication into the directory with the given name.
Each filename consists of the hostname with ".log" appended.
Errors are written to a separate file, where the filename
consists of the hostname with ".log.error" appended.
'''.strip())
parser.add_option('--no-authentication', '-n',
dest = 'no_authentication',
action = 'store_true',
default = False,
help = '''
When given, the automatic authentication procedure is skipped. Implies -i.
'''.strip())
parser.add_option('--authorization',
dest = 'authorization',
action = 'store_true',
default = False,
help = '''
Ask for an authorization password in addition to the authentication password.
'''.strip())
parser.add_option('--no-auto-logout',
dest = 'no_auto_logout',
action = 'store_true',
default = False,
help = '''
Do not attempt to execute the exit or quit command at the end of a script.
'''.strip())
parser.add_option('--no-prompt',
dest = 'no_prompt',
action = 'store_true',
default = False,
help = '''
Do not wait for a prompt anywhere (except during the authentication
procedure). Note that this will also cause Exscript to disable commands
that require a prompt, such as "extract".
'''.strip())
parser.add_option('--no-strip',
dest = 'no_strip',
action = 'store_true',
default = False,
help = 'Do not strip the first line of each response.')
parser.add_option('--overwrite-logs',
dest = 'overwrite_logs',
action = 'store_true',
default = False,
help = '''
Instructs Exscript to overwrite existing logfiles. The default
is to append the output if a log already exists.
'''.strip())
protocols = protocol_map.keys()
protocols.sort()
parser.add_option('--protocol', '-p',
dest = 'protocol',
type = 'protocol',
metavar = 'STRING',
default = 'telnet',
help = '''
Specify which protocol to use to connect to the remote host.
Allowed values for STRING include: %s.
The default protocol is telnet.
'''.strip() % ', '.join(protocols))
parser.add_option('--retry',
dest = 'retry',
type = 'int',
metavar = 'NUM',
default = 0,
help = '''
Defines the number of retries per host on failure. Default is 0.
'''.strip())
parser.add_option('--retry-login',
dest = 'retry_login',
type = 'int',
metavar = 'NUM',
default = 0,
help = '''
Defines the number of retries per host on login failure. Default is 0.
'''.strip())
parser.add_option('--sleep',
dest = 'sleep',
metavar = 'TIME',
default = '',
help = '''
Waits for the specified time before running the script.
TIME is a timespec as specified by the 'sleep' Unix command.
'''.strip())
parser.add_option('--ssh-auto-verify',
dest = 'ssh_auto_verify',
action = 'store_true',
default = False,
help = '''
Automatically confirms the 'Host key changed' SSH error
message with 'yes'. Highly insecure and not recommended.
'''.strip())
parser.add_option('--ssh-key',
dest = 'ssh_key',
metavar = 'FILE',
help = '''
Specify a key file that is passed to the SSH client.
This is equivalent to using the "-i" parameter of the
openssh command line client.
'''.strip())
parser.add_option('--verbose', '-v',
dest = 'verbose',
type = 'int',
metavar = 'NUM',
default = 1,
help = '''
Print out debug information about the queue.
NUM is a number between 0 (min) and 5 (max). Default is 1.
'''.strip())
parser.add_option('--parser-verbose', '-V',
dest = 'parser_verbose',
type = 'int',
metavar = 'NUM',
default = 0,
help = '''
Print out debug information about the Exscript template parser.
NUM is a number between 0 (min) and 5 (max). Default is 0.
'''.strip())
parser.add_option('--protocol-verbose',
dest = 'protocol_verbose',
type = 'int',
metavar = 'NUM',
default = 0,
help = '''
Print out debug information about the network activity.
NUM is a number between 0 (min) and 5 (max). Default is 1.
'''.strip())
if __name__ == '__main__':
SigIntWatcher()
failed = run()
if failed != 0:
sys.exit('error: %d actions failed.' % failed)