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

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

项目: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