Beispiel #1
0
    def run(self, params={}):
        hosts_to_scan = params.get("hosts")
        ports_to_scan = params.get("ports")
        nmap_args = params.get("arguments")
        sudo = params.get("sudo")  # defaulted to False

        if not len(ports_to_scan):
            ports_to_scan = None

        if not len(nmap_args):
            nmap_args = None

        scanner = PortScanner()

        try:
            scanner.scan(hosts=hosts_to_scan,
                         ports=ports_to_scan,
                         arguments=nmap_args,
                         sudo=sudo)
        except PortScannerError as e:
            self.logger.error("An error occurred: %s" % e)
        else:
            scanned_hosts = scanner.all_hosts()  # grab hosts that were scanned
            results = list(map(lambda host: scanner[host],
                               scanned_hosts))  # create list of scan results

            results = komand.helper.clean(results)

            return {"result": results}
 def portscannerWorkerProcess(self, mainSubQ, subMainQ, lock):
     nm = PortScanner()
     return_data = {'header': 'initialize', 'info': '', 'payload': ''}
     while True:
         elapsed_start = time.time()
         lock.acquire()
         try:
             print()
             subMainQ.put(return_data)
             instructions = None
             while instructions is None:
                 instructions = mainSubQ.get()
         finally:
             lock.release()
         if instructions['header'] == 'terminate': return
         ip = instructions['payload']
         nm.scan(ip)
         try:
             return_data['header'] = 'result'
             return_data['info'] = ip
             return_data['payload'] = {
                 **nm[ip],
                 **{
                     'elapsed': time.time() - elapsed_start
                 }
             }
         except Exception as error:
             return_data['header'] = 'error'
             return_data['info'] = ip
             return_data['payload'] = str(error)
Beispiel #3
0
    def run(self):
        """Scan the network for MAC addresses and keep tabs on which devices
            are present or have left"""

        nm = PortScanner()

        while self.running:

            # Decrement all hosts
            for mac in self.macs:
                if self.macs[mac] > 0:
                    self.macs[mac] -= 1;

            nm.scan(hosts = self.local_net, arguments = self.nmap_args)

            # Mark each host found as present unless it is not tracked
            for host in nm.all_hosts():
                try:
                    mac = nm[host]['addresses']['mac']
                    if mac in self.macs:
                        self.macs[mac] = self.timeout + 1 # Immediately decremented
                except KeyError:
                    # nmap didn't get the MAC?
                    # Just ignore it I guess
                    pass
Beispiel #4
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)
Beispiel #5
0
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
 def _run_nmap_scan(self):
     """Run nmap and return the result."""
     options = self._build_options()
     if not self._scanner:
         self._scanner = PortScanner()
     _LOGGER.debug("Scanning %s with args: %s", self._hosts, options)
     for attempt in range(MAX_SCAN_ATTEMPTS):
         try:
             result = self._scanner.scan(
                 hosts=" ".join(self._hosts),
                 arguments=options,
                 timeout=TRACKER_SCAN_INTERVAL * 10,
             )
             break
         except PortScannerError as ex:
             if attempt < (MAX_SCAN_ATTEMPTS - 1) and NMAP_TRANSIENT_FAILURE in str(
                 ex
             ):
                 _LOGGER.debug("Nmap saw transient error %s", NMAP_TRANSIENT_FAILURE)
                 continue
             raise
     _LOGGER.debug(
         "Finished scanning %s with args: %s",
         self._hosts,
         options,
     )
     return result
    def __portscannerWorkerThreads(self, fetch_id, lock):
        nm = PortScanner()
        while len(type(self).__data[fetch_id]['hosts_to_scan'])>0:
            elapsed_start = time.time()
            lock.acquire()
            if len(type(self).__data[fetch_id]['hosts_to_scan']) == 0: break
            try:
                ip = type(self).__data[fetch_id]['hosts_to_scan'][0]
                type(self).__data[fetch_id]['hosts_to_scan'].remove(ip)
            finally:
                lock.release()
            nm.scan(ip)
            if fetch_id != type(self).__data['current']:
                return
            try:
                type(self).__data[fetch_id]['host_details'][ip] = nm[ip]
                type(self).__data[fetch_id]['host_details'][ip]['elapsed'] = time.time() - elapsed_start

            except:
                continue

            lock.acquire()
            try:
                type(self).__data[fetch_id]['host_details'] = \
                    self.reorderDictByNumericKey(type(self).__data[fetch_id]['host_details'], 'key')
                type(self).__data[fetch_id]['details'] = 'Progress: {} / {}'.format(
                    len(type(self).__data[fetch_id]['host_details']),
                    len(type(self).__data[fetch_id]['valid_hosts'])
                )
            finally:
                type(self).__lg.log('Finished scanning ports @ {}'.format(ip))

                lock.release()
