def __init__(self): self.mas = masscan.PortScanner() self.temp_file = "masscan_temp_file.txt" # 不打印debug信息 masscan.logger.setLevel(logging.ERROR) pass
def masscan_scan(ips, ports, url_path, rate, out_port, out_url, q): scan_list = [] print('Masscan starting.....\n') masscan_scan = masscan.PortScanner() if 'txt' in ips: masscan_scan.scan( ports=ports, arguments= '-sS -Pn -n --randomize-hosts -v --send-eth -iL %s --open --rate %s' % (ips, rate)) else: masscan_scan.scan( hosts=ips, ports=ports, arguments= '-sS -Pn -n --randomize-hosts -v --send-eth --open --rate %s' % (rate)) try: for host in masscan_scan.all_hosts: for masscan_proto in masscan_scan[host].keys(): for masscan_port in masscan_scan[host][masscan_proto].keys(): scan_list.append(str(host) + ':' + str(masscan_port)) print('Masscan scanned.....\n') print('Path starting.....\n') for ip_port in scan_list: with open(out_port, 'a') as writer: writer.write(ip_port + '\n') q.put(ip_port) print('Path scanned.....\n') except Exception as e: print(e) pass finally: pass
def masscan(self): print('\033[34m[INFO]\033[0m Masscan PortScan Module Running!') try: mascan = masscan.PortScanner() mas = mascan.scan(hosts=self.hosts, ports=self.ports, arguments=self.arguments) for host in mascan.all_hosts: if host == '': print('\033[31m[ERRO]\033[0m No Surviving Hosts') else: print('\033[34m[ONLI]\033[0m Online Host: %s' % host) for host in mascan.all_hosts: print('\033[32m[TARG]\033[0m Target: %s' % host) port_all = mas['scan'][host]['tcp'].keys() port_all = list(port_all) # dict转list # print(port_all) for port in port_all: target_port_state = mas['scan'][host]['tcp'][port]['state'] # print('\033[32m[INFO]\033[0m Port: %s Status: %s' % (port, target_port_state)) if target_port_state == 'open': print('\033[32m[OPEN]\033[0m Port: %s Status: %s' % (port, target_port_state)) elif target_port_state == 'closed': print('\033[31m[CLOS]\033[0m Port: %s Status: %s' % (port, target_port_state)) else: print('\033[33m[FILT]\033[0m Port: %s Status: %s' % (port, target_port_state)) print() print('\033[32m[SUCC]\033[0m PortScan Module Has Finished Running!') except Exception as e: print('\033[31m[ERRO] %s' % e)
def masScan(host, portrange, whitelist=[80, 443]): mas = masscan.PortScanner() html = Template_html() conn = ConDb() logging.info('masscan scan the ports for host %s' % host) masports = "" attempts = 0 success = False # 如果出现异常重试,最多重试三次 while attempts < 3 and not success: try: mastmp = mas.scan( host, portrange, arguments= '--rate=1000 --interface eth0 --router-mac 48-7a-da-78-f6-xx') # mastmp = ip_scan(host, portrange) logging.info(mastmp) success = True masports = str(mastmp['scan'][host]['tcp'].keys()).replace( "[", "").replace("]", "").replace(", ", ",") except: attempts += 1 if attempts == 3: break tmp = nmScan(host, masports) try: ports = tmp['scan'][host]['tcp'].keys() for port in ports: status = tmp['scan'][host]['tcp'][port]['state'] service = tmp['scan'][host]['tcp'][port]['name'] if port in whitelist: deal = 'YES' else: deal = 'NO' # 扫描出来的端口在入库之前先查询是否有记录,如果存在则更新,如果不存在则添加。 # 以此多次执行全量扫描解决masscan少部分漏扫和nmap偶尔没有返回的情况。 query_sql = "select ip from scan_port where ip = '%s' and port = '%s'" % ( host, port) rs = conn.runSql(query_sql.encode('utf-8')) if rs: set = 'status = \"%s\", services = \"%s\", deal = \"%s\"' % ( status, service, deal) where = 'ip = \"%s\" and port = \"%s\"' % (host, port) conn.update_TB('scan_port', set, where) else: insert_sql = [host, port, status, service, deal] conn.insert_TB('scan_port', insert_sql, 'ip', 'port', 'status', 'services', 'deal') logging.info('To get host %s html template.' % host) rs = html.html_template(host, 'open', 'NO', conn) # if rs: # sendemail(rs[0], rs[1]) # else: # pass except Exception, e: logging.info("%s扫描结果正常,无暴漏端口: %s" % (host, e))
def kr_scan(ip, ports): if ip: mas = masscan.PortScanner() try: result = mas.scan(ip, ports=ports) return result except Exception as e: pass
def portscan(): try: m = masscan.PortScanner() m.scan(hosts='', ports='0', arguments=opts['masscan_opts'], sudo=True) except masscan.NetworkConnectionError as err: log('no sshds found or network unreachable', 'error') return m
def GetOneIPorts(self,ip): try: mas = masscan.PortScanner() mas.scan(self.ip,ports='21,22,23,25,80,81,88,8080,8888,999,9999,7000,1433,1521,3306,3389,6379,7001,27017,27018,21, 4445, 2638, 8089, 8080, 1433, 5632, 8099, 1423, 520, 5900, 512, 7003, 8873, 2888, 8649, 8083, 9043, 513, 9001, 8088, 50030, 9090, 80, 1527, 8087, 1723, 30015, 9991, 9000, 2049, 2439, 2375, 69, 162, 5631, 502, 4950, 4899, 3888, 9990, 514, 7001, 2601, 1900, 1435, 1521, 6002, 6000, 2100, 8889, 389, 25, 8161, 500, 68, 7002, 53, 888, 27018, 2181, 6371, 6003, 23, 6001, 9999, 161, 9110, 88, 999, 11211, 1098, 111, 89, 5353, 67, 995, 6379, 1099, 9300, 27019, 8888, 81, 27017, 7777, 123, 8090, 9200, 49152, 87, 8009, 8000, 993, 1080') OpenPorts = mas.scan_result['scan'][ip]['tcp'].keys() except: return None return {ip:OpenPorts}
def GetOneIPorts(self, ip): try: mas = masscan.PortScanner() mas.scan(ip) OpenPorts = mas.scan_result['scan'][ip]['tcp'].keys() except: return None return {ip: OpenPorts}
def masscan_scan(self, username, target, target_ip, min_port, max_port, rate): """ 用masscan进行扫描 :param username: 用户名 :param target: 待扫描的目标 :param target_ip: 待扫描的目标ip :param min_port: 扫描端口的最小值 :param max_port: 扫描端口的最大值 :param rate: 扫描速率 :return scan_list: 扫描的结果 """ scan_list = [] print('Masscan starting.....\n') self.mysqldb.update_scan(username, target, '开始扫描端口') masscan_scan = masscan.PortScanner() masscan_scan.scan( hosts=target_ip, ports='%s-%s' % (min_port, max_port), arguments= '-sS -Pn -n --randomize-hosts -v --send-eth --open --rate %s' % (rate)) try: for host in masscan_scan.all_hosts: for masscan_proto in masscan_scan[host].keys(): for masscan_port in masscan_scan[host][masscan_proto].keys( ): nm = nmap.PortScanner() arguments = '-p %s -sS -sV -Pn -T4 --open' % ( masscan_port) nm.scan(hosts=host, arguments=arguments) for nmap_proto in nm[host].all_protocols(): protocol = nm[host][nmap_proto][int( masscan_port)]['name'] product = nm[host][nmap_proto][int( masscan_port)]['product'] version = nm[host][nmap_proto][int( masscan_port)]['version'] if not self.mysqldb.get_target_port( username, target, masscan_port): self.mysqldb.save_target_port( username, target, masscan_port, protocol, product, version) else: self.mysqldb.update_target_port( username, target, masscan_port, protocol, product, version) scan_list.append( str(host) + ':' + str(masscan_port)) print('Masscan scanned.....\n') self.mysqldb.update_scan(username, target, '端口扫描结束') except Exception as e: print(e) pass finally: pass return scan_list
def detect(iprange): try: converted_list = [str(element) for element in portList] ports = ','.join(converted_list) mas = masscan.PortScanner() mas.scan(iprange, ports=ports, arguments='--max-rate 100000') return mas.scan_result["scan"] except: return None
def mas_scan(self): mas = masscan.PortScanner() ports = ','.join(self.ports) portinfo = {} for ips in self.destips: mas.scan(hosts = ips,ports=ports,arguments='--rate=%s' % self.rate) portinfo[ips] = mas.scan_result['scan'] return portinfo
def masscan_scan(local_dir): mas = masscan.PortScanner() mas.scan('0.0.0.0/0', ports='21', arguments='--max-rate 1000 --exclude 255.255.255.255 --open-only') count = 0 for i in mas.all_hosts(): count += 1 executor = ThreadPoolExecutor(max_workers=count) for host in mas.all_hosts(): executor.submit(ftp_operations(host, local_dir))
def scan(hosts, ports, args): mas = masscan.PortScanner() mas.scan(hosts, ports=ports, arguments=args) scan_buffer = io.StringIO() json.dump(mas.scan_result, scan_buffer, indent=4) out_dict = json.loads(scan_buffer.getvalue()) scan_json = parse_scan(out_dict, ports) log_scan(scan_json) return scan_json
def masscanresult(self, ipstr, thread): mas = masscan.PortScanner() threads = '--max-rate ' + str(thread) mas.scan(ipstr, ports='1-65535', arguments=threads) for result in mas.scan_result['scan']: yuanzu = list(mas.scan_result['scan'].values()) port = list(yuanzu[0]["tcp"].keys()) for i in port: ipdata = str(i) self.portdict.append(ipdata)
def get_ip_ports(ip): try: mas = masscan.PortScanner() mas.scan(ip) url_port = mas.scan_result['scan'][ip]['tcp'].keys() if url_port == [] or url_port == None or url_port == '': return None else: return url_port except Exception, e: return None
def masscanresult(ipstr, thread): mas = masscan.PortScanner() threads = '--max-rate ' + str(thread) mas.scan(ipstr, ports='1-65535', arguments=threads) for result in mas.scan_result['scan']: yuanzu = list(mas.scan_result['scan'].values()) port = list(yuanzu[0]["tcp"].keys()) for i in port: ipdata = result + ":" + str(i) print("发现端口开放\tip地址为:" + result + "\t端口为:" + str(i)) portdict.append(ipdata)
def masscanresult(ipstr,thread): mas = masscan.PortScanner() threads = '--max-rate ' + str(thread) mas.scan(ipstr, ports="21,22,23,80,161,389,443,445,512,513,514,873,1025,111,1433,1521,5560,7778,2601,2604,3128,3306,3312,3311,3389,4440,5432,5900,5984,6082,6379,7001,7002,7778,8000,8001,8080,8089,8090,9090,8083,8649,8888,9200,9300,10000,11211,27017,27018,28017,50000,50070,50030", arguments=threads) for result in mas.scan_result['scan']: yuanzu =list(mas.scan_result['scan'].values()) port = list(yuanzu[0]["tcp"].keys()) for i in port: ipdata =result+":"+ str(i) print("发现端口开放\tip地址为:"+result+"\t端口为:"+str(i)) portdict.append(ipdata)
def portscan(): try: m = masscan.PortScanner() m.scan(hosts='', ports='0', arguments=opts['masscan_opts'], sudo=True) except masscan.NetworkConnectionError as err: log('\n') log('no sshds found or network unreachable', 'error') except Exception as err: log('\n') log(f'unknown masscan error occured: str({err})', 'error') return m
def update(ip, port): mas = masscan.PortScanner() attempts = 0 tmp = [] success = False # 如果出现异常重试,最多重试三次 while attempts < 3 and not success: try: tmp = mas.scan( ip, port, arguments= '--rate=10000 --wait 0 --interface eth0 --router-mac 48-7a-da-78-f6-ae', sudo=True) success = True except: attempts += 1 if attempts == 3: if "," in port: ps = port.split(',') else: ps = [int(port)] for p in ps: # 端口关闭之后扫描也会出现network is unreachable.的异常,所以认为是关闭了 set = 'status = \"%s\", deal = \"%s\"' % ('closed', 'YES') where = 'ip = \"%s\" and port = \"%s\"' % (ip, int(p)) con.update_TB('scan_port', set, where) break try: if "," in port: ps = port.split(',') else: ps = [int(port)] ports = tmp['scan'][ip]['tcp'].keys() for p in ps: if int(p) not in ports: set = 'status = \"%s\", deal = \"%s\"' % ('closed', 'YES') where = 'ip = \"%s\" and port = \"%s\"' % (ip, p) con.update_TB('scan_port', set, where) for p in ports: state = tmp['scan'][ip]['tcp'][p]['state'] if state != 'open': set = 'status = \"%s\", deal = \"%s\"' % (state, 'YES') else: set = 'status = \"%s\", deal = \"%s\"' % (state, 'NO') where = 'ip = \"%s\" and port = \"%s\"' % (ip, p) con.update_TB('scan_port', set, where) except Exception, e: print e
def GetOneIPorts(self,ip,inport,rate): try: mas = masscan.PortScanner() mas.scan(self.ip, ports=inport, arguments='--rate {}'.format(rate)) OpenPorts = mas.scan_result['scan'][ip]['tcp'].keys() except Exception as e: Log('获取扫描IP端口结果异常:{}'.format(str(e))) return [] if len(OpenPorts)<1000: return [{ip:OpenPorts}] else: return []
def GetOneIPorts(self,ip,inport,rate): try: mas = masscan.PortScanner() mas.scan(self.ip, ports=inport, arguments='--rate {}'.format(rate)) # if inport == '0': # mas.scan(self.ip,arguments='--rate {}'.format(rate)) # else: # mas.scan(self.ip,ports=inport,arguments='--rate {}'.format(rate)) OpenPorts = mas.scan_result['scan'][ip]['tcp'].keys() except Exception as e: Log('获取扫描IP端口结果异常:{}'.format(str(e))) return None return {ip:OpenPorts}
def masscan_scan(self, username, target, target_ip, scan_id, min_port, max_port, rate): """ 用masscan进行扫描 :param str username: 用户名 :param str target: 待扫描的目标 :param str target_ip: 待扫描的目标 :param str scan_id: 扫描id :param str min_port: 扫描端口的最小值 :param str max_port: 扫描端口的最大值 :param str rate: 扫描速率 :return list scan_list: 扫描的结果 """ scan_list = [] print('Masscan starting.....\n') masscan_scan = masscan.PortScanner() masscan_scan.scan(hosts = target_ip, arguments = '-sS -Pn -n --randomize-hosts -v --send-eth --open --rate %s' % (rate)) try: for host in masscan_scan.all_hosts: for masscan_proto in masscan_scan[host].keys(): for masscan_port in masscan_scan[host][masscan_proto].keys(): nm = nmap.PortScanner() arguments = '-p %s -sS -sV -Pn -T4 --open' % (masscan_port) nm.scan(hosts = host, arguments = arguments) for nmap_proto in nm[host].all_protocols(): protocol = nm[host][nmap_proto][int(masscan_port)]['name'] product = nm[host][nmap_proto][int(masscan_port)]['product'] version = nm[host][nmap_proto][int(masscan_port)]['version'] if 'tcpwrapped' not in protocol: if 'http' in protocol or protocol == 'sun-answerbook': if protocol == 'https' or protocol == 'https-alt': scan_url_port = 'https://' + str(host) + ':' + str(masscan_port) else: scan_url_port = 'http://' + str(host) + ':' + str(masscan_port) result = self.get_title(scan_url_port) self.mysqldb.save_target_port(username, target, scan_id, target_ip, str(masscan_port), protocol, product, version, result[0], result[1]) self.mysqldb.save_port(username, target, str(host) + ':' + str(masscan_port), target_ip, str(masscan_port), protocol, product, version, result[0], result[1]) continue self.mysqldb.save_target_port(username, target, scan_id, target_ip, str(masscan_port), protocol, product, version, '', '') self.mysqldb.save_port(username, target, str(host) + ':' + str(masscan_port), target_ip, str(masscan_port), protocol, product, version, '', '') scan_list.append(str(host) + ':' + str(masscan_port)) print('Masscan scanned.....\n') except Exception as e: print(e) pass finally: pass return scan_list
def GetOpenPort(self): HostInfos = {} try: mas = masscan.PortScanner() mas.scan(self.ip,ports='21,22,23,25,80,81,88,8080,8888,999,9999,7000,1433,1521,3306,3389,6379,7001,27017,27018') # 这里简单的扫一下普通端口即可 Results = mas.scan_result['scan'] AliveHosts = list(Results.keys()) if AliveHosts != []: for k, v in Results.items(): HostInfos[str(k)] = list(v['tcp'].keys()) return HostInfos except Exception as e: pass return HostInfos
def openport_scan(ip, port): start = time.time() mas = masscan.PortScanner() mas.scan(ip, ports=port, arguments='--max-rate 10000') #存储扫描结果 results = mas.scan_result open_ips = list(results['scan'].keys()) proto = 'tcp' ip_port = {} for open_ip in open_ips: open_ports = list(results['scan'][open_ip][proto].keys()) ip_port[open_ip] = ','.join( [str(open_port) for open_port in open_ports]) print(time.time() - start) print(ip_port) return ip_port
def scanmass(): ipcount = len(scope) print stat+"Executing Masscan against "+str(ipcount)+" total IPs" print stat+"Breaking IPs into digestible parts (<=4096)" if ipcount > 4096: for part in range(0,ipcount,4096): masscope.append(scope[part:part + 4096]) else: masscope.append(scope) partsnumber = len(masscope) print stat+"IPs broken into "+str(partsnumber)+" parts" partcount = 0 count = 0 for part in masscope: partcount += 1 sys.stdout.flush() sys.stdout.write("\r"+stat+"Scanning part "+str(partcount)+" of "+str(partsnumber)+" ") sys.stdout.flush() targets = ",".join(part) try: mas = masscan.PortScanner() mas.scan(targets, ports='443', arguments='--rate=1000') for host in mas.all_hosts: masshosts.append(host) count += 1 sys.stdout.write("- 443 on: "+str(count)) sys.stdout.flush() except (masscan.masscan.NetworkConnectionError): sys.stdout.write("- 443 on: "+str(count)) sys.stdout.flush() pass except (KeyboardInterrupt, SystemExit): goodresp = 0 while goodresp == 0: print "" resp = raw_input(warn+'Interrupt Caught. Want to kill all Massscan? (y) or this chunk (n): ') if "y" in resp: print warn+"Killing all Masscan parts" return masshosts elif "n" in resp: print stat+"Continuing with next part" goodresp = 1 else: print warn+"Invalid Option..." print "" print good+"Masscan complete. Total hosts with 443 open: "+str(count) return masshosts
def masscan_target(iprange): print(colored("[*] Discovering targets. Please wait...", 'yellow')) try: converted_list = [str(element) for element in portList] ports = ','.join(converted_list) mas = masscan.PortScanner() mas.scan(iprange, ports=ports, arguments='--max-rate 100000') for ipaddress in mas.scan_result["scan"]: for portfound in mas.scan_result["scan"][ipaddress]["tcp"]: if str(ipaddress) not in targetList: targetList[str(ipaddress)] = dict( {portfound: getAUTH.detect_auth(ipaddress, portfound)}) else: targetList[str(ipaddress)].update( {portfound: getAUTH.detect_auth(ipaddress, portfound)}) except: pass
def masscanresult(self, ipstr, thread): ''' 敏感端口扫描 :param ipstr: :param thread: :return: ''' mas = masscan.PortScanner() threads = '--max-rate ' + str(thread) mas.scan(ipstr, ports=self.ports, arguments=threads) for result in mas.scan_result['scan']: yuanzu = list(mas.scan_result['scan'].values()) port = list(yuanzu[0]["tcp"].keys()) for i in port: ipdata = str(i) self.portdict.append(ipdata)
def masscan_main(self, target, port): default_port = '80' if port == '': port = default_port mas = masscan.PortScanner() try: mas.scan(target, ports=port) big_result = mas.scan_result middle_result = big_result.get('scan') key = middle_result.keys() #print middle_result print key if key == '': print 'not found' return key except Exception as e: print e
def doMasscan(ip, ports): if not type(ports) is list: raise Exception("Illegal Arguments") try: mas = masscan.PortScanner() mas.scan(ip, ports=",".join(str(i) for i in ports), arguments='--wait 0') hosts_Info = mas.scan_result["scan"] outList = [] for key in hosts_Info: outList.append(key) return outList except masscan.masscan.NetworkConnectionError: return []
def doPortscan(hostname, ports, redundant): info = getDNSInfo(hostname) open_ports = [] if 'A' in info.keys(): target_ip = info['A'][0] if target_ip not in redundant.keys(): try: mas = masscan.PortScanner() mas.scan(target_ip, ports=ports, arguments='--max-rate 2000') results = mas.scan_result['scan'] for item in results[target_ip]['tcp'].keys(): open_ports.append(item) except Exception as e: logger.error(e) else: open_ports = redundant[target_ip] return open_ports