def nmap_scan(data, host): #scan tcp ports if 'tcp' in data: nmap = nmap3.NmapScanTechniques() result = nmap.nmap_tcp_scan(host) #scan udp ports elif 'udp' in data: nmap = nmap3.NmapScanTechniques() result = nmap.nmap_udp_scan(host) #scan top ports elif 'top port' in data: nmap = nmap3.Nmap() result = nmap.scan_top_ports(host) #scan for subdomains elif 'subdomains' in data: nmap = nmap3.Nmap() result = nmap.nmap_dns_brute_script("domain") #scon for detect os elif 'os' in data: nmap = nmap3.Nmap() result = nmap.nmap_os_detection("your-host") #print in terminal with json format colored_json = highlight(json.dumps(result, indent=4, sort_keys=True), lexers.JsonLexer(), formatters.TerminalFormatter()) print("\n\n", colored_json)
def local_ports(request, ip="127.0.0.1", portrange=65535): """Scan all local ports Args: request (Object): [description] Returns: comma separated list in HttpResponse """ nmap_scanner = nmap3.Nmap() result = nmap_scanner.scan_top_ports(ip, args="--top-ports 10") open_ports = [] for host in result: print('Host: %s' % host) if "ports" in result[host]: for port in result[host]["ports"]: if port["state"] == "open": print('----------') print('Protocol : %s' % port["protocol"]) print ('port : %s\tstate : %s' % (port["portid"], port['state'])) print(port) open_ports.append(port) return open_ports
def callback(): self.textEdit.append('Performing OS scan on: ' + str(text_input) + '\n') nmap = nmap3.Nmap() version_result = nmap.nmap_version_detection(text_input) # pprint.pprint(version_result, width=61) try: self.textEdit.append('Port : ' + str(version_result[0]['port'])) self.textEdit.append('Protocol : ' + str(version_result[0]['protocol'])) self.textEdit.append('Reason : ' + str(version_result[0]['reason'])) self.textEdit.append( 'Method : ' + str(version_result[0]['service']['method'])) self.textEdit.append( 'OS type : ' + str(version_result[0]['service']['ostype'])) except (IndexError, KeyError): self.textEdit.append('Could not detect OS') try: if str(version_result[0]['service']['ostype']) == 'Linux': self.textEdit.append( 'Conn : ' + str(version_result[0]['service']['name'])) self.textEdit.append( 'Product : ' + str(version_result[0]['service']['product'])) self.textEdit.append( 'Version : ' + str(version_result[0]['service']['version'])) except: self.textEdit.append('Error retrieving values or timed out')
def analizeNetwork(netName): # read file with open('network-map.json', 'r') as myfile: data = myfile.read() # parse file jsonO = json.loads(data) if netName == 0: net = jsonO[NETWORK1]['map'] name = jsonO[NETWORK1]['networkName'] if netName == 1: net = jsonO[NETWORK2]['map'] name = jsonO[NETWORK2]['networkName'] nmap = nmap3.Nmap() fileOut = open( 'nmap-analysis' + name + "-" + str(time.localtime(time.time()).tm_mday) + "-" + str(time.localtime(time.time()).tm_mon) + '-tcp' + '.csv', 'w') for groups in net: group = groups['group'] fileOut.write('%s\n' % (group)) analizeGroups(groups, fileOut, nmap) fileOut.close()
def port_scan(self, target): """ 进行端口扫描 :param target: string 目标域名 :return: dict {"ip": [21, 22, ...]} """ nmap = nmap3.Nmap() # 扫描常用端口 print("正在进行常用端口扫描...") res = nmap.scan_top_ports(target) # 从结果中获取目标IP地址 target_ip = list(res.keys())[0] # 从结果中获取目标开放端口 for target_info in list(res.values())[0]: if target_info["state"] in self._port_status: self._open_ports.append(target_info["portid"]) self._port_scan_res["ip"] = target_ip self._port_scan_res["open_ports"] = self._open_ports print("常用端口扫描结束") return self._port_scan_res
def __init__(self, host, refresh_rate, metrics): threading.Thread.__init__(self) self.host = host self.refresh_rate = refresh_rate self.nmap = nmap3.Nmap() self.metrics = metrics self.logger = logging.getLogger(f"exporter:{self.host}")
def __init__(self): # Initiate the config.ini file config = configparser.ConfigParser() try: config.read( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini')) except FileExistsError as err: print( Color_Monitor.background_FAIL + '[x] File exists error: {}'.format(err), Color_Monitor.background_ENDC) # Initiate useful variable self.default_always_arg = "--privileged" self.default_name = "nmap_report" self.nmap = nmap3.NmapScanTechniques() self.nmap_version = nmap3.Nmap() # Temp data name self.filename_tmp = None self.directoryname_nmap_scan_tmp = None self.directoryname_nmap_tree_tmp = None # Coordinator of path self.path_data_nmap_save_scan = config['Data_path'][ 'path_save_nmap_scan'] self.path_data_nmap_save_tree = config['Data_path'][ 'path_save_nmap_tree'] self.path_data_metasploit_save_scan = config['Data_path'][ 'path_save_metasploit_scans'] self.path_data_metasploit_save_tree = config['Data_path'][ 'path_save metasploit_trees']
def getOpenPorts(self): logging.info("Scanning open ports for host {}".format(str(self._ip))) nmap = nmap3.Nmap() ports = nmap.nmap_version_detection(str(self._ip)) try: for port in ports: portid = port["port"] protocol = port["protocol"] try: product = port["service"]["product"] except: product = "" try: version = port["service"]["version"] except: version = "" try: cpe = port["cpe"][0]["cpe"] except: cpe = "" logging.info( "New service found [Port: {}, Protocol: {}]".format( portid, protocol)) self._services.append( Service(product, version, portid, protocol, cpe)) except: logging.error("Error scanning open ports, host: {}".format( str(self._ip)))
def nmapFullDetailed(IP, ports): logging.info("Starting a detailed nmap scan with masscan results") nmap = nmap3.Nmap() scan = nmap.nmap_version_detection( str(IP), args="-sC -p {} -T5 --min-rate=1000 --max-retries=2".format(ports)) return scan #JSON Object
def dns_nmap(self): nmap = nmap3.Nmap() result = nmap.nmap_dns_brute_script(f"{self.address}") print(colored.green("[ + ] HOST ") + "" + "\t" + "\t" + colored.blue("[ + ] IP ")) for i in result: text = i["hostname"] + "\t" + i["address"] print(text)
def get_ip(): nmap = nmap3.Nmap() results = nmap.scan_top_ports("192.168.1.0/24", args="-sn") res1.set(results) ip = list(results.keys()) for i in ip: print(i)
def users_server_check(): original = ServerConfig(flask_users.addr, flask_users.port) alt = ServerConfig(flask_users_alt.addr, flask_users_alt.port) nm = nmap3.Nmap() while True: before_scan = datetime.now() res = nm.scan_top_ports(f"{original.addr}", args=f"-p {original.port}") state = res[f"{original.addr}"]["ports"][0]["state"] #print(f"{original.addr}:{original.port}->{state}") after_scan = datetime.now() # Change to the back-up server if the original is down if state == 'closed' and (flask_users.addr != alt.addr or flask_users.port != alt.port): flask_users.set(alt.addr, alt.port) log2term('D', 'Users server set to be the alternative server') # Change to the original server if it's back up if state == 'open' and (flask_users.addr == alt.addr and flask_users.port == alt.port): flask_users.set(original.addr, original.port) log2term('D', 'Users server set to be the default server') time.sleep(SCAN_PERIOD - (after_scan - before_scan).total_seconds())
def scanPort(self): port_s = nmap3.Nmap() port_o = port_s.nmap_version_detection(self.host) for x in range(len(port_o[self.host]["ports"])): OPEN_PORT = { "protocol": "", "portid": "", "state": "", "service": "" } OPEN_PORT["protocol"] = port_o[self.host]["ports"][x]["protocol"] OPEN_PORT["portid"] = port_o[self.host]["ports"][x]["portid"] OPEN_PORT["state"] = port_o[self.host]["ports"][x]["state"] OPEN_PORT["service"] = port_o[ self.host]["ports"][x]["service"]["name"] if "product" in port_o[self.host]["ports"][x]["service"]: OPEN_PORT["version"] = port_o[ self.host]["ports"][x]["service"]["product"] if "version" in port_o[self.host]["ports"][x]["service"]: OPEN_PORT["version"] = OPEN_PORT["version"] + port_o[ self.host]["ports"][x]["service"]["version"] self.ports.append(OPEN_PORT)
def __init__(self): self.nmap = nmap3.Nmap() self.badges = badges() self.banner = banner() self.details = { 'Name': "nmap", 'Authors': ['enty8080'], 'Description': "Nmap scan plugin for ZetaSploit.", 'Comments': [''] } self.commands = { 'scanner': { 'port_scan': { 'Description': "Run port scan on host.", 'Usage': "port_scan <host>", 'ArgsCount': 1, 'NeedsArgs': True, 'Args': list(), 'Run': self.port_scan } } }
def scanNetwork(self): self.ips.clear() self.macs.clear() self.os.clear() cpt = 0 nmap = nmap3.Nmap() ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=str(self.getNetwork())), timeout=2) for snd, rcv in ans: self.ips.append(rcv[ARP].psrc) self.macs.append(rcv[Ether].src) print('/!\ This operation may take a while') for ip in self.ips: print('[*] Searching OS for ' + str(ip)) resultnmap = nmap.nmap_os_detection(ip) try: self.os.append(resultnmap[0]['name']) except IndexError: self.os.append('') sizeIP = len(self.ips) sizeMAC = len(self.macs) print('\r\n') if sizeIP == sizeMAC: print('IP: ' + ' ' * 15 + 'MAC: ' + ' ' * 20 + 'OS: ') for i in range(sizeIP): print(self.ips[i] + ' ' * 7 + self.macs[i] + ' ' * 7 + self.os[i]) print('\r\n')
def nmap(): disegno() print("| NMAP |") print("+-----------------------------------------------+") import nmap3 import json ip = input("Insert specific IP or \"<IP>/24\" for entire network: ") print("Port range:\n1) Default \"1-100\"\n2) Custom\n3) All") x = scelta(1, 3) if x == 1: port = "1-100" elif x == 2: rangemin = input("Port range min: ") rangemax = input("Port range max: ") port = str(rangemin) + "-" + str(rangemax) else: port = "1-65535" print("\n") nmap = nmap3.Nmap() results = nmap.scan_top_ports(ip, args="-p" + port) # Creo file json [report] con i dati di results report = json.dumps(results, sort_keys=True) # Trasformo da json in a dizionario data = json.loads(report) testo = "" # Stampo il dizionario for i, info in data.items(): testo += "Scanned IP [{}]\n".format(i) for categoria, dizionario in info.items(): if categoria == "hostname": if len(dizionario) != 0: for dettaglio, valoreDettaglio in dizionario[0].items(): testo += "{} : {}\n".format(dettaglio, valoreDettaglio) else: testo += "name : Not identified\ntype : Not identified\n" elif categoria == "ports": testo += "PORT PROTOCOL SERVICE STATUS\n" for dettaglio in dizionario: for porta, valorePorta in dettaglio.items(): if porta == "portid" or porta == "protocol" or porta == "state": testo += "{:<13s}".format(valorePorta) if porta == "service": testo += "{:<15s}".format(valorePorta["name"]) testo += "\n" testo += "\n" # Rinomino il file x = "MP_" x += ip.replace("/24", "_EN") x += "_port_" + str(port) wfile = open("./Nmap/MP/" + x + ".txt", "w") wfile.write(testo) wfile.close() print(testo) backToMenu()
def nmap(host): nmap = nmap3.Nmap() time.sleep(10) version_result = nmap.nmap_version_detection(host) print("Version Result:") print(version_result) if (version_result): print("Inside Scan results") file = open('scanresults.json', 'w+') jsonResult = json.dumps(version_result) file.write(jsonResult) file.close() else: file = open('scanresults.json', 'r') jsonResult = file.read() responseDict = eval(jsonResult) resultKeys = list(responseDict.keys()) resultDict = {} resultDict['hostname'] = resultKeys[0] resultDict['scannedResult'] = responseDict[resultKeys[0]] now = datetime.now() resultDict['scannedDate'] = now.strftime("%m/%d/%Y, %H:%M:%S") resultDict['rpcInfo'] = helper.rpcServiceInfo(host) resultDict['zapInfo'] = helper.zapSpiderInfo(host) print(resultDict) mongoObj = resultDict.copy() if os.getenv('MONGO'): id = db.storeScanResult(mongoObj) print("Id:" + str(id)) return json.dumps(resultDict)
def findOpenPorts(port, scanRange = 255,network =None): #network must be an iP address that ends in .0 ex 192.168.1.0 maxIP = scanRange Avail_IP_List = [] #Get IP network of local machine IP_network = returnIPNet() #if not ip address was added us the local IP if(network != None): IP_network = network #Grab Prefex IP_prefex = IP_network[:-1] #Start nmap connection nmap = nmap3.NmapScanTechniques() #ping all ips in network and generate list of machines for location in range(1,maxIP): IP_Address = IP_prefex + str(location) results = nmap.nmap_ping_scan(IP_Address) print("Pinging " + IP_Address + " ...") try: data = results[0] Avail_IP_List.append(IP_Address) print("Machine found at " + IP_Address + "...") except: continue #port scanning phase ports = nmap3.Nmap() print("Port " + str(port) + " scan") a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) openPortList = [] #scan for open port useing list of active machines for IPs in Avail_IP_List: location = (IPs, port) result_of_check = a_socket.connect_ex(location) if result_of_check == 0: print("Port " + str(port) + " on " + IPs + " is open adding to list") openPortList.append(IPs) else: print("Port on " + IPs + " is not open") a_socket.close() return openPortList
def scan_top(h): global nm global s1 #bar = progressbar.ProgressBar() nm = nmap3.Nmap() #for i in bar(range(100)): s1 = nm.scan_top_ports('{}'.format(h)) return s1
def getOsInformation(self, targetIP): """Taranan ip'nin os bilgilerini getirir""" nmap = nmap3.Nmap() result = nmap.nmap_os_detection(targetIP) if result: return result[0].get("name") else: return "Unable to determined"
def scan_dns(h): global nm global s2 bar = progressbar.ProgressBar() nm = nmap3.Nmap() s2 = nm.nmap_dns_brute_script(f'{h}') parse_dns(s2) return s2
def Top_port(self, Host, Timing=4): print("Loading ........................................") self.Host = sock.gethostbyname(self.Host) HOST_lib = nmap3.Nmap() System = HOST_lib.scan_top_ports(self.Host, self.Timing) for z in System[self.Host]: print(z['portid'], z['service']['name'], z['state'])
def scan(ip_addr): try: nmap = nmap3.Nmap() results = nmap.nmap_os_detection(ip_addr) print(f"nmap results: {results}") return results except Exception as err: print(f"Could not preform network scan, Device is inactive... {err}") return None
def get_ip(self): nmap = nmap3.Nmap() results = nmap.scan_top_ports("172.25.1.0/24", args="-sn") ip = list(results.keys()) ip = ip[:-2] for i in ip: self.plainTextEdit.appendPlainText(i) self.breached_ip()
def scan_vers(h): global nm global s6 bar = progressbar.ProgressBar() nm = nmap3.Nmap() for i in bar(range(100)): s6 = nm.nmap_version_detection('{}'.format(host)) time.sleep(0.5) return s6
def scan_subnet(h): global nm global s5 bar = progressbar.ProgressBar() nm = nmap3.Nmap() for i in bar(range(100)): s5 = nm.nmap_subnet_scan('{}'.format(h)) time.sleep(0.5) return s5
def scan_list(h): global nm global s3 bar = progressbar.ProgressBar() nm = nmap3.Nmap() for i in bar(range(100)): s3 = nm.nmap_list_scan('{}'.format(h)) time.sleep(0.5) return s3
def scan_os(h): global nm global s4 #bar = progressbar.ProgressBar() nm = nmap3.Nmap() #for i in bar(range(100)): s4 = nm.nmap_os_detection('{}'.format(h)) #time.sleep(0.5) parse_os(s4) return s4
def perform_tcp_scan(): logging.debug('[TCP SCAN] started') nmap = nmap3.Nmap() result = nmap.nmap_version_detection( None, "-sV -p- --script ssl-cert -vv -O -iL ips_to_scan.txt") remove_keys(result) # print(result) # logging.debug(result) logging.debug('[TCP SCAN] done') return result
def nmap_port_scanning(self) -> str: # Prints ports that are open and returns "Completed" when done try: nmap = nmap3.Nmap() results = nmap.scan_top_ports(f"{self.website_address}") ip_address = self.get_ip_address() for port in results[ip_address]: if port['state'] == "open": print(f"Port {port['portid']}: {port['state']}") return "Completed" except Exception: return "Unable to perform scan"