-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpentester_toolchain.py
More file actions
640 lines (564 loc) · 29.2 KB
/
pentester_toolchain.py
File metadata and controls
640 lines (564 loc) · 29.2 KB
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
# pylint: disable=R1719,W0106
"""
This tool may be used for legal purposes only.
Users take full responsibility for any actions performed using this tool.
The author accepts no liability for damage caused by this tool.
If these terms are not acceptable to you, then do not use this tool.
Built-in modules
"""
import logging
import re
import sys
import threading
import time
from logging.config import dictConfig
from logging.handlers import QueueHandler
from multiprocessing import cpu_count, Process, Queue
from pathlib import Path
# Custom Modules #
from Modules.tcp_handlers import ftp_handler, ssh_handler, telnet_handler, smtp_handler, \
whois_handler, finger_handler, web_handler, pop3_handler, \
ident_handler, nntp_handler, imap_handler, smux_handler, \
checkpoint_firewall_handler, smb_handler, modbus_handler, \
rlogin_handler, rsh_handler, apple_filing_handler, rtsp_handler, \
cups_handler, rsync_handler, java_rmi_handler, mssql_handler, \
oracle_db_handler, oracle_xmldb_handler, docker_handler, \
squid_handler, iscsi_handler, sap_router_handler, sql_handler, \
rdp_handler, distcc_handler, subversion_handler, epmd_handler, \
cisco_smart_install_handler, postgresql_handler, \
redshift_handler, vnc_handler, x11_handler, redis_handler, \
winrm_handler, apache_jserv_handler, influxdb_handler, \
bitcoin_handler, apache_casandra_handler, raw_printing_handler, \
elastic_search_handler, ndmp_handler, memcache_handler, \
gluster_fs_handler, mongo_db_handler, hadoop_handler
from Modules.tcp_udp_handlers import dns_handler, irc_handler, kerberos_handler, rpc_handler, \
ntp_handler, msrpc_handler, netbios_handler, snmp_handler, \
ldap_handler, ipsec_ike_vpn_handler, ipmi_handler, \
socks_proxy, nfs_handler, rabbit_mq_handler, couchdb_handler, \
ethernet_ip_handler
from Modules.udp_handlers import dhcp_handler, tftp_handler, ruserd_handler, ws_discovery_handler, \
mdns_handler, bacnet_handler
from Modules.utils import cmd_parser, ConfigClass, config_input, file_handler, logger_config, \
markdown_formatter, print_err, RegexHandler, system_cmd
def nmap_handler(hostname: str, nmap_path: Path, config: object, re_obj: object, log_tuple: tuple):
"""
Command execution function for nmap initial probing scans.
:param hostname: The hostname to be parsed into commands.
:param nmap_path: The path to the nmap output file.
:param config: Program configuration instance.
:param re_obj: Compiled regex instance.
:param log_tuple: Tuple containing console and scan_process loggers.
:return: Nothing
"""
# Iterate through adb commands from yaml file #
for command in config.nmap_init:
# Check to see if command has delimiter to parse #
args = [True if delimiter in command else False for delimiter in config.delimiters]
# If args are to be parsed in command #
if True in args:
# Parse in args and split into list #
command = cmd_parser(command, re_obj, hostname)
# Split command into list to grab name #
cmd_list = command.split()
log_tuple[0].log(logging.INFO, '[+] Executing %s on %s', cmd_list[0], hostname)
# Execute system command #
output = system_cmd(command, None, config, log_tuple[1])
# If the command return data #
if output:
data = f'>> {command}\n{"*" * (len(command) + 4)}\n{output.decode()}\n\n\n'
# Write the output with command title to service file #
file_handler(nmap_path, 'a', log_tuple[1], data=data)
def resolver(target_host: str, regex_obj: object, configs_obj: object, outs_scan: tuple,
resolver_path: Path):
"""
Takes the passed in IP or domain hosts and resolves it using the hosts command. If successful,
the IP and the domain will be returned. On failures, the passed in IP or domain will be
assigned as both.
:param target_host: The target to resolve, either IP address or domain.
:param regex_obj: The compiled regex instance.
:param configs_obj: The program configuration instance.
:param outs_scan: Tuple containing the output and scan process loggers.
:param resolver_path: The path to the file where the host commands output will go.
:return: The IP address and domain in a tuple grouping.
"""
# Execute host command on target to lookup ip address or domain depending on input #
output = system_cmd(f'host {target_host}', None, configs_obj, outs_scan[1])
# If ip/domain resolution was successful #
if output:
# Write the output to a file #
file_handler(resolver_path, 'wb', outs_scan[1], data=output)
# If passed in target is ip address #
if re.search(regex_obj.re_ip, target_host):
# Attempt to parse out resolved domain name with regex #
domain_parse = re.search(regex_obj.re_domain_parse, output.decode())
# If regex failed to parse resolved domain name #
if not domain_parse:
# Attempt to run scan with ip and domain the same (some scans will likely fail) #
target_ip = target_domain = target_host
# If resolved domain was parsed by regex #
else:
target_ip = target_host
target_domain = domain_parse.group(0)
# If passed in target is domain name #
else:
# Attempt to parse out resolved ip address with regex #
ip_parse = re.search(regex_obj.re_ip_parse, output.decode())
# If regex failed to parse resolved ip address #
if not ip_parse:
# Attempt to run scan with ip and domain the same (some scans will likely fail) #
target_ip = target_domain = target_host
# If resolved ip address was parsed by regex #
else:
target_ip = ip_parse.group(0)
target_domain = target_ip
# If ip/domain resolution was not successful #
else:
# Attempt to run scan with ip and domain the same (some scans will likely fail) #
target_ip = target_domain = target_host
return target_ip, target_domain
def scan_process(target_host: str, regex_obj: object, base_path: Path, configs_obj: object,
scanner: object, logger_queue: Queue):
"""
Begins by setting up process logging facilities, file paths, and directories. If there are no
specified ports in config file, nmap scans will be skipped assuming the ports have already been
enumerated. Otherwise, an initial nmap scan is run, followed by corresponding tool chains
configured based on regex matching of open ports, finishing with a full nmap scan checking all
ports.
:param target_host: The IP address or domain name of the targ to be scanned.
:param regex_obj: The compiled regex instance.
:param base_path: Path to the base directory for the project output.
:param configs_obj: The program configuration instance from loaded yaml file.
:param scanner: The program scan process service function class.
:param logger_queue: The queue used for handling inter-process logging.
:return: Nothing
"""
# Get the root logging instance to add queue handlers #
root_logg = logging.getLogger()
# Set the logging to debug #
root_logg.setLevel(logging.DEBUG)
# If the root logger does not a handler set #
if not root_logg.hasHandlers():
# Add queue handler to root logger #
root_logg.addHandler(QueueHandler(logger_queue))
# Get logging instance for output #
out_logger = logging.getLogger('output')
# Get logging instance for log file errors #
scan_logger = logging.getLogger('scan')
# Tuple grouping for output & error loggers #
outs_scan = (out_logger, scan_logger)
# Set file paths for target directory and nmap scans #
host_path = base_path / target_host
resolver_path = host_path / 'resolver_out.txt'
tcp_path = host_path / 'TCP_Handlers'
udp_path = host_path / 'UDP_Handlers'
tcp_udp_path = host_path / 'TCP_UDP_Handlers'
scan_dirs = (host_path, tcp_path, udp_path, tcp_udp_path)
# Iterate through program directory paths and create them #
[path.mkdir(parents=True, exist_ok=True) for path in scan_dirs]
# Attempt to resolve the IP/domain depending on whether IP/domain is passed in #
target_ip, target_domain = resolver(target_host, regex_obj, configs_obj, outs_scan,
resolver_path)
# If there were no ports specified in config instance #
if not configs_obj.ports:
# Set the nmap paths #
nmap_path = host_path / 'Nmap'
nmap_start = nmap_path / 'nmap_init.txt'
nmap_end = nmap_path / 'nmap_full.txt'
# Create the nmap directory #
nmap_path.mkdir(parents=True, exist_ok=True)
outs_scan[0].log(logging.INFO, '[+] Starting initial nmap scan for %s:%s',
target_domain, target_ip)
# Execute the initial nmap probing scans #
nmap_handler(target_ip, nmap_start, configs_obj, regex_obj, outs_scan)
# Read the nmap probe scans output data #
scan_data = file_handler(nmap_start, 'r', outs_scan[1])
# If nmap scans failed to produce output #
if not scan_data:
# Print error, log, and exit #
print_err(f'Initial nmap scan returned no data on {target_domain}:{target_ip}',
is_locked=True)
outs_scan[1].log(logging.ERROR, 'Initial nmap scan returned no data on %s:%s',
target_domain, target_ip)
sys.exit(4)
outs_scan[0].log(logging.INFO, '[!] Initial nmap scan for %s:%s completed',
target_domain, target_ip)
# Set error code for if not properly referenced in loop #
scan_port = '-1'
# Run regex operations on port scan output to find open ports #
re_searches = regex_obj.scan_parse(scan_data)
outs_scan[0].log(logging.INFO, '[+] Executing command toolchains on %s:%s',
target_domain, target_ip)
# Iterate through the regex result from port scan #
for key, value in re_searches.items():
# If the regex pattern matched #
if value:
# Iterate through split key port list #
for port in key.split(','):
# If current port found in match #
if port in value.group(0):
outs_scan[0].log(logging.INFO, '[+] Port %s matched on %s:%s', port,
target_domain, target_ip)
# Assign as scan port & exit loop #
scan_port = port
break
# If the scan port was not found #
if scan_port == '-1':
# Print error, log, and exit #
print_err(f'Port in {key} was not found in {value}', is_locked=True)
outs_scan[1].log(logging.ERROR, 'Port in %s was not found in %s', key, value)
sys.exit(4)
try:
# Execute service handler function #
scanner.service_handler[key](scan_dirs, configs_obj, regex_obj, outs_scan,
[target_ip, target_domain, int(scan_port)])
# If a key is passed in that does not exist #
except (KeyError, ValueError) as exec_err:
# Print error, log, and exit #
print_err('Attempting to access non-existent key in ScanClass func_dict or'
f'error converting port to int: {exec_err}', is_locked=True)
outs_scan[1].log(logging.ERROR, 'Attempting to access non-existent key in'
'ScanClass func_dict or error converting port '
'to int: %s', exec_err)
sys.exit(5)
outs_scan[0].log(logging.INFO, '[+] Starting final nmap scan for %s:%s',
target_domain, target_ip)
# Check and parse the yaml command #
cmd = cmd_parser(configs_obj.nmap_final, regex_obj, target_ip)
# Run final nmap scan on all uncommon ports #
scan_data = system_cmd(cmd, None, configs_obj, outs_scan[1])
# If the final nmap scan was successful #
if scan_data:
outs_scan[0].log(logging.INFO, '[!] Final nmap scan for %s:%s completed',
target_domain, target_ip)
# Write nmap data to output file #
file_handler(nmap_end, 'w', outs_scan[1], data=f'>> nmap final scan\n{"*" * 19}\n'
f'{scan_data.decode()}')
# If error occurred during final nmap scan #
else:
# Print error and log #
print_err(f'Error occurred on final nmap scan for {target_domain}:{target_ip}',
is_locked=True)
outs_scan[1].log(logging.ERROR, 'Error occurred on final nmap scan for %s:%s',
target_domain, target_ip)
# If ports already were identified on target #
else:
outs_scan[0].log(logging.INFO, '[+] Executing command toolchains on %s:%s',
target_domain, target_ip)
# Iterate through port list from yaml config #
for port in configs_obj.ports:
# Ensure port is string format #
str_port = str(port)
# If the converted string port is not a base10 decimal #
if not str_port.isdigit():
# Log error and move to next port #
outs_scan[1].log(logging.ERROR, 'Port \"%s\" in yaml file is not of base10 decimal'
' format', str_port)
continue
# Iterate through service dict items #
for key, _ in scanner.service_handler.items():
# If the port is detected the current key #
if str_port in key:
# Iterate through the ports in the key #
for key_port in key.split(','):
# If the target port matches a port in the key #
if str_port == key_port:
outs_scan[0].log(logging.INFO, '[+] Executing port %s on %s:%s',
str_port, target_domain, target_ip)
try:
# Execute service handler function #
scanner.service_handler[key](scan_dirs, configs_obj, regex_obj,
outs_scan, [target_ip, target_domain,
port])
# If a key is passed in that does not exist #
except KeyError as exec_err:
# Print error, log, and exit #
print_err(f'Attempting to access non-existent key in ScanClass func'
f'_dict: {exec_err}', is_locked=True)
outs_scan[1].log(logging.ERROR, 'Attempting to access non-existent '
'key inScanClass func_dict: %s',
exec_err)
sys.exit(5)
outs_scan[0].log(logging.INFO, '[!] Toolchain execution complete for %s:%s',
target_domain, target_ip)
class ScanClass:
"""
The scan process service handler class, which maps the ports of interest to their associated
service handler function to later be referenced for execution.
"""
service_handler = {
# TCP handler functions #
'20,21': ftp_handler,
'22': ssh_handler,
'23': telnet_handler,
'25,465,587,2525': smtp_handler,
'43': whois_handler,
'79': finger_handler,
'80,443,8080,8443': web_handler,
'110,995': pop3_handler,
'113': ident_handler,
'119,433': nntp_handler,
'143,993': imap_handler,
'199': smux_handler,
'264': checkpoint_firewall_handler,
'445': smb_handler,
'502': modbus_handler,
'513': rlogin_handler,
'514': rsh_handler,
'548': apple_filing_handler,
'554': rtsp_handler,
'631': cups_handler,
'873': rsync_handler,
'1050,1098,1099': java_rmi_handler,
'1433': mssql_handler,
'1521': oracle_db_handler,
'2100': oracle_xmldb_handler,
'2375,2376': docker_handler,
'3128': squid_handler,
'3260': iscsi_handler,
'3299': sap_router_handler,
'3306': sql_handler,
'3389': rdp_handler,
'3632': distcc_handler,
'3690': subversion_handler,
'4369': epmd_handler,
'4786': cisco_smart_install_handler,
'5432,5433': postgresql_handler,
'5439': redshift_handler,
'5800,5900': vnc_handler,
'5985,5986': winrm_handler,
'6000': x11_handler,
'6379': redis_handler,
'8009': apache_jserv_handler,
'8086': influxdb_handler,
'8333,18333,18444,38333': bitcoin_handler,
'9042,9160': apache_casandra_handler,
'9100': raw_printing_handler,
'9200': elastic_search_handler,
'10000': ndmp_handler,
'11210': memcache_handler,
'24007,24008,24009,49152': gluster_fs_handler,
'27017,27018': mongo_db_handler,
'50030,50060,50070,50075,50090': hadoop_handler,
# UDP handler functions #
'67': dhcp_handler,
'69': tftp_handler,
'1026': ruserd_handler,
'3702': ws_discovery_handler,
'5353': mdns_handler,
'47808': bacnet_handler,
# TCP/UDP handler functions #
'53': dns_handler,
'88': kerberos_handler,
'111': rpc_handler,
'123': ntp_handler,
'135': msrpc_handler,
'137,138,139': netbios_handler,
'161,162,10161,10162': snmp_handler,
'194,529,6667': irc_handler,
'389,636,3268,3269': ldap_handler,
'500,1723': ipsec_ike_vpn_handler,
'623': ipmi_handler,
'1080': socks_proxy,
'2049': nfs_handler,
'5671,5672': rabbit_mq_handler,
'5984,6984': couchdb_handler,
'44818': ethernet_ip_handler
}
def proc_alloc(hosts: Queue, count: int, re_obj: object, output_dir: Path, config_obj: object,
scan_obj: object, proc_list: list, num_cpu: int):
"""
Allocates scan process, adds to process list, and updates associated counter variables.
:param hosts: Queue of host IP addresses/domains to scan.
:param count: The current number of scan processes.
:param re_obj: The compiled regex instance.
:param output_dir: The path to the resulting scan process output directory.
:param config_obj: The program configuration instance.
:param scan_obj: The scan service handler instance.
:param proc_list: The scan process list.
:param num_cpu: The number of available CPU's.
:return: Tuple grouping of scan process list, number of available CPU's and scan process count
after process allocation.
"""
# Create scan process with next available host #
process = Process(target=scan_process, name=f'scanner{count}',
args=(hosts.get(), re_obj, output_dir, config_obj, scan_obj, log_queue))
# Start process and put in process list #
process.start()
proc_list.append(process)
num_cpu -= 1
count += 1
return proc_list, num_cpu, count
def main():
"""
Loads the config file, depending on config file settings, either runs ping scan to identify
hosts or already has target host in config file, and launches the scan process on target hosts
based on the available number of cpu's.
:return: Nothing
"""
hosts = Queue()
proc_list = []
# Get the current working directory #
cwd = Path.cwd()
# Format the output directory #
out_dir = cwd / 'Output'
# Create the output dir #
out_dir.mkdir(parents=True, exist_ok=True)
# Compile program regex and return as instance #
re_obj = RegexHandler()
# If potential yaml config file passed into to program #
if len(sys.argv) > 1:
# Format passed in argument as path #
config_path = cwd / 'Configs' / sys.argv[1]
# If the passed in configuration file does not exist or is not a yaml file #
if not config_path.exists() or not str(config_path).endswith('yml'):
# Prompt user for yaml config file #
config_path = config_input(cwd)
# If no args were passed in #
else:
# Prompt user for yaml config file #
config_path = config_input(cwd)
# Load the YAML configuration file #
config_data = file_handler(config_path, 'r', root_logger, yaml=True)
# Parse config data into class #
config_obj = ConfigClass(cwd, config_data)
# If specific target hosts are already specified #
if config_obj.hosts:
# Iterate through hosts and put in host queue if they are ip addresses or domains #
[hosts.put(host) for host in config_obj.hosts if re.search(re_obj.re_ip, host)
or re.search(re_obj.re_domain, host)]
# If CIDR network range is specified #
elif config_obj.cidr != 'null':
# If the provided cidr network in yaml is not properly formatted #
if not re.search(re_obj.re_cidr, config_obj.cidr):
print_err('Improper cidr network formatting in yaml config file')
sys.exit(2)
# Run ping scan on target CIDR #
ping_data = system_cmd(f'nmap -vv -sn -n {config_obj.cidr}', None, config_obj, root_logger)
# If the ping scan was successful #
if ping_data:
# Format ping output path #
ping_path = out_dir / 'ping_scan_out.txt'
# Write the output ping data saved to disk #
file_handler(ping_path, 'w', root_logger, data=f'>> nmap ping scan\n{"*" * 18}\n'
f'{ping_data.decode()}')
# If error occurred during ping scan #
else:
# Print error, log, and exit #
print_err('Initial nmap ping scan failed')
root_logger.log(logging.ERROR, 'Initial nmap ping scan failed')
sys.exit(2)
# Iterate through ping data line by line #
for line in ping_data.decode().split('\n'):
# If the current line does not indicate failure #
if not re.search(re_obj.re_ping_fail, line):
# Attempt to match IP in line #
ip_match = re.search(re_obj.re_ip, line)
# If an IP matched in line #
if ip_match:
# Put the matched IP address in hosts queue #
hosts.put(ip_match.group(0))
# If neither were specified causing error #
else:
print_err('Improper configuration file settings .. set either hosts or cidr range to ping')
sys.exit(2)
count = 1
line = f'+{"=" * 98}+'
# Initialize scan service function class #
scan_obj = ScanClass()
print(line)
print(r'''
.:oxxxdc,
.;xXMMMMMMMMMWO,
'oKMMMMMMWOxxOXMMMMO
.;::;'. .:kNMMMMMMKo' '0MMMK.
'o0MMMMMMMMKo.'o0MMMMMMWkc. kMMMN.
.:kNMMMMMMMWMMMMMMMMMMMMKd, oMMMW,
... 'oKMMMMMMWOc. .0MMMMMMWOc. cMMMW.
,dKWMMMWKx: .:kWMMMMMMKd, .XMMMMXd,'ck. dMMMx
.:kWMMMMMMMMMMMWxoKMMMMMMWk:. 0MMMW: :MMMW' dMMMx
'o0MMMMMMXd;'';oNMMMMMMMW0l' MMMMl cMMMW' cMMMW.
,xNWWWWWW0c. lWWWWWXx; . NWWWo oWWWk ;xNMMMN'
.. '.. ' ........ .......... '.. .'. .... .... . ..... . . . . kKl
. .c'.o.. c: ' .; :.. l. '. l.. o.: x ;. .;:. ',l ;. ;..c. ;l c.;, '
lXK .: l ' c; .; : o '. l o', x ,' .,;. '.l ;' ;. :.'.', c. .:'
.NMMX. . ... . ... .''... ....,... . .. .''..,''. .. ...'.'..,..
.WMMMN: cMMMM: .XMMMo .l0MMMMNMMMMN0kOKMMMMMXx;
lMMMM. ,WMMMo 'NMMd .:xNMMMMWkc..l0WMMMMMMNkc.
cMMMM .XMMMO..x, ;dKMMMMMKo' .',,..
XMMMk .'.0MMMMOoccoOWMMMMWk:.
.XMMMO 'oXMMc ;OMMMMMMMMMMKo,
0MMMK. ;xNMMMMNk. ,cdxxdl,.
OMMMX. .cOWMMMMXd,
xMMMN, 'oKMMMMM0l.
lWMMMXdlclkNMMMMWk:.
.oXMMMMMMMMMKo,
.;coooc,.
''')
print(line)
# Get the number of available cpu #
num_cpu = cpu_count()
# Allocate first scan process #
proc_list, num_cpu, count = proc_alloc(hosts, count, re_obj, out_dir, config_obj, scan_obj,
proc_list, num_cpu)
while True:
# Iterate through process list and remove completed processes #
[proc_list.remove(proc) for proc in proc_list if not proc.is_alive()]
# If all hosts have been scanned #
if hosts.empty() and not proc_list:
break
# Get the number of available cpu #
num_cpu = cpu_count()
# While there are cores available and hosts to scan #
while num_cpu > config_obj.min_cores and not hosts.empty():
# Allocation addition scan process #
proc_list, num_cpu, count = proc_alloc(hosts, count, re_obj, out_dir, config_obj,
scan_obj, proc_list, num_cpu)
# If markdown generate from output is set to True in config file #
if config_obj.markdown:
# Crawl through the Output director and copy text format to markdown #
markdown_formatter(out_dir, root_logger, re_obj)
print(line)
def log_handler(logger_queue: Queue):
"""
Logging thread that handles multiprocessing logging through the dedicated queue.
:param logger_queue: The logging queue used to pass messages to logging thread.
:return: Nothing
"""
while True:
# Get log message from queue and log to file #
log_message = logger_queue.get()
# Set the logger instance to log handler based on associated name #
logger = logging.getLogger(log_message.name)
# Handle the logging of the message based on name in config #
logger.handle(log_message)
if __name__ == '__main__':
# Get the logging config #
log_config = logger_config()
# Set the logging config based on retrieved dict #
dictConfig(log_config)
# Set the logging queue #
log_queue = Queue()
# Get the root logger instance #
root_logger = logging.getLogger()
# Start background logging thread #
log_thread = threading.Thread(target=log_handler, args=(log_queue,), daemon=True)
log_thread.start()
RET = 0
# Record the start time #
start_time = time.perf_counter()
try:
main()
# If unknown exception occurs #
except Exception as ex:
# Print error, log, and set error return code #
print_err(f'Unknown exception occurred: {ex}', is_locked=True)
root_logger.log(logging.ERROR, 'Unknown exception occurred: %s', ex)
RET = 1
# Record the finish time #
exec_time = time.perf_counter() - start_time
# Print and log total execution time #
print(f'\n[!] Execution time: {exec_time}')
root_logger.log(logging.INFO, 'Execution time: %s', exec_time)
# Sleep second to ensure logging thread logs info before exit #
time.sleep(1)
sys.exit(RET)