-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.py
741 lines (526 loc) · 20.4 KB
/
functions.py
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
from settings import *
from datetime import datetime
from blessed import Terminal
import os
import subprocess
import spur
import socket
import sys
import time
import shutil
import random
# https://blessed.readthedocs.io/en/latest/colors.html
col = Terminal()
return_code = {
'0': 'Success',
'1': 'Catchall for general errors',
'2': 'Misuse of shell builtins',
'100': 'Access denied',
'126': 'Command invoked cannot execute',
'127': 'Command not found',
'128': 'Invalid argument to exit',
}
# Date and time for log function
def TimeDate():
dateandtime = datetime.now()
date_time = dateandtime.strftime('%Y-%m-%d %H:%M:%S')
return str(date_time)
def CreateClientLogLocation(location):
if write_client_log == True:
if not os.path.exists(location):
os.mkdir(location)
# Write log message to specified log file
def WriteMasterLog(logmessage):
try:
with open(masterlogfile, 'a+') as log:
log.write(TimeDate() + ': ' + str(logmessage) + '\n')
except:
print(col.red1 + 'Error: Cant write to log' + col.normal)
# Write to specified error log
def WriteErrorLog(logmessage):
try:
with open(errorlogfile, 'a+') as log:
log.write(TimeDate() + ': ' + str(logmessage) + '\n')
except:
print(col.red1 + 'Error: Cant write to log' + col.normal)
# Write log message to specified log file
def WriteClientLog(client, logmessage):
location = clientloglocation
if location[-1] != '/':
location += '/'
try:
with open(location + client + '.log', 'a+') as log:
log.write(TimeDate() + ': ' + str(logmessage) + '\n')
except:
print(col.red1 + 'Error: Cant write to log' + col.normal)
## Clear screen
def ClearScreen():
os.system('clear')
## Check client response on ssh port
def CheckClient(address, port):
client_response = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_response.settimeout(0.5)
host = address
address = (host, int(port))
try:
result = client_response.connect_ex(address)
if result == 0:
return True
else:
return False
except:
print(col.red1 + 'Error: Cant do host lookup @' + str(host) + '. No entry in hosts file?' + col.normal)
if write_master_log == True:
WriteMasterLog(str(host) + ': Error: Cant do host lookup @' + str(host) + '. No entry in hosts file?')
if write_error_log == True:
WriteErrorLog(str(host) + ': Error: Cant do host lookup @' + str(host) + '. No entry in hosts file?')
if write_client_log == True:
WriteClientLog(str(host), 'Error: Cant do host lookup @' + str(host) + '. No entry in hosts file?')
## Status of the specified clients
def ClientStatus(group):
clients = GetClients(group)
ClearScreen()
print('')
print(col.bold_white('Client'), col.move_x(35), col.bold_white('Status'))
print (col.bold_snow4('-') * 42)
for client in clients:
client = client.split(' ')
name = client[0]
ip = client[1]
if len(client) > 2:
port = client[2]
else:
port = 22
if use_hostname == True:
client = client[0]
else:
client = client[1]
if CheckClient(client, port) == True:
print(col.yellow1(client), col.move_x(35), col.green2('Online'))
else:
print(col.yellow1(client), col.move_x(35), col.blink_red1('Offline'))
print ('')
## Runs the ClientStatus Ticker
def ClientStatusTicker(group):
while True:
ClientStatus(group)
time.sleep(ticker_intervall)
## Collect Files
def CollectFiles(path):
files = []
if os.path.isdir(path):
for r, d, f in os.walk(path):
for file in f:
files.append(os.path.join(r, file))
return files
else:
print(col.red1('Error: Cant collect groups and recipes from specified directory'))
if write_master_log == True:
WriteMasterLog('Error: Cant collect groups and recipes from specified directory')
if write_error_log == True:
WriteErrorLog('Error: Cant collect groups and recipes from specified directory')
## String cleanup
def CleanString(string):
string = string.replace("\\n'", '').replace('b\'', '')
string = string.strip()
return string
## Read group and recipe files
def ReadFile(file):
content = []
try:
with open(file) as file:
for row in file:
content.append(CleanString(row))
return content
except:
print(col.red1 + 'Error: Cant open file ' + str(file) + col.normal)
if write_master_log == True:
WriteMasterLog('Error: Cant open file ' + str(file))
if write_error_log == True:
WriteErrorLog('Error: Cant open file ' + str(file))
## Get the working directory of MassCTRL ## UNUSED ##
def WorkingDirectory():
dirpath = os.getcwd()
return str(dirpath)
## Return date and time to log file
def TimeDate():
dateandtime = datetime.now()
date_time = dateandtime.strftime('%Y-%m-%d %H:%M:%S')
return str(date_time)
## Executes the command on client
def SshExecute(host, port, user, passwd, string):
command = ['sh', '-c']
string = string.split(command_delimiter)
command.extend(string)
if missing_host_key_accept == True:
shell = spur.SshShell(hostname=host, port=port, username=user, password=passwd, missing_host_key=spur.ssh.MissingHostKey.accept)
elif private_key_login == True:
shell = spur.SshShell(hostname=host, port=port, username=user)
else:
shell = spur.SshShell(hostname=host, port=port, username=user, password=passwd)
try:
with shell:
result = shell.run(command, allow_error=True)
command = ', '.join(command)
command = command.replace('sh, -c, ','')
passwd = ''
if command_output == True:
print('Executing command: ' + col.steelblue1 + command + col.normal + ' with result:')
if exec_output == True:
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
print(CleanString(str(result.output, 'utf-8')))
if return_code_output == True:
print('Execution ' + FormatReturnCode(str(result.to_error())))
if write_master_log == True:
WriteMasterLog(host + ': Executing command: ' + command + ' with result:')
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
outputssh = CleanString(str(result.output, 'utf-8'))
outputssh = outputssh.split('\n')
for row in outputssh:
WriteMasterLog(host + ': ' + row)
WriteMasterLog(host + ': Execution ' + FormatReturnCodeLog(str(result.to_error())))
if write_client_log == True:
WriteClientLog(host, 'Executing command: ' + command + ' with result:')
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
outputssh = CleanString(str(result.output, 'utf-8'))
outputssh = outputssh.split('\n')
for row in outputssh:
WriteClientLog(host, row)
WriteClientLog(host, 'Execution ' + FormatReturnCodeLog(str(result.to_error())))
if write_error_log == True:
#print(result.to_error())
executiontest = FormatReturnCodeErrorLog(str(result.to_error()))
if executiontest != '0':
WriteErrorLog(host + ': Execution of command ' + command + ' failed with return code ' + executiontest)
except Exception as e:
print(e)
e = str(e).split('\n')
passwd = ''
print(col.red1 + 'Error: Cant connect to client ' + host)
for error in e:
print(str(error))
print(col.normal)
if write_master_log == True:
WriteMasterLog(host + ': Error: Cant connect to client ' + host)
for error in e:
WriteMasterLog(host + ': ' + error)
if write_client_log == True:
WriteClientLog(host, 'Error: Cant connect to client ' + host)
for error in e:
WriteClientLog(host, error)
if write_error_log == True:
WriteErrorLog('Error: Cant connect to client ' + host)
for error in e:
WriteErrorLog(host + ': ' + error)
## Executes the command locally
def LocalExecute(string):
command = ['sh', '-c']
string = string.split(command_delimiter)
command.extend(string)
shell = spur.LocalShell()
try:
with shell:
result = shell.run(command, allow_error=True)
command = ', '.join(command)
command = command.replace('sh, -c, ','')
if command_output == True:
print('Executing local command: ' + col.tan1 + command + col.normal + ' with result:')
if exec_output == True:
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
print(CleanString(str(result.output, 'utf-8')))
if return_code_output == True:
print('Execution ' + FormatReturnCode(str(result.to_error())))
if write_master_log == True:
WriteMasterLog('Executing local command: ' + command + ' with result:')
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
outputlocal = CleanString(str(result.output, 'utf-8'))
outputlocal = outputlocal.split('\n')
for row in outputlocal:
WriteMasterLog(row)
WriteMasterLog('Execution ' + FormatReturnCodeLog(str(result.to_error())))
if write_client_log == True:
WriteClientLog('Local', 'Executing local command: ' + command + ' with result:')
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
outputlocal = CleanString(str(result.output, 'utf-8'))
outputlocal = outputlocal.split('\n')
for row in outputlocal:
WriteClientLog('local', row)
WriteClientLog('Local', 'Execution ' + FormatReturnCodeLog(str(result.to_error())))
if write_error_log == True:
executiontest = FormatReturnCodeErrorLog(str(result.to_error()))
if executiontest != '0':
WriteErrorLog('Local Execution of command ' + command + ' failed with return code ' + executiontest)
except:
print(col.red1 + 'Error: Cant execute command' + col.normal)
if write_master_log == True:
WriteMasterLog('Local: Error: Cant execute command')
if write_client_log == True:
WriteClientLog('Local', 'Error: Cant execute command')
if write_error_log == True:
WriteErrorLog('Local: Error: Cant execute command')
## Main function for executing remote commands
def ExecCommand(group, recipe):
#ClearScreen()
clients = GetClients(group)
recipe = GetRecipe(recipe)
local_validator = ''
if recipe != []:
for client in clients:
client = client.split(' ')
name = client[0]
ip = client[1]
if len(client) > 2:
port = client[2]
else:
port = 22
if use_hostname == True:
client = client[0]
else:
client = client[1]
if client_headline == True:
print(col.bold_yellow1(client) + '\n' + (col.darkgray('=') * len(client)))
if CheckClient(client, port) == True:
user, passwd = GetCredentials(client)
try:
for ingredient in recipe:
ingredient = ingredient.split(':')
if ingredient[0] == str('EXEC'):
ingredient = str(ingredient[1])
SshExecute(client, port, user, passwd, ingredient)
elif ingredient[0] == str('LOCAL'):
ingredient = str(ingredient[1])
if local_validator != ingredient:
LocalExecute(ingredient)
local_validator = ingredient
elif ingredient[0] == str('PUT'):
ingredient = str(ingredient[1])
ingredient = ingredient.split(' ')
source = str(ingredient[0])
dest = str(ingredient[1])
FileOperation(client, port, user, passwd, source, dest, 'put')
elif ingredient[0] == str('GET'):
ingredient = str(ingredient[1])
ingredient = ingredient.split(' ')
source = str(ingredient[0])
dest = str(ingredient[1])
FileOperation(client, port, user, passwd, source, dest, 'get')
print('-' * 30)
passwd = ''
except Exception as error:
print(str(error))
passwd = ''
else:
passwd = ''
print(col.red1 + 'Client: ' + str(client) + ' does not respond' + col.normal)
print('-' * 30)
if write_master_log == True:
WriteMasterLog(str(client) + ': Client: ' + str(client) + ' does not respond')
if write_client_log == True:
WriteClientLog(str(client), 'Client: ' + str(client) + ' does not respond')
if write_error_log == True:
WriteErrorLog(str(client) + ': Client: ' + str(client) + ' does not respond')
print('')
else:
print(col.red1 + 'Error: The recipe file has no ingredients' + col.normal)
if write_master_log == True:
WriteMasterLog(str(client) + ': Error: The recipe file has no ingredients')
if write_client_log == True:
WriteClientLog(str(client), + 'Error: The recipe file has no ingredients')
if write_error_log == True:
WriteErrorLog(str(client), + 'Error: The recipe file has no ingredients')
## Format the return code of executed command
def FormatReturnCode(returncode):
returncode = returncode.split('\n')
returncode = str(returncode[0])
returnnum = str(returncode).split(' ')
rc_message = return_code.get(str(returnnum[2]))
if rc_message is None:
rc_message = returnnum[2]
if str(returnnum[2]) == '0':
return (returncode + ' - ' + col.green2 + rc_message + col.normal)
else:
return (returncode + ' - ' + col.red1 + rc_message + col.normal)
def FormatReturnCodeLog(returncode):
returncode = returncode.split('\n')
returncode = str(returncode[0])
returnnum = str(returncode).split(' ')
rc_message = return_code.get(str(returnnum[2]))
if rc_message is None:
rc_message = returnnum[2]
if str(returnnum[2]) == '0':
return (returncode + ' - ' + rc_message)
else:
return (returncode + ' - ' + rc_message)
def FormatReturnCodeErrorLog(returncode):
returncode = returncode.split('\n')
returncode = str(returncode[0])
returnnum = str(returncode).split(' ')
rc_message = return_code.get(str(returnnum[2]))
if rc_message is None:
rc_message = returnnum[2]
return (str(returnnum[2]))
## Get login credentials from key file.
def GetCredentials(host):
if os.path.exists(keyfile):
user = ''
passwd = ''
content = ReadFile(keyfile)
if master_account == True:
for row in content:
if 'masteraccount' in str(row):
row = row.split(' ')
user = row[2]
passwd = row[3]
else:
for row in content:
if str(host) in str(row):
row = row.split(' ')
user = row[2]
passwd = row[3]
return user, passwd
else:
print(col.red1 + 'The keyfile ' + keyfile + ' does not exist' + col.normal)
WriteErrorLog('The keyfile ' + keyfile + ' does not exist')
sys.exit(1)
## Gets clients from group file
def GetClients(group):
hosts = []
groups = group.split(',')
location = groupfiles
if location[-1] != '/':
location = location + '/'
for group in groups:
if os.path.exists(location + group):
content = ReadFile(location + group)
for client in content:
if client != '' and client != '\n' and client[0] != '#':
hosts.append(client)
else:
print(col.red1 + 'The group ' + group + ' does not exist' + col.normal)
WriteErrorLog('The group ' + group + ' does not exist')
sys.exit(1)
return hosts
## Get commands from recipe file
def GetRecipe(recipe):
ingredients = []
recipes = str(recipe).split(',')
location = recipefiles
if location[-1] != '/':
location = location + '/'
for recipe in recipes:
if os.path.exists(location + recipe):
recipe = ReadFile(location + recipe)
for command in recipe:
if command != '' and command[0] != '#':
if 'EXEC:' in command or 'GET:' in command or 'PUT:' in command or 'LOCAL:' in command:
ingredients.append(command)
else:
print(col.red1 + 'The recipe file ' + recipe + ' is invalid and does not contain mandatory trigger commands' + col.normal)
if write_master_log == True:
WriteMasterLog('The recipe file ' + recipe + ' is invalid and does not contain mandatory trigger commands')
if write_error_log == True:
WriteErrorLog('The recipe file ' + recipe + ' is invalid and does not contain mandatory trigger commands')
sys.exit(1)
else:
continue
else:
print(col.red1 + 'The recipe ' + recipe + ' does not exist' + col.normal)
if write_master_log == True:
WriteMasterLog('The recipe ' + recipe + ' does not exist')
if write_error_log == True:
WriteErrorLog('The recipe ' + recipe + ' does not exist')
sys.exit(1)
return ingredients
## Show a list of groups and recipes
def InventoryList():
if os.path.exists(groupfiles):
grplocation = groupfiles
if grplocation[-1] != '/':
grplocation = grplocation + '/'
print(col.bold_green3('\nGroups:'))
print(col.bold_snow4('-' * 20))
groups = CollectFiles(grplocation)
groups.sort()
for entry in groups:
print(entry.replace(grplocation, ''))
print('')
else:
print(col.red1 + 'Error: Group directory ' + grplocation + ' does not exist' + col.normal)
sys.exit(1)
if os.path.exists(recipefiles):
reclocation = recipefiles
if reclocation[-1] != '/':
reclocation = reclocation + '/'
print(col.bold_green3('\nRecipes:'))
print(col.bold_snow4('-' * 20))
recipes = CollectFiles(reclocation)
recipes.sort()
for entry in recipes:
print(entry.replace(reclocation, ''))
else:
print(col.red1 + 'Error: Recipe directory ' + reclocation + ' does not exist' + col.normal)
if write_error_log == True:
WriteErrorLog('Error: Recipe directory ' + reclocation + ' does not exist' + col.normal)
sys.exit(1)
print('')
## Function to handle file transfers
def FileOperation(host, port, user, passwd, source, dest, direction):
command = ['sh', '-c']
if missing_host_key_accept == True:
if direction == 'put':
scp_command = ['sshpass -p ' + "'" + passwd + "'" + ' scp -o StrictHostKeyChecking=no -v -P ' + str(port) + ' -p ' + source + ' ' +user + '@' + host + ':' + dest]
elif direction == 'get':
scp_command = ['sshpass -p ' + "'" + passwd + "'" + ' scp -o StrictHostKeyChecking=no -v -P ' + str(port) + ' -p ' + user + '@' + host + ':' + source + ' ' + dest]
else:
if direction == 'put':
scp_command = ['scp -v -P ' + str(port) + ' -p ' + source + ' ' +user + '@' + host + ':' + dest]
elif direction == 'get':
scp_command = ['scp -v -P ' + str(port) + ' -p ' + user + '@' + host + ':' + dest + ' ' + source]
command.extend(scp_command)
shell = spur.LocalShell()
if command_output == True and direction == 'put':
print('Sending file: ' + col.yellow1 + source + col.normal + ' to remote: ' + col.orange + dest + col.normal)
if write_master_log == True:
WriteMasterLog(host + ': Sending file ' + source + ' -> ' + dest)
if write_client_log == True:
WriteClientLog(host, ': Sending file ' + source + ' -> ' + dest)
elif command_output == True and direction == 'get':
print('Receiving file: ' + col.yellow1 + source + col.normal + ' from remote: ' + col.orange + dest + col.normal)
if write_master_log == True:
WriteMasterLog(host + ': Receiving file ' + source + ' from remote: ' + dest)
if write_client_log == True:
WriteClientLog(host, ': Receiving file ' + source + ' from remote: ' + dest)
try:
with shell:
result = shell.run(command)
passwd = ''
filename = source.rsplit('/', 1)[-1]
if exec_output == True:
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
print(CleanString(str(result.output, 'utf-8')))
if return_code_output == True:
print('Execution ' + FormatReturnCode(str(result.to_error())))
if get_file_rename == True and direction == 'get' and os.path.exists(dest + filename):
shutil.move(dest + filename, dest + host + '_' + filename)
if write_master_log == True:
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
WriteMasterLog(host + ': ' + CleanString(str(result.output, 'utf-8')))
WriteMasterLog(host + ': ' + 'Execution ' + FormatReturnCodeLog(str(result.to_error())))
if write_client_log == True:
WriteClientLog(host, direction + ' ' + source + ' -> ' + dest)
if CleanString(str(result.output, 'utf-8')) != '' and CleanString(str(result.output, 'utf-8')) != '\n':
WriteClientLog(host, CleanString(str(result.output, 'utf-8')))
WriteClientLog(host, 'Execution ' + FormatReturnCodeLog(str(result.to_error())))
if write_error_log == True:
executiontest = FormatReturnCodeErrorLog(str(result.to_error()))
if executiontest != '0':
WriteErrorLog(host + ': Execution of file transfer failed')
except:
passwd = ''
print(col.red1 + 'Error: I probably couldnt find the requested file or directory @' + host + col.normal)
if write_master_log == True:
WriteMasterLog(host + ': Error: I probably couldnt find the requested file or directory @' + host)
if write_client_log == True:
WriteClientLog(host, 'Error: I probably couldnt find the requested file or directory @' + host)
if write_error_log == True:
WriteErrorLog(host + ': Error: I probably couldnt find the requested file or directory @' + host)