Python nmap.PortScanner() Examples

The following are 30 code examples of nmap.PortScanner(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module nmap , or try the search function .
Example #1
Source File: nmap.py    From platypush with MIT License 7 votes vote down vote up
def scan(self, hosts: str, ports: str, args: str, sudo: bool = False) -> Dict[str, Any]:
        """
        Perform a port scan towards a certain host or network.

        :param hosts: Host name/IP or IP subnet to scan (e.g. ``192.168.1.0/24``).
        :param ports: Port number, (comma-separated) list or (dash-separated) range to scan (default: all).
        :param args: Additional command line arguments for nmap.
        :param sudo: Execute nmap as root through sudo (default: ``False``).
        :return: Scan results, as an ip -> host map.
        """
        import nmap
        nm = nmap.PortScanner()
        return nm.scan(hosts=hosts, ports=ports, arguments=args, sudo=sudo).get('scan')


# vim:sw=4:ts=4:et: 
Example #2
Source File: osdetect.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def osdetect(ip):
    # sys.stdout.write(Bcolors.RED + "\nOS:\n" + Bcolors.ENDC)
    nm = nmap.PortScanner()
    try:
        result = nm.scan(hosts=ip, arguments='-sS -O -vv -n -T4 -p 80,22,443')
        for k, v in result.get('scan').items():
            if v.get('osmatch'):
                for i in v.get('osmatch'):
                    console('OSdetect', ip, i.get('name') + '\n')
                    return i.get('name')
            else:
                break
    except (xml.etree.ElementTree.ParseError, nmap.nmap.PortScannerError):
        pass
    except Exception as e:
        console('OSdetect', ip, 'None\n')
        logging.exception(e) 
Example #3
Source File: utils.py    From 3vilTwinAttacker with MIT License 6 votes vote down vote up
def run(self):
        nm = PortScanner()
        a=nm.scan(hosts=self.gateway, arguments='-sU --script nbstat.nse -O -p137')
        for k,v in a['scan'].iteritems():
            if str(v['status']['state']) == 'up':
                try:
                    ip = str(v['addresses']['ipv4'])
                    hostname = str(v['hostscript'][0]['output']).split(',')[0]
                    hostname = hostname.split(':')[1]
                    mac = str(v['hostscript'][0]['output']).split(',')[2]
                    if search('<unknown>',mac):mac = '<unknown>'
                    else:mac = mac[13:32]
                    self.result = ip +'|'+mac.replace('\n','')+'|'+hostname.replace('\n','')
                    self.emit(SIGNAL('Activated( QString )'),
                    self.result)
                except :
                    pass 
Example #4
Source File: portscan.py    From vulscan with MIT License 6 votes vote down vote up
def port_scan(self,):
        host = self.ip
        nm = nmap.PortScanner()
        self.state = 'scanning'
        try:
            nm.scan(host) #arguments='-T5 -p 1-65535 -sV -sT -Pn --host-timeout 3600'
            ports = nm[host]['tcp'].keys()
            report_list = []
            for port in ports:
                report = {}
                state = nm[host]['tcp'][port]['state']
                service = nm[host]['tcp'][port]['name']
                product = nm[host]['tcp'][port]['product']
                report['port'] = port
                report['state'] = state
                report['service'] = service
                report['product'] = product
                if state == 'open':
                    report_list.append(report)
            print report_list
            self.state = 'scanned'
            self.report = json.dumps(report_list)
            return json.dumps(report_list)
        except Exception as e:
            print e 
Example #5
Source File: AutoBrowser.py    From AutoBrowser with GNU General Public License v3.0 6 votes vote down vote up
def get_ports_from_report(nmap_report):
    """
    This function is responsible to make a generator object from Nmap report
    :param nmap_report: Nmap report location
    :return:
    """

    scanner = PortScanner()
    try:
        scan_result = scanner.analyse_nmap_xml_scan(open(nmap_report.strip('"')).read())
        for host in scan_result['scan']:
            try:
                LOGGER.info("%s - Total ports to browse: %d" % (host, len(scan_result['scan'][host]['tcp'])))
                for port, port_details in scan_result['scan'][host]['tcp'].items():
                    try:
                        yield host, port, port_details
                    except IndexError:
                        pass
            except KeyError:
                pass
    except Exception as e:
        LOGGER.error("Error: %s" % e)
        raise StopIteration 
Example #6
Source File: nmap-osdetection.py    From HomePWN with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        if not has_nmap:
            print_error("To launch this module install nmap (sudo apt install nmap)")
            return
        print("Trying to get OS")
        nm = nmap.PortScanner()
        try:
            timeout = int(self.args["timeout"])
        except:
            timeout = 6
        result = nm.scan(self.args["rhost"], arguments=f"-O --host-timeout {timeout}")
        try:
            state = result["scan"][self.args["rhost"]]["status"]["state"]
        except:
            state = "down"
        print_info(f"Host state: <b>{state}</b>")

        try:
            print_info(f'OS: <b>{result["scan"][self.args["rhost"]]["osmatch"][0]["name"]}</b>')
        except:
            print_info("OS not found") 
Example #7
Source File: os_scan.py    From vault with MIT License 6 votes vote down vote up
def __init__(self, url, ip):
        self.is_root()

        try:
            self.nm = nmap.PortScanner()
        except nmap.PortScanner:
            colors.error('Nmap not found')
            sys.exit(1)
        except Exception as e:
            print(e)
            sys.exit(1)

        if url is not None and ip is not None:
            colors.error('Please provide either the URL or the IP address...')
            sys.exit(1)

        if ip is not None:
            self.target = ip
        elif url is not None:
            self.target = self.check_url(url)
        else:
            colors.error('Please provide URL or the IP address to scan...') 
Example #8
Source File: information.py    From RubyRoseBot with Mozilla Public License 2.0 6 votes vote down vote up
def portscan(self, ctx, host:str, ports:str):
        """Uses nmap to scan the specified ports from the specified host"""
        await ctx.channel.trigger_typing()
        forbidden_hosts = ["localhost", "0.0.0.0", "127.0.0.1"]
        if host in forbidden_hosts:
            await ctx.send(Language.get("information.forbidden_host", ctx).format(host))
            return
        scanner = nmap.PortScanner()
        try:
            host = socket.gethostbyname(host)
        except socket.gaierror:
            await ctx.send("`{}` is not a valid address".format(host))
            return
        ports = scanner.scan(host, ports)["scan"][host]["tcp"]
        results = []
        for port, data in ports.items():
            service = data["name"]
            if service == "":
                service = Language.get("information.unknown", ctx)
            results.append(Language.get("information.port_status", ctx).format(port, service, data["state"]))
        await ctx.send(xl.format("\n".join(results))) 
Example #9
Source File: nmap.py    From SecurityManageFramwork-SeMF with GNU General Public License v3.0 6 votes vote down vote up
def nmap_alive_lists(segment):
    nm = nmap.PortScanner()
    try:
        nm.scan(hosts=segment,arguments='-n -sn')
    except:
        return None
    return nm.all_hosts() 
Example #10
Source File: worm.py    From NetWorm with MIT License 6 votes vote down vote up
def scan_ssh_hosts():
    """
    Scans all machines on the same network that
     have SSH (port 22) enabled

    Returns:
        IP addresses of hosts
    """
    logger.debug("Scanning machines on the same network with port 22 open.")


    logger.debug("Gateway: " + gateway)

    port_scanner = nmap.PortScanner()
    port_scanner.scan(gateway + "/24", arguments='-p 22 --open')

    all_hosts = port_scanner.all_hosts()

    logger.debug("Hosts: " + str(all_hosts))
    return all_hosts 
Example #11
Source File: worm.py    From NetWorm with MIT License 6 votes vote down vote up
def scan_ftp_hosts():
    """
    Scans all machines on the same network that
     have FTP (port 21) enabled

    Returns:
        IP addresses of hosts
    """
    logger.debug("Scanning machines on the same network with port 21 open.")

    port_scanner = nmap.PortScanner()
    port_scanner.scan(gateway + '/24', arguments='-p 21 --open')
    all_hosts = port_scanner.all_hosts()

    logger.debug("Hosts: " + str(all_hosts))
    return all_hosts 
Example #12
Source File: NmapScannerJSONGenerate.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def __init__(self):
        self.nmsc = nmap.PortScanner() 
Example #13
Source File: nmap_all_server.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def nmap_allip(self,nmap_net):
        '''
        扫描网段中存活主机
        '''
        nm = nmap.PortScanner()
        nm.scan(hosts=nmap_net,arguments = ' -n -sP -PE')
        # nm.scan(hosts=nmap_net,arguments = ' -n -PA -PS')
        hostlist = nm.all_hosts()
        return hostlist 
Example #14
Source File: 3_6_find_network_interface_status.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def get_interface_status(ifname):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip_address = socket.inet_ntoa(fcntl.ioctl(
        sock.fileno(),
        0x8915, #SIOCGIFADDR, C socket library sockios.h
        struct.pack(b'256s', bytes(ifname[:15], 'utf-8'))
    )[20:24])
    nm = nmap.PortScanner()         
    nm.scan(ip_address, SAMPLE_PORTS)      
    return nm[ip_address].state() 
Example #15
Source File: nmap.py    From w12scan-client with MIT License 5 votes vote down vote up
def nmapscan(host, ports):
    # 接受从masscan上扫描出来的结果
    # 为了可以多线程使用,此函数支持多线程调用
    nm = nmap.PortScanner()
    argument = "-sV -sS -Pn --host-timeout 1m -p{}".format(','.join(ports))
    try:
        ret = nm.scan(host, arguments=argument)
    except nmap.PortScannerError:
        logger.debug("Nmap PortScannerError host:{}".format(host))
        return None
    except:
        return None

    # debug
    elapsed = ret["nmap"]["scanstats"]["elapsed"]
    command_line = ret["nmap"]["command_line"]
    logger.debug("[nmap] successed,elapsed:%s command_line:%s" % (elapsed, command_line))

    if host in ret["scan"]:
        try:
            result = ret["scan"][host]["tcp"]
        except KeyError:
            return None
        return result

    return None 
Example #16
Source File: __init__.py    From isf with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def port_scan(protocol, target, port):
    nm = nmap.PortScanner()
    try:
        if str(protocol).upper() == "TCP":
            nm.scan(hosts=target, ports=str(port), arguments='-Pn -sT ')
            return nm
        elif str(protocol).upper() == "UDP":
            print_status("UDP Scan requires root privileges will using sudo to scan target ")
            nm.scan(hosts=target, ports=str(port), arguments='-Pn -sU ', sudo=True)
            return nm
    except Exception as err:
        print_error(err)
        return None 
Example #17
Source File: sshDictionaryAttack.py    From ssh-password-cracker with GNU General Public License v3.0 5 votes vote down vote up
def nmapScan(tgtHost):
	nmapScan = nmap.PortScanner()
	nmapScan.scan(tgtHost, '22')
	state = nmapScan[tgtHost]['tcp'][22]['state']
	return state 
Example #18
Source File: nmap-portscan.py    From HomePWN with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        if not has_nmap:
            print_error("To launch this module install nmap (sudo apt install nmap)")
            return
        print("Scanning...")
        nm = nmap.PortScanner()
        try:
            timeout = int(self.args["timeout"])
        except:
            timeout = 6

        result = nm.scan(self.args["rhost"], self.args["rports"], arguments=f"-s{self.args['scan']} --host-timeout {timeout}")
        try:
            state = result["scan"][self.args["rhost"]]["status"]["state"]
        except:
            state = "down"
        hs = "Host state"
        print("")
        print(hs)
        print("-"*len(hs))
        print_info(state)
        if state == "down":
            return
        ports = result["scan"][self.args["rhost"]]["tcp"]
        msg = "Services found"
        print(msg)
        print("-"*len(msg))
        found = False
        for key, value in ports.items():
            if value["state"] == "open":
                found = True
                print_info(f"{key}  -  {value['name']}")
        if not found:
            print_info("No open ports") 
Example #19
Source File: portscan.py    From pynmap with GNU General Public License v3.0 5 votes vote down vote up
def online(self,ip):
        """ Check if target is online using nmap -sP probe """
        # -sP probe could be blocked. Check for common ports. 
        # there could be solution with socket module. 
        try:
            nm = nmap.PortScanner()
            nm.scan(hosts=ip, arguments='-sP')
            result = nm[ip].state()
        except KeyError:
            pass
        else:
            if result == 'up':
                return True
            else:
                return False 
Example #20
Source File: NmapScannerAsyncFTP.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def __init__(self):
                self.nmsync = nmap.PortScanner()
                self.nmasync = nmap.PortScannerAsync() 
Example #21
Source File: NmapScanner.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def __init__(self): 
        self.nmsc = nmap.PortScanner() 
Example #22
Source File: NmapScannerAsync.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def __init__(self):
                self.nmsync = nmap.PortScanner()
                self.nmasync = nmap.PortScannerAsync() 
Example #23
Source File: 13_6_find_network_interface_status.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def get_interface_status(ifname):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip_address = socket.inet_ntoa(fcntl.ioctl(
        sock.fileno(),
        0x8915, #SIOCGIFADDR, C socket library sockios.h
        struct.pack(b'256s', bytes(ifname[:15], 'utf-8'))
    )[20:24])
    nm = nmap.PortScanner()         
    nm.scan(ip_address, SAMPLE_PORTS)      
    return nm[ip_address].state() 
Example #24
Source File: test_nmap.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def setup_module():
    global nm
    nm = nmap.PortScanner() 
Example #25
Source File: tasks.py    From xunfengES with GNU General Public License v3.0 5 votes vote down vote up
def hostScan(host, ports, arguments, queue):
    """
    host - 单台主机: 127.0.0.1
    ports - 多个端口: 21,22,135,137,445,3389
    arguments - 扫描参数: -Pn -sV
    """
    try:
        nm = nmap.PortScanner()
        nm.scan(hosts=host, ports=ports, arguments=arguments)

        if "tcp" in nm[host].all_protocols():
            for port in nm[host]["tcp"].keys():
                if nm[host]["tcp"][port]["state"] == "open":
                    #nm[host]["tcp"][port]["extrainfo"] match codes
                    pattern = re.compile('(php)|(aspx?)|(jsp)|(python)', re.I)
                    match = pattern.search(nm[host]["tcp"][port]["extrainfo"])
                    if match:
                        codes = match.group().lower()
                    else:
                        codes = ""
                    result = {
                        "id": get_id_md5(host, port),
                        "tags": "hostScan",
                        "host": host,
                        "port": port,
                        "product": nm[host]["tcp"][port]["product"],
                        "state": nm[host]["tcp"][port]["state"],
                        "version": nm[host]["tcp"][port]["version"],
                        "server": nm[host]["tcp"][port]["name"],
                        "codes": codes,
                        "extrainfo": nm[host]["tcp"][port]["extrainfo"],
                        "reason": nm[host]["tcp"][port]["reason"],
                        "cpe": nm[host]["tcp"][port]["cpe"],
                        "queue": queue
                    }
                    getPoolBR().lpush(RedisConfig.HOSTSCANKEY, json.dumps(result))
    except Exception as e:
        pass 
Example #26
Source File: nmap_scan.py    From violent-python3 with GNU General Public License v3.0 5 votes vote down vote up
def nmap_scan(tgt_host, tgt_port):
    nmscan = nmap.PortScanner()
    nmscan.scan(tgt_host, tgt_port)
    state = nmscan[tgt_host]['tcp'][int(tgt_port)]['state']
    print("[+] " + tgt_host + " tcp/" + tgt_port + " " + state) 
Example #27
Source File: nmap.py    From SecurityManageFramwork with GNU General Public License v3.0 5 votes vote down vote up
def nmap_port(host,port):
    nm = nmap.PortScanner()
    nm.scan(host,port)
    if nm[host].state()== 'up':
        return  nm[host]['tcp'][port]


#获取目标主机内所有开放端口 
Example #28
Source File: nmap.py    From SecurityManageFramwork with GNU General Public License v3.0 5 votes vote down vote up
def nmap_host_all(host):
    nm = nmap.PortScanner()
    nm.scan(host,'0-65535')
    try:
        if nm[host].state()== 'up':
            return nm[host]['tcp']
        else:
            return 0
    except:
        return 0
    
#获取指定网段内全部存活主机 
Example #29
Source File: nmap.py    From SecurityManageFramwork with GNU General Public License v3.0 5 votes vote down vote up
def nmap_alive_lists(segment):
    nm = nmap.PortScanner()
    try:
        nm.scan(hosts=segment,arguments='-n -sn')
    except:
        return None
    return nm.all_hosts() 
Example #30
Source File: nmap_port_scanner.py    From pycurity with GNU General Public License v3.0 5 votes vote down vote up
def nmapScan(tgtHost, tgtPort):
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost, tgtPort)
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print(" [*] " + tgtHost + " tcp/" +tgtPort + " " + state)