def nmap_get_service(self, ip_port): '''nmap 获取端口的 service''' ip, port = ip_port try: nm_scan = nmap.PortScanner() args = '-p T:' + str(port) + ' -Pn -sT -sV -n' # args = '--allports -Pn -sT -sV -n --version-all --min-parallelism 100' nm_scan.scan(ip, arguments=args) # logger.info(nm_scan.command_line()) self.port_service_list[ip] = list() port_result = nm_scan[ip]['tcp'] for port in port_result.keys(): state = port_result[port]['state'] name = port_result[port]['name'] product = port_result[port]['product'] version = port_result[port]['version'] result = "{:<17}{:<7}{:<10}{:<16}{:<32}{}".format( ip, port, state, name, product, version) lock.acquire() logger.info(result) lock.release() service_result = dict() service_result['port'] = port service_result['state'] = state service_result['name'] = name service_result['product'] = product service_result['version'] = version self.port_service_list[ip].append(service_result) except Exception as e: # logger.error(e) pass
def __init__(self): self.__name = get_rand_name() self.__begin = [] self.__end = [] self.__nmap = nmap.PortScanner() self.logger = Logger('log/producer_%s.log' % self.__name, level='debug') self.logger.info('Create a producer(%s)' % self.__name)
def scan_hosts(host, ports): nm = nmap.PortScanner() nm.scan(hosts=host, arguments='-Pn -p{0} -sV'.format(ports)) hosts = [] for h in nm.all_hosts(): hosts.append(Host(h, nm)) return hosts
def run(config): """ :param config: GlobalParameters option instance :type config: `GlobalParameters` :raises: TypeError """ if not isinstance(config, GlobalParameters): raise TypeError("Expected GlobalParameters, got '%s' instead" % type(config)) # -------------------------------------------------------------------------- # Checks Python version # -------------------------------------------------------------------------- # if version_info < 3: # raise RuntimeError("You need Python 3.x or higher to run ScanX") # -------------------------------------------------------------------------- print('----------------------------------------------------') from nmap import nmap scanner = nmap.PortScanner() print("Nmap Version: ", scanner.nmap_version()) scanner.scan('127.0.0.1', '21-443') for host in scanner.all_hosts(): print('Host : %s (%s)' % (host, scanner[host].hostname())) print('State : %s' % scanner[host].state()) if scanner[host].has_tcp(22): ssh22 = 'open' else: ssh22 = 'closed' if scanner[host].has_tcp(23): telnet = 'open' else: telnet = 'closed' print('SSH 22 : %s' % ssh22) print('TELNET : %s' % telnet) for proto in scanner[host].all_protocols(): print('Protocol : %s' % proto) lport = scanner[host][proto].keys() lport.sort() for port in lport: print('port : %s\tstate : %s' % (port, scanner[host][proto][port]['state'])) print('Ping Scan NETWORK ...') scanner.scan(hosts='192.168.0.0/24', arguments='-n -sP -PE -PA21,23,80,3389') hosts_list = [(x, scanner[x]['status']['state']) for x in scanner.all_hosts()] for host, status in hosts_list: print('{0}:{1}'.format(host, status)) print('Script : %s' % scanner.command_line()) print('----------------------------------------------------')
def exploit(self, *args, **kwargs): nm = nmap.PortScanner() scriptname = self.getParam("Script") p = os.path.realpath(__file__) p = os.path.dirname(p) p = os.path.join(p, scriptname) p = p.replace('\\', "/") ments = "-p %s --script=%s" % (str(self.TargetPort), p) ret = nm.scan(self.TargetIp, arguments=ments) UniPrinter().pprint(ret['scan']) return ret
def ips_nmap(): print("INICIANDO SCANNER DE REDE") ip = netifaces.gateways()['default'][2][0] nm = nmap.PortScanner() nm.scan(hosts=ip + "/25", arguments="-F -n") print("FINALIZADO...") ips_up = {} if nm.all_hosts(): for host in nm.all_hosts(): if nm[host].state() == 'up': try: ips_up[host] = nm[host]['tcp'] except: ValueError() return ips_up, ip
def dnssecc_subdomain_enum(self, target): if os.getuid() == 0: print("Starting DNSSEC Enum") nm = nmap.PortScanner() arguments = '-sSU -p 53 --script dns-nsec-enum --script-args dns-nsec-enum.domains=' + target nm.scan(hosts=self.ip, arguments=arguments) for host in nm.all_hosts(): try: print(nm[host]['udp'][53]['script']['dns-nsec-enum']) except: pass else: ColorPrint.red( "To run a DNSSEC subdomain enumeration, Anubis must be run as root" )
def __init__(self, output, all_ip, arguments, thread_count): self.arguments = arguments self.nm = nmap.PortScanner() self.thread_count = 30 if thread_count > 30 else thread_count self.all_ip = all_ip self.lock = threading.Lock() self.thread = [] self.r = re.compile( "^(192\.168|169|172\.[0-3][0-9]|127|10).*") #正则匹配保留地址 self.console_width = getTerminalSize()[0] self.console_width -= 2 # Cal width when starts up self.output = open('nmap_' + output + '.txt', 'w') print('\033[1;33;40m[*]Count of All Thread: ' + str(self.thread_count) + '\033[0m') for thread_name in range(self.thread_count): #根据线程数创建线程 self.thread.append( threading.Thread(target=self._do_Scan, name=str(thread_name)))
def find_server_ip(self) -> str: """ creates a port scanner which finds all machines on network and pings their port 3000. The first machine with an open port 3000 (signifying the server) is returned. :return: IP_address as str """ while True: nm = nmap.PortScanner() ip = self.HOST ip = '.'.join(ip.split('.')[:-1]) ip = ip + '.0/24' results = nm.scan(hosts=ip, ports=str(self.PORT), arguments='') for ip in results['scan']: if results['scan'][ip]['tcp'][self.PORT]['state'] == 'open': return ip time.sleep(.5)
#sys.argv[3]-->argumentsValidation #sys.argv[4]-->arguments args3 = base64.b64decode(sys.argv[3]) args4 = base64.b64decode(sys.argv[4]) print(sys.argv[1]) print(sys.argv[2]) #print(sys.argv[3]) print(args3) #print(sys.argv[4]) print(args4) #db.nmapConfig.update_or_insert(db.nmapConfig.id==sys.argv[1], scanRunning='T') try: nm = nmap.PortScanner() except: redirect(URL('default','index', vars=dict(msg='To use HOST SCAN, you should install NMAP https://nmap.org/'))) result = nm.scan(hosts=sys.argv[2], arguments=args3) #result = nm.scan(hosts='127.0.0.1') #print(result) #argumentsParser = str(str(request.get_vars.arguments).replace(' ',',')).split(',') argumentsParser = str(str(args4).replace(' ',',')).split(',') db.nmapConfig.update_or_insert(db.nmapConfig.id==sys.argv[1], scanInfo=nm.scaninfo(), command_line=nm.command_line(), scanstats=nm.scanstats(), scanRunning='F') #argumentsParser = str(str(args4).replace(' ',',')).split(',') for host in nm.all_hosts(): if nm[host].state()=='up':
def hostScan(): #------------------------------------------------------------------------------------- if demo == False: if (auth.has_membership(role='admin') or auth.has_membership(role='riskManager')): pass else: redirect(URL('default', 'index')) #------------------------------------------------------------------------------------- import nmap.nmap try: nm = nmap.PortScanner() except: redirect( URL('default', 'index', vars=dict( msg= 'To use HOST SCAN, you should install NMAP https://nmap.org/' ))) #db.nmapConfig.id.readable = False db.nmapConfig.scanInfo.writable = False db.nmapConfig.command_line.writable = False db.nmapConfig.scanstats.writable = False db.nmapConfig.scanRunning.writable = False fields = (db.nmapConfig.id, db.nmapConfig.scanHostName, db.nmapConfig.scanHostNetwork, db.nmapConfig.scanDate, db.nmapConfig.scanArguments, db.nmapConfig.scanRunning) links = [ lambda row: A(T('Scan'), _class='button btn btn-danger', _href=URL("portScanner", "executeScan", args=[row.id, row.scanDate], vars=dict(hosts=row.scanHostNetwork, arguments=row.scanArguments))), lambda row: A(T('Stats'), _class='button btn btn-primary', _href=URL( "portScanner", "hostScan", vars=dict(idRow=row.id))) ] form = SQLFORM.grid(db.nmapConfig, fields=fields, user_signature=False, searchable=True, create=True, editable=True, deletable=True, links=links, maxtextlength=500, paginate=10) if request.get_vars.idRow != 'None': idRow = request.get_vars.idRow else: idRow = 0 if request.get_vars.idRow: scanHostsCount = db.nmapResults.id.count() rScan2 = db(db.nmapResults.nmapConfigId == idRow).select( db.nmapResults.ALL) scanHosts = db(db.nmapResults.nmapConfigId == idRow).select( db.nmapResults.scanHostName, db.nmapResults.port, db.nmapResults.protocolState, db.nmapResults.statusState, scanHostsCount, db.nmapResults.nmapConfigId, groupby=db.nmapResults.scanHostName) scanPorts = db(db.nmapResults.nmapConfigId == idRow).select( db.nmapResults.scanHostName, db.nmapResults.port, db.nmapResults.protocolState, db.nmapResults.statusState, scanHostsCount, groupby=db.nmapResults.port) else: rScan2 = '' scanHosts = '' scanPorts = '' return dict(form=form, rScan2=rScan2, scanHosts=scanHosts, scanPorts=scanPorts)
def discover_hosts(): portScanner = nmap.PortScanner() portScanner.scan(hosts='192.168.1.0/24', arguments='-n -sP') return [(x, portScanner[x]['status']['state']) for x in portScanner.all_hosts()]
def test_nmap(): from nmap import nmap nm = nmap.PortScanner() nm.scan('192.168.43.1-255', arguments='-sn -PS -T5 --min-parallelism 100') print(nm.get_nmap_last_output())
def scan(target, port_range, extra_options, job_id, sensor='localhost'): ''' Scans the port range on the target IP/IP Range with nmap. extra_options are passed as CLI arguments to nmap. The job_id will be saved to the changelog entry in the database for reference to the actual job. @param target CIDR Range, singular IP or hostname @param port_range range of ports to be scanned @param extra_options extra CLI arguments to be passed to nmap @param job_id job UUID as used by the schedule model @param sensor In future versions, you may specify a sensor to be used for scanning (not implemented yet). ''' #get db cur = request.db.cursor() #set all IN PROGRESS log entries older than one day to TIMEOUT q = """update scanlog set state='TIMEOUT' where state='IN PROGRESS' and datediff(now(), startdate) > 1""" cur.execute(q) #log start of scan q = """INSERT INTO scanlog (jobid, state, startdate, iprange, portrange, extraoptions) VALUES ("%s", "%s", NOW(), "%s", %s, %s)""" % ( "%s" % job_id if job_id else "Null", "IN PROGRESS", target, "%s" % port_range if port_range else "Null", "'%s'" % extra_options if extra_options else "Null") cur.execute(q) logid = cur.lastrowid request.db.commit() cur.close() try: #start port scanner ps = nmap.PortScanner() #recode to ascii - utf not allowed ps.scan(target.encode('ascii'), port_range.encode('ascii') if port_range else None, extra_options.encode('ascii')) cur = request.db.cursor() #machines #remove old machines oldmachs = Machine.getIPsInRange(target.encode('ascii'), exposedOnly=True) print "known machines in range %s: %s" % (target, oldmachs) print "machines found by scan: %s" % ps.all_hosts() for hostip in filter(lambda x: False if x in ps.all_hosts() else True, oldmachs.keys()): mach = Machine(oldmachs[hostip]) for svc in mach.getServices(exposedOnly=True): print "deleting service %s on %s" % (svc.port, hostip) svc.delete() #create new machines, add/remove services for hostip in ps.all_hosts(): host = ps[hostip] #if nmap did not determine hostname, try be reverse name resolution if not (host['hostname'] and len(host['hostname'])): from socket import gethostbyaddr, herror try: host['hostname'] = gethostbyaddr(hostip)[0] except herror: host['hostname'] = '' #create new machines mach = Machine.create(host['hostname'], hostip) #open ports if 'tcp' in host: portnumbers = filter(lambda x: True if host['tcp'][x]['state'] == 'open' else False, host['tcp'].keys()) #delete old services for svc in mach.getServices(exposedOnly=True): # if port not detected anymore and in scanned range, delete # it if not svc.port in portnumbers and (svc.inRange(port_range ) if port_range else True): print "deleting %s" % svc.port svc.delete() #create new services for portno in portnumbers: port = host['tcp'][portno] if port['state'] == 'open': print "creating %s" % portno Service.create(mach, portno, port['product'] if "product" in port else None, port['version'] if "version" in port else None, port['extrainfo'] if "extrainfo" in port else None) #log state = "OK" message = None except: state = "FAILED" message = traceback.format_exc() print message finally: #log cur = request.db.cursor() q = ("""UPDATE scanlog SET state="%s", enddate=NOW(), output=%s WHERE ID=%d""" % (state, "'%s'" % request.db.escape_string(message) if message else "NULL", logid)) cur.execute(q) request.db.commit() return state
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- import threading from nmap import nmap nmScan=nmap.PortScanner() def scan(tgtport): nmScan.scan(tgthost, str(tgtport)) state = nmScan[tgthost]['tcp'][tgtport]['state'] print('port: %d state: %s' % (tgtport, state)) tgthost=input('host: ') tgtports=range(8200,8400) print('start scan') for tgtport in tgtports: thread=threading.Thread(target=scan,args=(tgtport,)) thread.start()