Beispiel #8
0
def check_passive_port_task(request, module_key):

    module = Module.objects.get(id=module_key)
    debug(module, ("begin",))
    events = ModuleEvent.objects.filter(module=module).filter(back_at=None)

    portscanner = PortScanner()
    result = None
    try:
        if not module.check_port:
            raise Exception("Improperly configured")
        portscanner.scan(arguments = NMAP_ARGS, ports=str(module.check_port), hosts=module.host.encode('ascii','ignore'))

        now = datetime.datetime.now()

        host = portscanner.all_hosts()[0]
        if 'open' == portscanner[host]['tcp'][module.check_port]['state']:
            debug(module, "Port open")
            for event in events:
                event.back_at = now
                event.save()
                debug(module,"Site is back online %s" % module.name)
        else:
            if not events:
                _create_new_event(module, "off-line", now, None, "Port is closed")

    except KeyError, e:
        pass
Beispiel #9
0
    def sort_alive_hosts(self) -> None:
        """
        Make fast pingscan for all hosts to check
        if it needed to be scanned with TLS-Scanner
        (reject all offline hosts)
        :return: None
        """
        nm = PortScanner()
        online_hosts = self._remove_already_scanned_hosts(self.hosts)
        online_hosts = self.sort_hosts_by_product(online_hosts)
        hosts_ip = list(online_hosts.keys())
        groups = self._grouper(self.n, hosts_ip)
        groups = [list(group) for group in groups]
        groups_len = len(groups)

        for index, group in enumerate(groups):
            print(f"│ Do pingscan for {self.n} hosts ({index}/{groups_len})")
            group_ips = [ip for ip in group if ip]
            hosts_in_nmap_format = " ".join(group_ips)
            nm.scan(
                hosts=hosts_in_nmap_format,
                arguments=DefaultTlsScannerValues.NMAP_PING_SCAN_ARGS,
            )
            results = nm.all_hosts()
            alive_hosts_group = [
                ip for ip in results if nm[ip]["status"]["state"] == "up"
            ]
            groups[index] = alive_hosts_group

        print(f"└ Done pingscan for {len(hosts_ip)} hosts")
        groups_flat = [host for group in groups for host in group]
        self.alive_hosts = groups_flat
        self._set_ping_status()
Beispiel #10
0
 def get_ports(self,
               host: str,
               services_scan=True,
               ports='1-65535',
               opts='-Pn',
               speed=4):
     """
     Scan for open ports (and services if specified) on given host.
     :param host: host to scan
     :param services_scan: if True, scan for service details, otherwise scan for open ports only; default is True
     :param ports: ports to scan; default is 1-65535
     :param opts: NMAP flags
     :param speed: NMAP scan speed from 1-5; default is 4
     :param sudo: whether or not to scan using sudo; default is False
     :return:
     """
     nm = PortScanner()
     opts = '{} -T{}'.format(opts, speed)
     if services_scan:
         opts = '{} -sV'.format(opts)
     else:
         opts = '{} -sS'.format(opts)
     results = nm.scan(hosts=host, ports=ports, arguments=opts)
     ports_details = results['scan']
     self.logger.debug(json.dumps(ports_details, indent=2))
     return ports_details
Beispiel #11
0
 def do_discovery(self,
                  host: str,
                  ports='1-65535',
                  opts='-Pn',
                  sudo=False) -> Tuple:
     """
     Run discovery functions on the specified host.
     :param host: host to scan
     :param ports: ports to scan; default is 1-65535
     :param opts: NMAP flags
     :param sudo: whether or not to scan OS using sudo
     :return: tuple in format (ports details, OS details)
     """
     nm = PortScanner()
     self.logger.info(
         'Checking to make sure host {} is reachable.'.format(host))
     results = nm.scan(hosts=host, arguments='-PE -n -sn')
     if len(list(results['scan'].keys())) < 1:
         self.logger.error(
             'Error, I was unable to reach host {}.'.format(host))
         return None, None
     self.logger.info('Scanning ports {} on host {}.'.format(ports, host))
     ports_details = self.get_ports(host, ports=ports, opts=opts)
     self.logger.info('Determining OS of host {}.'.format(host))
     os_details = self.get_os(host, opts=opts, sudo=sudo)
     return ports_details, os_details
