def __init__(self): self.config = WrapMapConfig() # Instance of config class self.modules = self.importModules() self.asyncScanner = nmap.PortScannerAsync( ) # singleton scanner instance # self.currBaseDir: base output folder return
def port_scan(self, timestamp): def port_scanner(host, scan_result): if host in scan_result['scan']: if 'tcp' in scan_result['scan'][host]: portresults = scan_result['scan'][host]['tcp'] for service in portresults: print bcolors.OKGREEN + 'Found open port: ' + str( service) + ' (' + ports.get( ports.port == service).description + ')' + bcolors.ENDC host_id = host_current.get( host_current.hostIP == host).id services.create(hostID=host_id, portID=service, scanTime=timestamp) print bcolors.HEADER + 'Starting basic services scan' + bcolors.ENDC # Instantiate service port scanner object service_scanner = nmap.PortScannerAsync() # Grab list of hosts discovered during most recent scan for i in host_current.select(host_current.hostIP, host_current.hostname, host_current.scanTime).where( host_current.scanTime == timestamp): print bcolors.OKBLUE + 'Scanning ' + i.hostname + ' - ' + i.hostIP + '....' + bcolors.ENDC # Start service port scan service_scanner.scan(hosts=i.hostIP, ports='22-2222', arguments='', callback=port_scanner) # Whilst scanning, output - to screen while service_scanner.still_scanning(): time.sleep(0.3) sys.stdout.write("-") sys.stdout.flush()
def run(self, callback): self.callback = callback try: nm = nmap.PortScannerAsync() if (type(self.params["hosts"]) != list): raise RedOpsInvalidType(type(self.params["hosts"]), list, self.moduleName) # Translate host to ID self.hostMap = [] for host in self.params["hosts"]: if isinstance(host, Domain): try: self.hostMap.append( (socket.gethostbyname(host.name), host.id)) except socket.gaierror as e: pass # Invalid domain else: self.hostMap.append((host.value, host.id)) # Convert to dict self.hostMap = dict(self.hostMap) # We read the IP or domain name and make a list hosts = [ host.name if isinstance(host, Domain) else host.value for host in self.params["hosts"] ] hosts = " ".join(hosts) # Also a list of ports ports = ",".join(self.params["options"]["ports"]) if (self.params["options"]["mode"] == "TCP"): # We update every time a host is scan # Detect if ROOT mode to launch SYN scan if (os.environ.get('NMAP_PRIVILEGED') != None): nm.scan(hosts=hosts, arguments='-sS -sV -Pn', ports=ports, callback=self.update) else: nm.scan(hosts=hosts, arguments='-sT -sV -Pn', ports=ports, callback=self.update) # In the last loop we want to finish the task in the server elif (self.params["options"]["mode"] == "UDP"): nm.scan(hosts=hosts, arguments='-sU -Pn', ports=ports, callback=self.update) else: self.callback.warning("Invalid scan mode") # As is async we cant use callback.finish here, we have to wait while nm.still_scanning(): nm.wait(2) callback.finish(list()) # End the job except Exception as e: self.callback.exception(e)
def scan(help, nikto, target): if not target: click.echo("Please provide a target. Ex: python ptf.py 10.10.10.91") click.echo("Beginning probe scans for {}".format(target)) global conn conn = create_db_connection(False) prep_db() global pm pm = ProcessManager() pm.load() # Start nmap scanning #click.echo("Nmap's scanning {}, check {} and {} for output".format(target, nmapLight, nmapFull)) click.echo("Starting light nmap scan for initial recon...") # Asynchronous usage of PortScannerAsync #run_program("nikto", target, "80", "http", ["nikto", "-h", "http://{}".format(target)]) #return def investigate_service(port, target, service): #click.echo("{}: {}".format(port,service)) service_directory = {} http = ["nikto", "-h", "http://{}".format(target)] # Port Definitions for key in [80, 8080, 443, 8043]: service_directory[key] = http if port in service_directory: run_program(service_directory[port][0], target, port, service["name"], service_directory[port]) nma = nmap.PortScannerAsync() def process_nmap_scan(host, result): if result["scan"] and result["scan"][host]: services = result["scan"][host]["tcp"] if services: click.echo("Auto investigating the following identified services. Run `ptf status` for an update.") for port in services: investigate_service(port, target, services[port]) else: click.echo("{} doesn't appear to have any open ports!".format(host)) else: click.echo("This host didn't respond, it might be down") # Go ahead and kick off the intense nmap scan while everything else runs run_program("nmapFull", target, "", "", ["nmap", "-vvv", "-A", "-p-", "-Pn", "--script=all", target]) click.echo(pm.toString()) conn.close() nma.scan(hosts=str(target), arguments='-F -Pn', callback=process_nmap_scan) while nma.still_scanning(): nma.wait(1) return """ Process simulation w/ cURL """ run_program("curl", target, "80", "http", ["curl", target+":80"]) run_program("nmapLight", target, "", "", ["nmap", "-vvv", "-F", target]) run_program("nmapFull", target, "", "", ["nmap", "-vvv", "-A", "-p-", "-Pn", "--script=all", target]) run_program("nikto", target, "80", "http", ["nikto", "-h", "http://{}".format(target)])
def test_scan_progressive(): nmp = nmap.PortScannerAsync() def callback(host, scan_data): assert (host is not None) nmp.scan(hosts='127.0.0.1', arguments='-sV', callback=callback) nmp.wait()
def defaultScannning(ipAddress): print('Retrieving Device BIOs for Host {0}'.format(ipAddress)) nma = nmap.PortScannerAsync() nma.scan(hosts=ipAddress, arguments='-n -sV -O', callback=callback_result) while nma.still_scanning(): print("Waiting >>>") nma.wait(2)
def nmapScan(target_list): scanner = nmap.PortScannerAsync() for target in target_list: scanner.scan(target, arguments='-sV -PS -p' + ','.join(target_list[target]), callback=callback_result) while scanner.still_scanning(): scanner.wait(2)
def nmap_engine(request, task, action): """ 调用nmap,实现设备的扫描功能""" subtask = task.subtask scanner = task.scanner scanner_id = scanner.id nm = nmap.PortScanner() nm_a = nmap.PortScannerAsync() if action == 'running': subtask.subtask_status = action subtask.save() nmap_call.delay(subtask, task, nm_a)
def scanTCP(self, callback_function=None): nma = nmap.PortScannerAsync() if not callback_function: nma.scan(self.host, arguments=self.arguments, sudo=self.privileged, callback=self.callback_results) else: nma.scan(self.host, arguments=self.arguments, sudo=self.privileged, callback=callback_function) return nma
def scan(network): """ The network scanning function. Scans the network using 'nmap -sP'. For each found host there is a callback async called :param network: an ipaddress including it's subnetmask, eg. 192.168.0.0/24 """ nma = nmap.PortScannerAsync() nma.scan(hosts=network, arguments='-sP', callback=cb_host) while nma.still_scanning(): nma.wait(2)
def port_scan_async(): print ("---------------多线程端口扫描-----------------") nmaps = nmap.PortScannerAsync() nmaps.scan(hosts="192.168.199.1/24", ports="21-80", callback=call_back, sudo=False) for host_list in nmaps.all_hosts(): print ("Host : %s (%s)" % (host_list, nmaps[host_list].hostname())) print ("State : %s " % nmaps[host_list].state()) for protocols in nmaps[host_list].all_protocols(): print ("\tProtocols : %s " % protocols) prots_list = nmaps[host_list][protocols].keys() prots_list.sort() for prots in prots_list: print ("\t\tProt : %s \t state : %s " % (prots, nmaps[host_list][protocols][int(prots)]['state']))
def scanTCP(self, callback_function=None): self.logger.info("Running TCP port scan on {}...".format(self.host)) nma = nmap.PortScannerAsync() if not callback_function: nma.scan(self.host, arguments=self.arguments, sudo=self.privileged, callback=self.callback_results) else: nma.scan(self.host, arguments=self.arguments, sudo=self.privileged, callback=callback_function) return nma
def AsyncScan(self, ports): self.asynclog = [] self.ports = ports self.network = '-iR ' + str(self.NmapRandomCount) self.arguments = ' -Pn -n -sV -p ' + self.ports self.nma = nmap.PortScannerAsync() self.nma.scan(hosts=self.network, arguments=self.arguments, callback=self.async_callback_result) while self.nma.still_scanning(): print("Waiting >>>") print(self.asynclog) self.nma.wait(2)
def test_ipv6_async(): global FLAG FLAG = Value('i', 0) nma = nmap.PortScannerAsync() def callback_result(host, scan_result): global FLAG FLAG.value = 1 nma.scan(hosts='::1', arguments='-6 -p 22 -Pn', callback=callback_result) while nma.still_scanning(): nma.wait(2) assert_equals(FLAG.value, 1)
def portinfos(p, quantity): while True: try: host = queue.get(timeout=0.1) global num nma = nmap.PortScannerAsync() apple = nma.scan(hosts=host, arguments='-sV -p ' + p, callback=callback_result) while nma.still_scanning(): nma.wait(100) except Exception as e: break queue.task_done() progress(quantity)
def scanner(hosts, ports, arguments='-sV'): def callback_result(host, scan_result): if scan_result['nmap']['scanstats']['uphosts']: doc = {'hosts': hosts, 'scan_result': scan_result} client.cron.scanner.find_one_and_replace({'host': host}, doc, upsert=True) try: nma = nmap.PortScannerAsync() nma.scan(hosts=hosts, ports=ports, arguments=arguments, callback=callback_result) except Exception as e: print str(e)
def scan(target, nmap_arguments, ports, output_arguments, sudo=False): def callback_result(host, scan_result): if VERBOSE: logger.info('Finished scanning %s.' % host) d = nerds_format(host, scan_result) if d: output(d, output_arguments['out_dir'], output_arguments['no_write']) nma = nmap.PortScannerAsync() nma.scan(hosts=target, ports=ports, arguments=nmap_arguments, callback=callback_result, sudo=sudo) return nma
def run(self): self.log('Starting thread...') self._nma = nmap.PortScannerAsync() while self._running: try: target = faker.ipv4() self.log('Performing scan on', target) self._nma.scan(target, PORT_LIST, arguments='-A', callback=self.procesar_resultado) while self._nma.still_scanning(): self._nma.wait(2) except Exception: self.log('Exiting thread...') self.stop()
def test_ipv4_async(): global FLAG FLAG = Value("i", 0) nma = nmap.PortScannerAsync() def callback_result(host, scan_result): global FLAG FLAG.value = 1 nma.scan(hosts="127.0.0.1", arguments="-p 22 -Pn", callback=callback_result) while nma.still_scanning(): nma.wait(2) assert_equals(FLAG.value, 1)
def test_ipv6_async(): global FLAG_ipv6 FLAG_ipv6 = Value("i", 0) nma_ipv6 = nmap.PortScannerAsync() def callback_result(host, scan_result): global FLAG_ipv6 FLAG_ipv6.value = 1 nma_ipv6.scan(hosts="::1", arguments="-6 -p 22 -Pn", callback=callback_result) while nma_ipv6.still_scanning(): nma_ipv6.wait(2) assert_equals(FLAG_ipv6.value, 1)
def AsyncScan(self): self.nma = nmap.PortScannerAsync() def callback_result(host, scan_result): print('------------------') print(scan_result['nmap']['command_line']) print(scan_result['scan'][host]['addresses']['ipv4']) # print(host, scan_result) print('------------------') HasPort(host, scan_result) # print(scan_result['scan']) # print(scan_result['scan'][host].all_protocols()) # if(scan_result['scan'][host].has_tcp(21)): # if(scan_result['scan'][host]['tcp'][21]['state'] == 'open'): # print(scan_result['scan'][host]['tcp'][21]) # print(scan_result['scan'][host]['addresses']['ipv4'],21,scan_result['scan'][host]['tcp'][21]['state']) # print(scan_result['nmap']) # print(scan_result['nmap']['scaninfo']['tcp']['services']) # print(scan_result['nmap']['scanstats']) def HasPort(host, scan_result): for port in self.ports.split(','): if (scan_result['scan'][host].has_tcp(int(port))): if (scan_result['scan'][host]['tcp'][int(port)]['state'] == 'open'): print(scan_result['scan'][host]['tcp'][int(port)]) print( scan_result['scan'][host]['addresses']['ipv4'], int(port), scan_result['scan'][host]['tcp'][int( port)]['state']) else: print(port + " not open but " + scan_result['scan'] [host]['tcp'][int(port)]['state']) self.nma.scan(hosts=self.network, arguments=self.arguments, callback=callback_result) while self.nma.still_scanning(): print("Waiting >>>") self.nma.wait( 2 ) # you can do whatever you want but I choose to wait after the end of
def scan_host(host, ports='1-65535'): u""" 最小化任务,仅扫描一个ip """ sudo = False scan_args = '-sT -Pn' if os.getuid() == 0: sudo = True scan_args = '-sS -Pn' def call_back(host, scan_data): logger.debug("Scan Host {0} complate: {1}".format(host, scan_data)) scanner = nmap.PortScannerAsync() logger.debug("Add task Scan Host `{0}` with Ports {1}".format(host, ports)) scanner.scan(str(host), str(ports), scan_args, callback=call_back, sudo=sudo) return dict(ok=True)
def __init__(self): self.arguments = get_arguments() self.current_directory = os.path.dirname(os.path.realpath(__file__)) self.date = "date_" + str(time.strftime("%Y_%m_%d")) if not self.arguments.output_dir: self.arguments.output_dir = self.current_directory + os.sep + 'results' if not os.path.exists(self.arguments.output_dir): print("Creating: " + str(self.arguments.output_dir)) os.makedirs(self.arguments.output_dir) if not self.arguments.database: self.arguments.database = self.date self.ping_args = '-n -Pn -v -sn' # self.ping_args = '-n -Pn -v -sT -p 21,23,80,443,139,445,3389' self.basic_args = '-n -Pn -v -O -sV -sT --top-ports 5000 -T3 --script=banner-plus,smb-os-discovery' self.advanced_args = '-n -Pn -v -O -sV -sT --top-ports 500 -T3 --script=banner-plus,smb-os-discovery' self.full_args = '-n -Pn -v -O -sV -sT -sU -p0-65535 --script=banner-plus,smb-os-discovery' self.scan_type = str() self.local_data = self.get_local_info( ) # Get Attacking Machine Information self.async_scan = nmap.PortScannerAsync() self.ping_results = dict() self.basic_results = dict()
def scan_ipaddres_protocol_port(ipaddres, protocolo, port): nm = nmap.PortScannerAsync() return nm[str(ipaddres)][str(protocolo)][int(port)]['state']
def info_ipaddres(ipaddres): nm = nmap.PortScannerAsync() results = nm.scan(str(ipaddres)) scan_info = nm.scaninfo() return nm.csv(), results, scan_info
#!/usr/bin/env python import nmap nm = nmap.PortScannerAsync() def callback_result(host, scan_result): print('------------------') print(host, scan_result) nm.scan('127.0.0.1', arguments="-O -v", callback=callback_result) while nm.still_scanning(): print("Waiting >>>") nm.wait(2) print(nm1.nmap_version())
def nmapping(): nm = nmap.PortScannerAsync() nm.scan('afast.ws', arguments='-v -A -O', callback=callback_result) while nm.still_scanning(): nm.wait(2)
def leases(self): l = lease_check() myfile = open('/var/lib/dhcp/dhcpd.leases', 'r') leases = l.parse_leases_file(myfile) myfile.close() now = l.timestamp_now() report_dataset = l.select_active_leases(leases, now) print( '+------------------------------------------------------------------------------' ) print('| DHCPD ACTIVE LEASES REPORT') print( '+-----------------+-------------------+----------------------+-----------------' ) print( '| IP Address | MAC Address | Expires (days,H:M:S) | Client Hostname ' ) print( '+-----------------+-------------------+----------------------+-----------------' ) for lease in report_dataset: print('| ' + format(lease['ip_address'], '<15') + ' | ' + \ format(lease['hardware'], '<17') + ' | ' + \ format(str((lease['ends'] - now) if lease['ends'] != 'never' else 'never'), '>20') + ' | ' + \ lease['client-hostname']) print( '+-----------------+-------------------+----------------------+-----------------' ) print('| Total Active Leases: ' + str(len(report_dataset))) for lease in report_dataset: #result = nm.scan(lease['ip_address'], '1-1024', '-n', '-Pn') #print nm.scaninfo() print "rrrr" result = nm.scan(hosts=lease['ip_address'], arguments='-n -sP -PE -PA21,23,80,3389') print result for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname())) print('State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): print('----------') print('Protocol : %s' % proto) lport = nm[host][proto].keys() lport.sort() for port in lport: print('port : %s\tstate : %s' % (port, nm[host][proto][port]['state'])) #print "ssss" print(nm.csv()) #nm.scan(hosts=lease['ip_address'], arguments='-n -Pn -p1-1024') #print(nm.csv()) print('----------------------------------------------------') # Asynchronous usage of PortScannerAsync nma = nmap.PortScannerAsync() def callback_result(host, scan_result): print('------------------') print(host, scan_result) nma.scan(hosts=lease['ip_address'], arguments='-sP', callback=callback_result) while nma.still_scanning(): print("Waiting ...") nma.wait( 2 ) # you can do whatever you want but I choose to wait after the end of the scan #if (os.getuid() == 0): # print('----------------------------------------------------') # # Os detection (need root privileges) # ip = lease['ip_address'] # nm.scan(ip ,arguments="-O") # if 'osclass' in nm[ip]: # for osclass in nm[ip]['osclass']: # print('OsClass.type : {0}'.format(osclass['type'])) # print('OsClass.vendor : {0}'.format(osclass['vendor'])) # print('OsClass.osfamily : {0}'.format(osclass['osfamily'])) # print('OsClass.osgen : {0}'.format(osclass['osgen'])) # print('OsClass.accuracy : {0}'.format(osclass['accuracy'])) # print('') # # if 'osmatch' in nm[lease['ip_address']]: # for osmatch in nm[lease['ip_address']]['osmatch']: # print('OsMatch.name : {0}'.format(osclass['name'])) # print('OsMatch.accuracy : {0}'.format(osclass['accuracy'])) # print('OsMatch.line : {0}'.format(osclass['line'])) # print('') # # if 'fingerprint' in nm[lease['ip_address']]: # print('Fingerprint : {0}'.format(nm[lease['ip_address']]['fingerprint'])) # Vendor list for MAC address nm.scan(lease['ip_address'], arguments='-O') for h in nm.all_hosts(): if 'mac' in nm[h]['addresses']: print(nm[h]['addresses'], nm[h]['vendor'])
with open('./logging.yml', 'rt') as f: config = yaml.safe_load(f.read()) f.close() logging.config.dictConfig(config) # Get an instance of a logger logger = logging.getLogger("flanby") def callback_result(host, scan_result): message = "{} -> {}".format(host, scan_result) logger.debug(message) nmScan = nmap.PortScannerAsync() nmScan.scan(hosts='192.168.1.1-254', ports='21-443', callback=callback_result) while nmScan.still_scanning(): pass # logger.debug("Waiting ...") # for host in nmScan.all_hosts(): # logger.debug('Host : %s (%s)' % (host, nmScan[host].hostname())) # logger.debug('State : %s' % nmScan[host].state()) # for proto in nmScan[host].all_protocols(): # logger.debug('| Protocol : %s' % proto) # # lport = nmScan[host][proto].keys() # # lport.sort() # for port in lport: # logger.debug('-->port : %s\tstate : %s' % (port, nmScan[host][proto][port]['state']))
""" @file: nmap_test.py @time: 2019/10/8 @author: alfons """ import nmap scaner = nmap.PortScannerAsync() res = scaner.scan(hosts="10.10.100.0/24", arguments="-sP") print(res) pass