Exemple #1
0
class Scanner(object):
    """
    Simplified nmap scanning and retrieval of MAC addresses
    """
    def __init__(self, ip=get_ip()):
        self.ip = ip
        self.nmap = PortScanner()
        self.scanned = False
        self.unknown = 0
        self.known = 0
        self.total = 0
        self.previous_total = 0
        self.previous_mac_vendors = []
        self.mac_vendors = None

    def scan(self):
        self.previous_mac_vendors = self.mac_vendors
        self.simple_scan()
        self.scanned = True
        self.total = self._connections()
        self.mac_vendors = self._mac_vendors()
        self.known = len(self.mac_vendors)
        self.unknown = self.total - self.known

    def simple_scan(self):
        self.nmap.scan(hosts=self.ip + '/24',
                       arguments='-n -sn -PE -PA21,23,80,3389')

    def _mac_vendors(self):
        if not self.scanned:
            self.simple_scan()

        hosts = self.nmap.all_hosts()

        macs = {host: self.nmap[host]['addresses'].get('mac', None)
                for host in hosts}
        mac_vendors = [(host, mac, vendor) for host in hosts
                       for mac, vendor in self.nmap[host]['vendor'].items()]

        logger.debug("Scanner._mac_vendors() - macs: %s\n mac_vendors: %s"
                     % (macs, mac_vendors))

        # nmap often doesn't produce current device MAC address
        if not macs[self.ip]:
            mac_vendors.append((self.ip, ":".join(re.findall('..', '%012x'
                               % get_mac())).upper(), None))

        return mac_vendors

    def _connections(self):
        try:
            return int(self.nmap.scanstats()['uphosts'])
        except AssertionError:
            self.simple_scan()
            return self._connections()

    def get_mac_vendors_json(self):
        if not self.scanned:
            self.scan()
        return json.dumps(self.mac_vendors)