Beispiel #12
0
    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)
Beispiel #13
0
def main(argv):

    iprange = None

    try:
        opts, args = getopt.gnu_getopt(argv,"i:",["iprange="])
    except getopt.GetoptError:
        print sys.argv[0]+' -i <iprange>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print sys.argv[0]+' -i <iprange>'
            sys.exit()
        elif opt in ("-i", "--iprange"):
            iprange = arg

    if iprange is None:
        print sys.argv[0]+' -i <iprange>'
        sys.exit()

    scan_port = int(cfg.getConfigValue('pdu', 'scan_port'))
    snmp_port = int(cfg.getConfigValue('pdu', 'snmp_port'))
    ro_community = cfg.getConfigValue('pdu', 'ro_community')
    rw_community = cfg.getConfigValue('pdu', 'rw_community')
    dccode = cfg.getConfigValue('pdu', 'dccode')
    url = '%s/pdu/update' % cfg.getConfigValue('pdu', 'api_base')

    nm = PortScanner()
    nm.scan(hosts=iprange, arguments='-n -p %s' % (scan_port))

    for host in nm.all_hosts():
        state = nm[host]['tcp'][scan_port]['state']
        t = Thread(target=probePdu, args=(host, state, snmp_port, ro_community, rw_community, dccode, url))
        t.start()
Beispiel #14
0
 def get_os(self, host, opts='-Pn', speed=4, sudo=True):
     nm = PortScanner()
     results = nm.scan(hosts=host,
                       arguments='-O {} -T{}'.format(opts, speed),
                       sudo=sudo)
     host_details = results['scan']
     self.logger.debug(json.dumps(host_details, indent=2))
     return host_details
def isHTTPSopen ():
    try:
        scanner = PortScanner()
        scanner.scan(HOST, str(PORT), sudo=True, arguments=arg)
        return scanner[HOST]['tcp'][PORT]['state'] == "open"
    except KeyError:
        logging.warning("{} - nmap Key error. Probably the router is off".format(time.asctime()))
    except:
        logging.error("{} - nmap Scan error".format(time.asctime()))
Beispiel #16
0
class NmapParser(TestPlugin):
    def __init__(self):
        self.tool_name = "nmap"
        super(NmapParser, self).__init__("nmap")
        self.nm = PortScanner()
        self.hosts = None
        self.ports = None
        self.argments = "-sV"
        self.resultparser = ResultPlugin()

    def args_status(self):
        print "hosts:", self.hosts, "\n"
        print "ports:", self.ports, "\n"
        print "argments:", self.argments, "\n"

    def start_scan(self):
        if self.hosts is not None:
            self.nm.scan(self.hosts, arguments=self.argments)
            if self.ports is not None:
                self.nm.scan(self.hosts, self.ports, arguments=self.argments)
        else:
            print "please set hosts"

    def scan_result(self):
        if self.hosts is not None and self.nm.all_hosts():
            return self.nm[self.hosts]

    def run(self):
        super(NmapParser, self).run()
        print "scanning .................\n", "please wait!\n"
        self.start_scan()

    def status(self):
        self.args_status()

    def result(self):
        if self.scan_result() is not None:
            self.resultparser.set_hostname(self.scan_result().hostname())
            self.resultparser.set_state(self.scan_result().state())
            self.resultparser.set_address(self.hosts)
            self.resultparser.set_openports(self.scan_result().all_tcp())
            if u"tcp" in self.scan_result():
                self.resultparser.set_servers(self.scan_result()[u"tcp"])

            print "hostname:", self.resultparser.get_hostname
            print "address:", self.resultparser.get_address
            print "state is :", self.resultparser.get_state
            print "open ports:", self.resultparser.get_openports
            print "servers:", self.resultparser.get_servers, "\n"

    def set_arg(self, arg1, arg2):
        if arg1 == "hosts":
            self.hosts = arg2
        elif arg1 == "ports":
            self.ports = arg2
        elif arg1 == "argments":
            self.argments = arg2
Beispiel #17
0
 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
