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)
    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()
Example #3
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)
Example #4
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
Example #5
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}
Example #6
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()
 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
Example #8
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
 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
Example #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
Example #11
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()))
Example #13
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
Example #14
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
Example #17
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
Example #18
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
Example #19
0
    def get_device_ips(self, default_gateway):
        ips = []

        if not default_gateway:
            default_gateway = self.get_default_gateway()

        for result in PortScanner().scan(hosts=default_gateway + '/24',
                                         arguments='-sP')['scan'].values():
            if 'addresses' in result:
                if 'ipv4' in result['addresses'] and \
                result['addresses']['ipv4'] != default_gateway and \
                result['addresses']['ipv4'] not in socket.gethostbyname_ex(socket.gethostname())[-1]:
                    ips.append(result['addresses']['ipv4'])

        return ips
Example #20
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)
Example #21
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
Example #22
0
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")
Example #23
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
Example #24
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
Example #25
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
Example #26
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()
Example #27
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)
Example #28
0
def nmap_scan(ip, port):
    global lock
    try:
        nmap_scanner = PortScanner()
        result = nmap_scanner.scan(ip, str(port))
        state = result['scan'][ip]['tcp'][int(port)]['state']
        lock.acquire()
        print '[+][', port, '], IP:', ip, 'Port:', port, 'State:', state
        print '[+]', result['scan'][ip]['tcp'][int(port)]
        if state == 'open':
            open_ports.append(port)
        else:
            closed_ports.append(port)
    except Exception, e:
        lock.acquire()
        print '[-] IP:', ip, 'Port:', port, 'Errors occur when scanning', e.message
        closed_ports.append(port)
Example #29
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'])
Example #30
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