Beispiel #18
0
 def run_test(self):
     """Check the port is open on the remote host"""
     ps = PortScanner()
     scan = ps.scan(hosts=self.host, ports=self.port, arguments='--host-timeout ' + str(self.timeout) + 's')
     try:
         if scan['scan'][str(self.host)]['tcp'][int(self.port)]['state'] == 'open':
             return True
         else:
             return False
     except KeyError:  # If we cannot find the info in the key for the status, this means the host is down
         return False
Beispiel #19
0
    def _update_info(self):
        """Scan the network for devices.

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

        from nmap import PortScanner, PortScannerError

        scanner = PortScanner()

        options = self._options

        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 get_mac_address(ip=ipv4)
            if mac is None:
                _LOGGER.info("No MAC address found for %s", ipv4)
                continue
            last_results.append(Device(mac.upper(), name, ipv4, now))

        self.last_results = last_results

        _LOGGER.debug("nmap scan successful")
        return True
def findPrinters(IP='192.168.0.0', r='/24'):
    printers = []
    nmap = PortScanner()
    scan = nmap.scan(f'{IP}{r}', '9100')['scan']
    for ip in scan.values():

        if ip['tcp'][9100]['state'] == 'open':
            print(f'9100 OPEN AT {ip["addresses"]["ipv4"]}')
            printers.append(ip["addresses"]["ipv4"])
        else:
            print(f'9100 closed at {ip["addresses"]["ipv4"]}')

    return printers
    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 = self._options

        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
Beispiel #22
0
    def __portscannerWorkerThreads(self, fetch_id, ip, no, q):
        nm = PortScanner()
        # type(self).__data[fetch_id]['details'] = 'Analyzing: ' + str(ip)
        elapsed_start = time.time()
        nm.scan(ip)
        if fetch_id != type(self).__data['current']:
            return
        try:
            data = nm[ip]
            elapsed = time.time() - elapsed_start
            q.put({ip: {**data, **{'elapsed': elapsed}}})

        except:
            pass
Beispiel #23
0
    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 "
        exclude = "--exclude "

        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:
                # Pylint is confused here.
                # pylint: disable=no-member
                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:
            exclude = " --exclude {}".format(",".join(exclude_hosts))
            options += exclude

        try:
            result = scanner.scan(hosts=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
Beispiel #24
0
def nm_scan(hosts, ports, args='-T4 -A'):
    print("From" , platform.uname()[0], platform.uname()[2])
    print("On",  datetime.datetime.now().ctime())
    print("Scanning for host", hosts)
    try:
        nm = PortScanner()
        result = nm.scan(hosts=hosts, ports=ports, arguments=args, sudo=False)
        return result
    except:
        print("[-] Error!!! Something is wrong,")
        print("| (network trouble / nmap problem) ")
        print("| make sure you have nmap installed ")
        print("|__ Please try ./pvascan.py -h\n")
        exit(0)
Beispiel #25
0
    def get_devices(self):
        '''Return a list
        Creates a list of items that contain device information
        '''
        if len(self.ip) >= 1:
            network_to_scan = self.ip + '/24'
        else:
            network_to_scan = self.ip_default + '/24'

        p_scanner = PortScanner()
        print('Scanning {}...'.format(network_to_scan))
        p_scanner.scan(hosts=network_to_scan, arguments='-sn')
        device_list = [(device, p_scanner[device])
                       for device in p_scanner.all_hosts()]
        return device_list
Beispiel #26
0
def scan_host(host):
    """ 
    Utilizza nmap per ricercare i servizi sull'host... la scansione e' 
    di tipo probing, nel senso che effettua delle prove sulle varie 
    porte per determinare il tipo di servizio, ritorna un oggetto
    contenente i risultati sulla scansione (che tra l'altro e' l'oggetto
    stesso che contiene il metodo per la scansione) 
    """

    scanner = PortScanner()
    print("Checking services on %s" % host)
    scanner.scan(hosts=host,
                 arguments='--host_timeout 60s -sV --version_light')

    return (scanner)
Beispiel #27
0
 def do_discovery(self, host, ports='1-65535', opts='-Pn', sudo=False):
     nm = PortScanner()
     self.logger.info(
         '[!] Checking to make sure host {} is reachable.'.format(host))
     results = nm.scan(hosts=host, arguments='-PE -n -sn')
     if len(list(results['scan'].keys())) < 1:
         self.logger.error(
             '[-] Error, I was unable to reach host {}.'.format(host))
         return None, None
     self.logger.info('[!] Scanning ports {} on host {}.'.format(
         ports, host))
     ports_details = self.get_ports(host, ports=ports, opts=opts)
     self.logger.info('[+] Determining OS of host {}.'.format(host))
     os_details = self.get_os(host, opts=opts, sudo=sudo)
     return ports_details, os_details
Beispiel #28
0
    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
def TacacsTest(ip_tacacs, tacacsport_inputuser):
    """
    Funcion para definir el puerto tacacs.

    Esta funcion permite determinar si se desea cambiar el numero de puerto
    al servidor tacacs.
    """
    version = IPTypeVersion(ip_tacacs)

    try:
        nmap = PortScanner()
        nmap.scan(hosts=ip_tacacs,
                  arguments=f"-{version} -p 22-443, {tacacsport_inputuser}")

        port_up = nmap[ip_tacacs].has_tcp(tacacsport_inputuser)

        if port_up is True:
            print(
                f"El servidor Tacacs IPv{version} {ip_tacacs} tiene el puerto"
                + f"{tacacsport_inputuser} activo.")
            return tacacsport_inputuser

        else:
            print(
                f" El puerto {tacacsport_inputuser} que has elegido para el" +
                f" servidor Tacacs con IPv{version} {ip_tacacs}" +
                f" no se encuentra activo.")

            print(f" {blue}{'='*66}")
            print(f" {green_blink} {('Precaucion '*6):^40}")
            print(f" {blue}{'='*66}\n")
            print(f" {red}Se ha producido el siguiente {green}Error {red}>>\n")
            print(
                f" {red}*** El puerto {tacacsport_inputuser} que has elegido "
                +
                f"para el Servidor Tacacs con IPv{version}{green}{ip_tacacs} {blue}no se ha determinado"
                + f" el {green}puerto {red}***\n")

            confirmation_err = input(
                f" {blue}Deseas continuar {green}y/n {red}>> {green}")

    except KeyboardInterrupt:
        print(
            f"\n\n\t{red}Has detenido el {green}programa {red}con el teclado.")

    except KeyError:
        CleanScreen()
        print(f" No se ha podido establer conexion con el servidor")
Beispiel #30
0
def check_url(url):
    '''
    Check connection
    :param url: suspicious url
    :return: status of connection
    '''

    nmScan = PortScanner()
    result = nmScan.scan(url, arguments='-sn')

    if int(result['nmap']['scanstats']['uphosts']) > 0:
        msg = '{0}[{1}*{0}]{1} Connection test: UP'.format(GREEN, END)
    else:
        msg = '{0}[{1}!{0}]{1} Connection test: DOWN'.format(YELLOW, END)

    return msg
def scan_host(host):

    """ 
    Utilizza nmap per ricercare i servizi sull'host... la scansione e' 
    di tipo probing, nel senso che effettua delle prove sulle varie 
    porte per determinare il tipo di servizio, ritorna un oggetto
    contenente i risultati sulla scansione (che tra l'altro e' l'oggetto
    stesso che contiene il metodo per la scansione) 
    """

    scanner = PortScanner()
    print("Checking services on %s" % host)
    scanner.scan(hosts=host, 
                 arguments='--host_timeout 60s -sV --version_light')

    return(scanner)
Beispiel #32
0
def get_ports_from_report(nmap_report):
    """
        This function is responsible to take XML file and generate the report details.
    """
    scanner = PortScanner()
    try:
        scan_result = scanner.analyse_nmap_xml_scan(open(nmap_report).read())
        for host in scan_result['scan']:
            try:
                for port, port_details in scan_result['scan'][host]['tcp'].items():
                    yield host, port, port_details
            except exceptions.KeyError:
                pass
    except Exception, error:
        LOGGER.error("Error: %s" % error)
        exit(1)
Beispiel #33
0
 def __init__(self):
     self.ports = []
     self.network_speed = '4'
     self.nmap_args = '-sV'
     self.ports_name = []
     self.port_of_intrest = []
     self.protocols = []
     self.products = []
     self.flags = []
     self.results = []
     self.service_detected = []
     self.service_identified = []
     self.unknown_ports = list()
     self.time_frame = '25'
     self.Web_Port = False
     self.nm = PortScanner()
 def run_test(self):
     scan = PortScanner().scan(hosts=self.host, arguments='-sn --host-timeout ' + str(self.timeout) + 's')
     try:
         if scan['scan'][str(self.host)]['status']['state'] == 'up':
             return True
     except KeyError:  # If we cannot find the info in the key for the status, this means the host is down
         return False
Beispiel #35
0
 def get_os(self, host: str, opts='-Pn', speed=4, sudo=True) -> Dict:
     """
     Scan for OS details of provided hosts.
     :param host: host to scan
     :param opts: NMAP flags
     :param speed: NMAP scan speed from 1-5; default is 4
     :param sudo: whether or not to scan using sudo; default is True
     :return: dictionary of host details
     """
     nm = PortScanner()
     results = nm.scan(hosts=host,
                       arguments='-O {} -T{}'.format(opts, speed),
                       sudo=sudo)
     host_details = results['scan']
     self.logger.debug(json.dumps(host_details, indent=2))
     return host_details
Beispiel #36
0
 def get_ports(self,
               host,
               services_scan=True,
               ports='1-65535',
               opts='-Pn',
               speed=4):
     nm = PortScanner()
     opts = '{} -T{}'.format(opts, speed)
     if services_scan:
         opts = '{} -sV'.format(opts)
     else:
         opts = '{} -sS'.format(opts)
     results = nm.scan(hosts=host, ports=ports, arguments=opts)
     ports_details = results['scan']
     self.logger.debug(json.dumps(ports_details, indent=2))
     return ports_details
Beispiel #37
0
    def scan(self, bot, update, args):
        chat_id = update.message.chat_id
        from_user = update.message.from_user.username

        parser = ArgumentParser(prog='nmap_plugin')
        parser.add_argument('-host', required=True)
        parser.add_argument('-ports', required=False, default=None)
        parser.add_argument('-all', required=False, default=False, type=bool)
        parser.add_argument('-raw', required=False, default=None)
        try:
            p = parser.parse_args(args)
            for param in vars(p):
                if self.__check_for_idiot_friends(getattr(p, param)):
                    bot.sendMessage(
                        chat_id,
                        text='{} you are a funny guy... but go to try to be an h4x0r somewhere else.'.format(from_user)
                    )
                    if from_user == 'dzonerzy':
                        bot.sendMessage(chat_id,
                                        text='Amico del jaguaro... Ti fo un rutto ne `i viso che ti fo diventa` bello!'
                                        )
                    return
        except ArgumentError:
            bot.sendMessage(chat_id, text="Wrong parameters passed.")
            return

        arguments = '-sV'
        if p.all is True:
            arguments = '-A'

        bot.sendMessage(chat_id, text="Command accepted, running nmap against: {}".format(p.host))
        nm = PortScanner()
        nm.scan(hosts=p.host, ports=p.ports, arguments=arguments)

        msg = ''
        for host in nm.all_hosts():
            msg = '----------------------------------------------------\n'
            msg += 'Host: {} ({})\n'.format(host, nm[host].hostname())
            msg += 'State: {}\n'.format(nm[host].state())
            for proto in nm[host].all_protocols():
                msg += 'Protocol : {}\n'.format(proto)
                lport = nm[host][proto].keys()
                lport.sort()
                for port in lport:
                    msg += '\tport : {}\tstate : {}\n'.format(port, nm[host][proto][port]['state'])
        msg = 'Empty response object received.' if msg == '' else msg
        bot.sendMessage(chat_id, text=msg)
Beispiel #38
0
    def _update_info(self):
        """
        Scans the network for devices.
        Returns boolean if scanning successful.
        """
        _LOGGER.info("Scanning")

        from nmap import PortScanner, PortScannerError
        scanner = PortScanner()

        options = "-F --host-timeout 5"

        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:
                # Pylint is confused here.
                # pylint: disable=no-member
                options += " --exclude {}".format(",".join(
                    device.ip for device in last_results))
        else:
            last_results = []

        try:
            result = scanner.scan(hosts=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
Beispiel #39
0
 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
Beispiel #40
0
def nmapScan(target):
	nm = PortScanner()
	sc = nm.scan(hosts=target, arguments="-n -T4 -sV -p 21,22,23,25,53,80,110,143,443,465,995,993,1248,1433,3306,3389")
	global siteIP
	siteIP = sc["scan"].keys()[0]
	key, value, total = sc["scan"][siteIP]["tcp"].keys(), sc["scan"][siteIP]["tcp"].values(), len(sc["scan"][siteIP]["tcp"].keys())
	print bold+"Port\t\tName\t\tVersion\t\tStatus"+endcolor
	print "----\t\t------\t\t----\t\t-------"
	for port in range(total):
		if value[port]["state"] == "open":
			portlist.append(key[port])
		else:
			pass
		print "{}\t\t{}\t\t{}\t\t{}".format(key[port], value[port]["name"], value[port]["version"], value[port]["state"])
	print ""
	print "Scan Time     : {}".format(sc["nmap"]['scanstats']['timestr'])
	print "Scan Interval : {}".format(sc["nmap"]['scanstats']['elapsed'])
Beispiel #41
0
def nmapScan(target):
	nm = PortScanner()
	sc = nm.scan(hosts=target, arguments="-n -T4 -sV -p 21,22,23,25,53,80,110,143,443,465,995,993,1248,1433,3306,3389")
	global siteIP
	siteIP = sc["scan"].keys()[0]
	key, value, total = sc["scan"][siteIP]["tcp"].keys(), sc["scan"][siteIP]["tcp"].values(), len(sc["scan"][siteIP]["tcp"].keys())
	print bold+"Port\t\tName\t\tVersion\t\tStatus"+endcolor
	print "----\t\t------\t\t----\t\t-------"
	for port in range(total):
		if value[port]["state"] == "open":
			portlist.append(key[port])
		else:
			pass
		print "{}\t\t{}\t\t{}\t\t{}".format(key[port], value[port]["name"], value[port]["version"], value[port]["state"])
	print ""
	print "Scan Time     : {}".format(sc["nmap"]['scanstats']['timestr'])
	print "Scan Interval : {}".format(sc["nmap"]['scanstats']['elapsed'])
Beispiel #42
0
def get_ports_from_report(nmap_report):
    """
        This function is responsible to take XML file and generate the report details.
    """
    scanner = PortScanner()
    try:
        scan_result = scanner.analyse_nmap_xml_scan(open(nmap_report).read())
        for host in scan_result['scan']:
            try:
                for port, port_details in scan_result['scan'][host][
                        'tcp'].items():
                    yield host, port, port_details
            except exceptions.KeyError:
                pass
    except Exception, error:
        LOGGER.error("Error: %s" % error)
        exit(1)
Beispiel #43
0
class NmapConnector:
    @exception_handler(expected_exception=NmapConnectorInitError)
    def __init__(self):
        self.nm = PortScanner()
        self.results: dict = {}

    def check_ip_v6(self, host: str):
        if "IPv6Address" in str(type(ip_address(host))):
            return True

    @exception_handler(expected_exception=NmapConnectorScanError)
    def scan(self,
             host: str,
             arguments: str = "",
             ports: str = "",
             sudo: bool = False) -> None:
        # Add special Nmap key to scan ipv6 hosts
        if self.check_ip_v6(host):
            arguments += " -6"

        # If user wants to scan for top-ports,
        # let's remove other ports from nmap scan
        if "top-ports" in arguments:
            self.nm.scan(hosts=host, arguments=arguments, sudo=sudo)

        # Else if user doesn't want scan for top-ports,
        # let's scan with defined ports
        elif arguments and ports:
            self.nm.scan(hosts=host,
                         arguments=arguments,
                         ports=ports,
                         sudo=sudo)

        # Else if ports are not defined, let's
        # scan with default ports
        elif arguments:
            self.nm.scan(hosts=host, arguments=arguments, sudo=sudo)

        # If arguments are not setted too, make
        # simple scan
        else:
            self.nm.scan(hosts=host, sudo=sudo)
        self.results = {host: self.nm[host] for host in self.nm.all_hosts()}

    @exception_handler(expected_exception=NmapConnectorGetResultsError)
    def get_results(self) -> dict:
        return self.results

    @exception_handler(expected_exception=NmapConnectorGetResultsCountError)
    def get_results_count(self) -> int:
        return len(self.results)
 def __init__(self):
     self.tool_name = "nmap"
     super(NmapParser, self).__init__("nmap")
     self.nm = PortScanner()
     self.hosts = None
     self.ports = None
     self.arguments = "-sV"
     self.resultparser = ResultPlugin()
 def run(self):
     nm = PortScanner()
     a=nm.scan(hosts=config_getway, 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
class NmapParser(ScanPlugin):
    def __init__(self):
        self.tool_name = "nmap"
        super(NmapParser, self).__init__("nmap")
        self.nm = PortScanner()
        self.hosts = None
        self.ports = None
        self.arguments = "-sV"
        self.resultparser = ResultPlugin()

    def start_scan(self):
        if self.hosts is not None:
            self.nm.scan(self.hosts, arguments=self.arguments)
            if self.ports is not None:
                self.nm.scan(self.hosts, self.ports, arguments=self.arguments)
        else:
            print 'please set hosts'
            
    def scan_result(self):
        if self.hosts is not None and self.nm.all_hosts():
            return self.nm[self.hosts]
    
    def run(self, status):
        if status and len(status) == 3:
            self.hosts = status['hosts']
            self.ports = status['ports']
            self.arguments = status['arguments']
        super(NmapParser, self).run(status)
        print "scanning .................\n", "please wait!\n"
        self.start_scan()
        
    def status(self):
        return {"hosts": self.hosts, "ports": self.ports, "arguments": self.arguments}

    def result(self):
        if self.scan_result() is not None:
            self.resultparser.set_hostname(self.scan_result().hostname())
            self.resultparser.set_state(self.scan_result().state())
            self.resultparser.set_address(self.hosts)
            self.resultparser.set_openports(self.scan_result().all_tcp())
            if u'tcp' in self.scan_result():
                self.resultparser.set_servers(self.scan_result()[u'tcp'])
            self.resultparser.log_result()
        return self.scan_result()
    def _update_info(self):
        """
        Scans the network for devices.
        Returns boolean if scanning successful.
        """
        _LOGGER.info("Scanning")

        from nmap import PortScanner, PortScannerError
        scanner = PortScanner()

        options = "-F --host-timeout 5"
        exclude_targets = set()
        if self.home_interval:
            now = dt_util.now()
            for host in self.last_results:
                if host.last_update + self.home_interval > now:
                    exclude_targets.add(host)
            if len(exclude_targets) > 0:
                target_list = [t.ip for t in exclude_targets]
                options += " --exclude {}".format(",".join(target_list))

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

        now = dt_util.now()
        self.last_results = []
        for ipv4, info in result['scan'].items():
            if info['status']['state'] != 'up':
                continue
            name = info['hostnames'][0] 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
            device = Device(mac.upper(), name, ipv4, now)
            self.last_results.append(device)
        self.last_results.extend(exclude_targets)

        _LOGGER.info("nmap scan successful")
        return True
def host_discovery(network_address):

    """
    Tramite il modulo nmap viene effettuata una ricerca degli host
    attivi in rete. Ritorna una lista degli host attivi in rete.
    """

    scanner = PortScanner()

    if network_address:
        print("Searching for hosts on %s..." % network_address)

    scanner.scan(hosts=network_address, arguments='-sP')

    iplist = [ip for ip in scanner.all_hosts() 
              if scanner[ip].state() == 'up']

    print("Found %s host(s)" % len(iplist))
    print(iplist)

    return iplist
Beispiel #49
0
 def run(self):
     try:
         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
     except NameError:
         QMessageBox.information(self, "error module", "the module Python-nmap not installed")
Beispiel #50
0
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
Beispiel #51
0
		ws = wb.get_sheet_by_name( curr_sheet )

		for rn in range( ws.max_row ):
			if n_rec >= 10:
				break

			curr_ip_s = ws.cell( row=rn+1,column=ipcol_s ).value
			curr_ip_e = ws.cell( row=rn+1,column=ipcol_e ).value
			# check the validity of ip datas
			if p.match( curr_ip_s ) == None or p.match( curr_ip_e ) == None:
				continue

			n_rec += 1

			if curr_ip_s == curr_ip_e:
				np = PortScanner()
				scan_res = np.scan( curr_ip_s,port_scope )
				print scan_res
				# print curr_ip_s
			else:
				ip1_list = curr_ip_s.split( '.' )
				ip2_list = curr_ip_e.split( '.' )

				ip1_num_1st = int( ip1_list[0] )
				ip1_num_2nd = int( ip1_list[1] )
				ip1_num_3rd = int( ip1_list[2] )
				ip1_num_4th = int( ip1_list[3] )

				ip2_num_1st = int( ip2_list[0] )
				ip2_num_2nd = int( ip2_list[1] )
				ip2_num_3rd = int( ip2_list[2] )