Python socket.herror() Examples

The following are code examples for showing how to use socket.herror(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: TA-Send_to_HEC   Author: georgestarcher   File: net_utils.py    MIT License 6 votes vote down vote up
def resolve_hostname(addr):
    '''Try to resolve an IP to a host name and returns None
    on common failures.

    :param addr: IP address to resolve.
    :type addr: ``string``
    :returns: Host name if success else None.
    :rtype: ``string``

    :raises ValueError: If `addr` is not a valid address
    '''

    if ip_math.is_valid_ip(addr):
        try:
            name, _, _ = socket.gethostbyaddr(addr)
            return name
        except socket.gaierror:
            # [Errno 8] nodename nor servname provided, or not known
            pass
        except socket.herror:
            # [Errno 1] Unknown host
            pass
        except socket.timeout:
            # Timeout.
            pass

        return None
    else:
        raise ValueError('Invalid ip address.') 
Example 2
Project: openmano   Author: nfvlabs   File: console_proxy_thread.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, host, port, console_host, console_port):
        try:
            threading.Thread.__init__(self)
            self.console_host = console_host
            self.console_port = console_port
            self.host = host
            self.port = port
            self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.server.bind((host, port))
            self.server.listen(200)
            #TODO timeout in a lock section can be used to autoterminate the thread
            #when inactivity and timeout<time : set timeout=0 and terminate
            #from outside, close class when timeout==0; set timeout=time+120 when adding a new console on this thread
            #set self.timeout = time.time() + 120 at init
            self.name = "ConsoleProxy " + console_host + ":" + str(console_port)
            self.input_list = [self.server]
            self.channel = {}
            self.terminate = False #put at True from outside to force termination
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            if e is socket.error and e.errno==98:
                raise ConsoleProxyExceptionPortUsed("socket.error " + str(e))
            raise ConsoleProxyException(type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0])) ) 
Example 3
Project: openmano   Author: nfvlabs   File: console_proxy_thread.py    Apache License 2.0 6 votes vote down vote up
def on_close(self, sock, cause):
        if sock not in self.channel:
            return  #can happen if there is data ready to received at both sides and the channel has been deleted. QUITE IMPROBABLE but just in case
        info = self.channel[sock]
        #debug info
        sockname = "client" if sock is info["clientsock"] else "server"
        print self.name, ": del connection %s %s at %s side" % (info["name"], cause, sockname)
        #close sockets
        try:
            # close the connection with client
            info["clientsock"].close()  # equivalent to do self.s.close()
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            print self.name, ": Exception on_close client socket %s: %s" % (type(e).__name__, str(e) )
        try:
            # close the connection with remote server
            info["serversock"].close()
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            print self.name, ": Exception on_close server socket %s: %s" % (type(e).__name__, str(e) )
        
        #remove objects from input_list
        self.input_list.remove(info["clientsock"])
        self.input_list.remove(info["serversock"])
        # delete both objects from channel dict
        del self.channel[info["clientsock"]]
        del self.channel[info["serversock"]] 
Example 4
Project: openmano   Author: nfvlabs   File: console_proxy_thread.py    Apache License 2.0 6 votes vote down vote up
def on_recv(self, sock):
        if sock not in self.channel:
            return  #can happen if there is data ready to received at both sides and the channel has been deleted. QUITE IMPROBABLE but just in case
        info = self.channel[sock]
        peersock = info["serversock"] if sock is info["clientsock"] else info["clientsock"]
        try:
            data = sock.recv(self.buffer_size)
            if len(data) == 0:
                self.on_close(sock, "peer closed")
            else:
                #print self.data
                sock = peersock
                peersock.send(data)
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            #print self.name, ": Exception %s: %s" % (type(e).__name__, str(e) )
            self.on_close(sock, "Exception %s: %s" % (type(e).__name__, str(e) ))

        

    #def start_timeout(self):
    #    self.timeout = time.time() + 120 
Example 5
Project: cerberus-core   Author: ovh   File: networking.py    GNU General Public License v3.0 6 votes vote down vote up
def get_ips_from_url(url):
    """
        Retrieve IPs from url

        :param str url: The url to resolve
        :rtype: list
        :return: the list of resolved IP address for given url
    """
    try:
        parsed = urlparse(url)
        if parsed.hostname:
            socket.setdefaulttimeout(5)
            ips = socket.gethostbyname_ex(parsed.hostname)[2]
            return ips
    except (ValueError, socket.error, socket.gaierror, socket.herror, socket.timeout):
        pass 
Example 6
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: common.py    MIT License 6 votes vote down vote up
def ip2name(addr):
    if not ip2name.resolve:
        return addr
    try:
        if addr in ip2name.cache:
            return ip2name.cache[addr]
        # FIXME: Workaround Python bug
        # Need double try/except to catch the bug
        try:
            name = gethostbyaddr(addr)[0]
        except KeyboardInterrupt:
            raise
    except (socket_host_error, ValueError):
        name = addr
    except (socket_host_error, KeyboardInterrupt, ValueError):
        ip2name.resolve = False
        name = addr
    ip2name.cache[addr] = name
    return name 
Example 7
Project: ITWSV   Author: penetrate2hack   File: common.py    MIT License 6 votes vote down vote up
def ip2name(addr):
    if not ip2name.resolve:
        return addr
    try:
        if addr in ip2name.cache:
            return ip2name.cache[addr]
        # FIXME: Workaround Python bug
        # Need double try/except to catch the bug
        try:
            name = gethostbyaddr(addr)[0]
        except KeyboardInterrupt:
            raise
    except (socket_host_error, ValueError):
        name = addr
    except (socket_host_error, KeyboardInterrupt, ValueError):
        ip2name.resolve = False
        name = addr
    ip2name.cache[addr] = name
    return name 
Example 8
Project: data-flow-graph   Author: macbre   File: pcap-to-data-flow.py    MIT License 6 votes vote down vote up
def normalize_host(ip):
	def resolve_host(ip):
		logger = logging.getLogger('resolve_host')

		try:
			hostname = gethostbyaddr(ip)[0]
		except herror as e:
			# socket.herror: [Errno 1] Unknown host
			logger.error("Unable to resolve %s: %s", ip, e)
			return ip

		hostname = hostname.split('.')[0]
		logger.info("%s is known as %s", ip, hostname)

		if not hostname.startswith('ap-') and not hostname.startswith('task-'):
			return hostname
		else:
			# ap-s200 -> ap-s*
			return re.sub(r'\d+$', '*', hostname)

	if ip not in hosts_cache:
		hosts_cache[ip] = resolve_host(ip)

	return hosts_cache[ip] 
Example 9
Project: webdigger   Author: rajeshmajumdar   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def whois(url, command=False):
    # clean domain to expose netloc
    ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = result[0]
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain, 0)
    return WhoisEntry.load(domain, text) 
Example 10
Project: Belati   Author: aancw   File: __init__.py    GNU General Public License v2.0 6 votes vote down vote up
def whois(url, command=False):
    # clean domain to expose netloc
    ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = result[0]
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain, 0)
    return WhoisEntry.load(domain, text) 
Example 11
Project: oecluster   Author: OECFHTW   File: NetworkMapper.py    GNU General Public License v3.0 6 votes vote down vote up
def scan_network(self):
        logger.info('scanning Network')
        network = self._config_reader.get_config_section("Networking")['network']
        netmask = self._config_reader.get_config_section("Networking")['netmask']
        my_net = ipaddress.ip_network(network+'/'+netmask)
        host_list = dict()
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(2.0)

        for ip in my_net:
            try:
                # print(ip)
                host = self._generate_host(ip)
                if host is not None:
                    host_list[ip] = host
            except socket.herror as ex:
                pass
        return host_list 
Example 12
Project: oecluster   Author: OECFHTW   File: NetworkMapper.py    GNU General Public License v3.0 6 votes vote down vote up
def fill_host_list(self, ip_list):
        host_list = dict()

        # Use UDP.
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(2.0)

        for ip in ip_list:
            try:
                ip = ipaddress.ip_address(ip)
                host = self._generate_host(ip)
                if host is not None:
                    host_list[ip] = host
            except socket.herror as ex:
                pass

        return host_list 
Example 13
Project: oecluster   Author: OECFHTW   File: NetworkMapper.py    GNU General Public License v3.0 6 votes vote down vote up
def _generate_host(self, ip):
        host = None

        # Use UDP. socket.SOCK_DGRAM
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(2.0)

        try:
            host_name, alias, ipaddr = socket.gethostbyaddr(str(ip))
            host = Node.Node(ip, host_name)
        except socket.herror as ex:
            pass

        return host

    # Properties 
Example 14
Project: python-rrmngmnt   Author: lukas-bednar   File: ssh.py    GNU General Public License v2.0 6 votes vote down vote up
def open(self):
            self._ssh.get_host_keys().clear()
            try:
                self._ssh.connect(
                    self._executor.address,
                    username=self._executor.user.name,
                    password=self._executor.user.password,
                    timeout=self._timeout,
                    pkey=self.pkey
                )
            except (socket.gaierror, socket.herror) as ex:
                args = list(ex.args)
                message = "%s: %s" % (self._executor.address, args[1])
                args[1] = message
                ex.strerror = message
                ex.args = tuple(args)
                raise
            except socket.timeout as ex:
                self._update_timeout_exception(ex)
                raise 
Example 15
Project: python-rrmngmnt   Author: lukas-bednar   File: common.py    GNU General Public License v2.0 6 votes vote down vote up
def fqdn2ip(fqdn):
    """
    translate fqdn to IP

    :param fqdn: host name
    :type fqdn: string
    :return: IP
    :rtype: string
    """
    try:
        return socket.gethostbyname(fqdn)
    except (socket.gaierror, socket.herror) as ex:
        args = list(ex.args)
        message = "%s: %s" % (fqdn, args[1])
        args[1] = message
        ex.strerror = message
        ex.args = tuple(args)
        raise 
Example 16
Project: smarthome   Author: smarthomeNG   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def get_local_hostname(self):
        """
        Returns the local hostname under which the webinterface can be reached

        :return: fully qualified hostname
        :rtype: str
        """
        import socket
        try:
            return socket.gethostbyaddr(self.get_local_ip_address())[0] # can fail with default /etc/hosts
        except socket.herror:
            try:
                return socket.gethostbyaddr("127.0.1.1")[0]	# in debian based systems hostname is assigned to "127.0.1.1" by default
            except socket.herror:
                try:
                    return socket.gethostbyaddr("127.0.0.1")[0]	# 'localhost' in most cases
                except socket.herror:
                    return "localhost"	# should not happen 
Example 17
Project: Juniper-PyEZ-Unit-Testing   Author: GIC-de   File: routing_neighbors.py    MIT License 6 votes vote down vote up
def all(self):
        """Return ALL Neighbors with protocols

        :return: dict of neighbors with IFD as key
        :rtype: dict
        """
        neighbors = defaultdict(lambda: {'protocols': set()})
        for lldp in self.lldp:
            neighbors[lldp.local_int]['hostname'] = lldp.remote_sysname
            neighbors[lldp.local_int]['protocols'].add('lldp')
        for isis in self.isis:
            ifd, unit = isis.interface_name.split('.')
            if 'hostname' not in neighbors[ifd]:
                neighbors[ifd]['hostname'] = isis.system_name
            neighbors[ifd]['protocols'].add('isis')
        for ospf in self.ospf:
            ifd, unit = ospf.interface_name.split('.')
            if 'hostname' not in neighbors[ifd]:
                try:
                    dns_name = socket.gethostbyaddr(ospf.neighbor_id)[0]
                    neighbors[ifd]['hostname'] = dns_name
                except socket.herror:
                    neighbors[ifd]['hostname'] = ospf.neighbor_id
            neighbors[ifd]['protocols'].add('ospf')
        return neighbors 
Example 18
Project: Scrummage   Author: matamorphosis   File: checkdmarc.py    GNU General Public License v3.0 6 votes vote down vote up
def _get_reverse_dns(ip_address):
    """
    Queries for an IP addresses reverse DNS hostname(s)

    Args:
        ip_address (str): An IPv4 or IPv6 address

    Returns:
        list: A list of reverse DNS hostnames

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    try:
        results = socket.gethostbyaddr(ip_address)
        hostnames = [results[0]] + results[1]
    except socket.herror:
        return []
    except Exception as error:
        raise DNSException(error)

    return hostnames 
Example 19
Project: legos.nettools   Author: Legobot   File: ping.py    MIT License 6 votes vote down vote up
def run(self):
        #do pings
        for x in range(0, self.repeat):
            self.one_ping(self.ip, self.port, self.identifier, self.sequence, self.ttl, self.timeout)
            self.sequence += 1
            if x != self.repeat -1:
                time.sleep(self.sleep)
        #count packet loss
        self.result['packet_loss'] /= self.repeat
        #try to get hostname
        try:
            self.result['hostname'] = socket.gethostbyaddr(self.ip)[0]
        except socket.herror:
            self.result['hostname'] = None
        #calculate averate time
        if len(self.result['times']) != 0:
            self.result['avg_time'] = sum(self.result['times']) / len(self.result['times'])
            #and calculate mdev
            mean = sum([float(x) for x in self.result['times']]) / len(self.result['times'])
            self.result['mdev'] = sum([abs(x - mean) for x in self.result['times']]) / len(self.result['times'])

        return self.result 
Example 20
Project: pychess   Author: pychess   File: FICSConnection.py    GNU General Public License v3.0 6 votes vote down vote up
def start(self):
        try:
            if not self.isConnected():
                yield from self._connect()
            while self.isConnected():
                yield from self.client.parse()
        except CancelledError:
            pass
        except Exception as err:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_traceback)
            log.info("FICSConnection.run: %s" % repr(err),
                     extra={"task": (self.host, "raw")})
            self.close()
            if isinstance(err,
                          (IOError, LogOnException, EOFError, socket.error,
                           socket.gaierror, socket.herror)):
                self.emit("error", err)
            else:
                raise
        finally:
            if isinstance(self, FICSMainConnection):
                self.emit("disconnected") 
Example 21
Project: pychess   Author: pychess   File: FICSConnection.py    GNU General Public License v3.0 6 votes vote down vote up
def close(self):
        if isinstance(self.client, PredictionsTelnet) and self.set_user_vars:
            self.client.run_command("set open 0")
            self.client.run_command("set gin 0")
            self.client.run_command("set availinfo 0")
        try:
            self.lvm.stop()
        except AttributeError:
            pass
        except Exception as err:
            if not isinstance(err,
                              (IOError, LogOnException, EOFError, socket.error,
                               socket.gaierror, socket.herror)):
                raise
        finally:
            FICSConnection.close(self) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSocketError(self):
        # Testing socket module exceptions
        def raise_error(*args, **kwargs):
            raise socket.error
        def raise_herror(*args, **kwargs):
            raise socket.herror
        def raise_gaierror(*args, **kwargs):
            raise socket.gaierror
        self.assertRaises(socket.error, raise_error,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_herror,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_gaierror,
                              "Error raising socket exception.") 
Example 23
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testExceptionTree(self):
        self.assertTrue(issubclass(socket.error, Exception))
        self.assertTrue(issubclass(socket.herror, socket.error))
        self.assertTrue(issubclass(socket.gaierror, socket.error))
        self.assertTrue(issubclass(socket.timeout, socket.error)) 
Example 24
Project: osg-configure   Author: opensciencegrid   File: validation.py    Apache License 2.0 5 votes vote down vote up
def valid_domain(host, resolve=False):
    """Return True if the string passed in is a valid domain

    If resolve=True, also check that it resolves (according to gethostbyname).

    """
    if not host:
        return False
    is_ipv4_address = False
    try:
        is_ipv4_address = bool(socket.inet_pton(socket.AF_INET, host))
    except socket.error:
        pass
    is_ipv6_address = False
    try:
        is_ipv6_address = bool(socket.inet_pton(socket.AF_INET6, host))
    except socket.error:
        pass
    is_hostname = valid_hostname(host)

    if not (is_ipv4_address or is_ipv6_address or is_hostname):
        return False

    if not resolve:
        return True

    try:
        socket.gethostbyname(host)
    except (socket.herror, socket.gaierror):
        return False
    return True 
Example 25
Project: misp42splunk   Author: remg427   File: net_utils.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolve_hostname(addr):
    '''Try to resolve an IP to a host name and returns None
    on common failures.

    :param addr: IP address to resolve.
    :type addr: ``string``
    :returns: Host name if success else None.
    :rtype: ``string``

    :raises ValueError: If `addr` is not a valid address
    '''

    if ip_math.is_valid_ip(addr):
        try:
            name, _, _ = socket.gethostbyaddr(addr)
            return name
        except socket.gaierror:
            # [Errno 8] nodename nor servname provided, or not known
            pass
        except socket.herror:
            # [Errno 1] Unknown host
            pass
        except socket.timeout:
            # Timeout.
            pass

        return None
    else:
        raise ValueError('Invalid ip address.') 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testSocketError(self):
        # Testing socket module exceptions
        msg = "Error raising socket exception (%s)."
        with self.assertRaises(OSError, msg=msg % 'OSError'):
            raise OSError
        with self.assertRaises(OSError, msg=msg % 'socket.herror'):
            raise socket.herror
        with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
            raise socket.gaierror 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testExceptionTree(self):
        self.assertTrue(issubclass(OSError, Exception))
        self.assertTrue(issubclass(socket.herror, OSError))
        self.assertTrue(issubclass(socket.gaierror, OSError))
        self.assertTrue(issubclass(socket.timeout, OSError)) 
Example 28
Project: ssh-prompter   Author: azlux   File: ssh.py    MIT License 5 votes vote down vote up
def is_ssh_open(host, ip, port):
    if not ip:
        ip = host
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    try:
        s.connect((ip, port))
        s.shutdown(socket.SHUT_RDWR)
        return True
    except (socket.gaierror, socket.herror):
        return True
    except (socket.timeout, ConnectionRefusedError):
        return False
    finally:
        s.close() 
Example 29
Project: cct   Author: awacha   File: device_tcp.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, instancename, host, port, poll_timeout, sendqueue, incomingqueue,
                 killflag, exitedflag, getcompletemessages):
        self.name = instancename
        assert isinstance(sendqueue, multiprocessing.queues.Queue)
        self.sendqueue = sendqueue
        assert isinstance(incomingqueue, multiprocessing.queues.Queue)
        self.incomingqueue = incomingqueue
        self.poll_timeout = poll_timeout
        self.get_complete_messages = getcompletemessages
        self.logger = logging.getLogger(
            __name__ + '::' + instancename + '__tcpprocess')
        self.logger.propagate = False
        self.msgid_counter = 0
        self.killflag = killflag
        self.exitedflag = exitedflag
        if not self.logger.hasHandlers():
            self.logger.addHandler(QueueLogHandler(incomingqueue))
            self.logger.addHandler(logging.StreamHandler())
            self.logger.setLevel(logging.getLogger(__name__).getEffectiveLevel())
        self.logger.debug('Connecting over TCP/IP to device {}: {}:{:d}'.format(self.name, host, port))
        try:
            self.tcpsocket = socket.create_connection((host, port))
            self.tcpsocket.setblocking(False)
        except (socket.error, socket.gaierror, socket.herror, ConnectionRefusedError) as exc:
            self.logger.error(
                'Error initializing socket connection to device {}:{:d}'.format(host, port))
            try:
                self.tcpsocket.close()
            except AttributeError:
                pass
            self.tcpsocket = None
            self.send_to_backend('error', exception=exc, traceback=traceback.format_exc())
            self.send_to_backend('exited', normaltermination=False)
            raise DeviceError('Cannot connect to device.', exc)

        self.message_part = b''
        self.lastsent = []  # a stack of recently sent messages.
        self.lastsendtimes = []
        self.cleartosend = True 
Example 30
Project: attacks-pages-collector   Author: ifreddyrondon   File: rules.emergingthreats.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 31
Project: attacks-pages-collector   Author: ifreddyrondon   File: malc0de.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 32
Project: attacks-pages-collector   Author: ifreddyrondon   File: phishtank.py    MIT License 5 votes vote down vote up
def get_ip(name):
    attempts = 5
    ip = "undefined"
    while attempts:
        try:
            data = socket.gethostbyname_ex(name)
            ip = data[2][0]
            break
        except (socket.herror, socket.gaierror):
            attempts -= 1

    return ip 
Example 33
Project: attacks-pages-collector   Author: ifreddyrondon   File: malwaredomainlist.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 34
Project: attacks-pages-collector   Author: ifreddyrondon   File: malwarepatrol.py    MIT License 5 votes vote down vote up
def get_ip(name):
    attempts = 5
    ip = "undefined"
    while attempts:
        try:
            data = socket.gethostbyname_ex(name)
            ip = data[2][0]
            break
        except (socket.herror, socket.gaierror):
            attempts -= 1

    return ip 
Example 35
Project: attacks-pages-collector   Author: ifreddyrondon   File: map.norsecorp.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 36
Project: attacks-pages-collector   Author: ifreddyrondon   File: hosts-file.py    MIT License 5 votes vote down vote up
def get_ip(name):
    attempts = 5
    ip = "undefined"
    while attempts:
        try:
            data = socket.gethostbyname_ex(name)
            ip = data[2][0]
            break
        except (socket.herror, socket.gaierror):
            attempts -= 1

    return ip 
Example 37
Project: attacks-pages-collector   Author: ifreddyrondon   File: feodotracker.abuse.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 38
Project: attacks-pages-collector   Author: ifreddyrondon   File: blocklist.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 39
Project: attacks-pages-collector   Author: ifreddyrondon   File: reputation.alienvault.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 40
Project: attacks-pages-collector   Author: ifreddyrondon   File: palevotracker.abuse.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 41
Project: attacks-pages-collector   Author: ifreddyrondon   File: openbl.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 42
Project: attacks-pages-collector   Author: ifreddyrondon   File: malwareblacklist.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 43
Project: attacks-pages-collector   Author: ifreddyrondon   File: dragonresearchgroup.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 44
Project: attacks-pages-collector   Author: ifreddyrondon   File: malwaredomains.py    MIT License 5 votes vote down vote up
def get_ip(name):
    attempts = 5
    ip = "undefined"
    while attempts:
        try:
            data = socket.gethostbyname_ex(name)
            ip = data[2][0]
            break
        except (socket.herror, socket.gaierror):
            attempts -= 1

    return ip 
Example 45
Project: attacks-pages-collector   Author: ifreddyrondon   File: torstatus.blutmagie.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 46
Project: attacks-pages-collector   Author: ifreddyrondon   File: badips.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 47
Project: attacks-pages-collector   Author: ifreddyrondon   File: cybercrime-tracker.py    MIT License 5 votes vote down vote up
def get_ip(name):
    attempts = 5
    ip = "undefined"
    while attempts:
        try:
            data = socket.gethostbyname_ex(name)
            ip = data[2][0]
            break
        except (socket.herror, socket.gaierror):
            attempts -= 1

    return ip 
Example 48
Project: attacks-pages-collector   Author: ifreddyrondon   File: vxvault.py    MIT License 5 votes vote down vote up
def get_ip(name):
    attempts = 5
    ip = "undefined"
    while attempts:
        try:
            data = socket.gethostbyname_ex(name)
            ip = data[2][0]
            break
        except (socket.herror, socket.gaierror):
            attempts -= 1

    return ip 
Example 49
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rsocket.py    MIT License 5 votes vote down vote up
def test_gethostbyaddr():
    try:
        cpy_socket.gethostbyaddr("::1")
    except cpy_socket.herror:
        ipv6 = HSocketError
    except cpy_socket.gaierror:
        ipv6 = GAIError
    else:
        ipv6 = None
    for host in ["localhost", "127.0.0.1", "::1"]:
        if host == "::1" and ipv6:
            with py.test.raises(ipv6):
                gethostbyaddr(host)
            continue
        name, aliases, address_list = gethostbyaddr(host)
        allnames = [name] + aliases
        for n in allnames:
            assert isinstance(n, str)
        if sys.platform != 'win32':
            assert 'localhost' in allnames or 'ip6-localhost' in allnames
        for a in address_list:
            if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
                break  # ok
            if host != '127.0.0.1':  # name lookup might return IPV6
                if isinstance(a, INET6Address) and a.get_host() == "::1":
                    break  # ok
        else:
            py.test.fail("could not find the localhost address in %r"
                         % (address_list,)) 
Example 50
Project: ironpython2   Author: IronLanguages   File: test_socket.py    Apache License 2.0 5 votes vote down vote up
def testSocketError(self):
        # Testing socket module exceptions
        def raise_error(*args, **kwargs):
            raise socket.error
        def raise_herror(*args, **kwargs):
            raise socket.herror
        def raise_gaierror(*args, **kwargs):
            raise socket.gaierror
        self.assertRaises(socket.error, raise_error,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_herror,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_gaierror,
                              "Error raising socket exception.") 
Example 51
Project: ironpython2   Author: IronLanguages   File: test_socket.py    Apache License 2.0 5 votes vote down vote up
def testExceptionTree(self):
        self.assertTrue(issubclass(socket.error, Exception))
        self.assertTrue(issubclass(socket.herror, socket.error))
        self.assertTrue(issubclass(socket.gaierror, socket.error))
        self.assertTrue(issubclass(socket.timeout, socket.error)) 
Example 52
Project: lanscan   Author: sumpfgottheit   File: lanscan.py    MIT License 5 votes vote down vote up
def __init__(self, ip_address, mac_address):
        self.ip = ip_address
        self.mac = mac_address
        self.sort_value = netaddr.IPAddress(self.ip).value
        try:
            self.hostname = socket.gethostbyaddr(self.ip)[0]
        except socket.herror:
            # failed to resolve
            self.hostname = ''
        self.vendor = ''
        self.is_alive = False
        self.open_ports = {} 
Example 53
Project: git_for_splunk   Author: ChrisYounger   File: net_utils.py    Apache License 2.0 5 votes vote down vote up
def resolve_hostname(addr):
    '''Try to resolve an IP to a host name and returns None
    on common failures.

    :param addr: IP address to resolve.
    :type addr: ``string``
    :returns: Host name if success else None.
    :rtype: ``string``

    :raises ValueError: If `addr` is not a valid address
    '''

    if ip_math.is_valid_ip(addr):
        try:
            name, _, _ = socket.gethostbyaddr(addr)
            return name
        except socket.gaierror:
            # [Errno 8] nodename nor servname provided, or not known
            pass
        except socket.herror:
            # [Errno 1] Unknown host
            pass
        except socket.timeout:
            # Timeout.
            pass

        return None
    else:
        raise ValueError('Invalid ip address.') 
Example 54
Project: openmano   Author: nfvlabs   File: console_proxy_thread.py    Apache License 2.0 5 votes vote down vote up
def on_accept(self):
        #accept
        try:
            clientsock, clientaddr = self.server.accept()
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            print self.name, ": Exception on_accept %s: %s" % (type(e).__name__, str(e) )
            return False
        #print self.name, ": Accept new client ", clientaddr

        #connect
        try:
            forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            forward.connect((self.console_host, self.console_port))
            name = "%s:%d => (%s:%d => %s:%d) => %s:%d" %\
                (clientsock.getpeername() + clientsock.getsockname()  + forward.getsockname() + forward.getpeername() )
            print self.name, ": new connection " + name
                
            self.input_list.append(clientsock)
            self.input_list.append(forward)
            info = { "name": name,
                    "clientsock" : clientsock,
                    "serversock" : forward
                    }
            self.channel[clientsock] = info
            self.channel[forward] = info
            return True
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            print self.name, ": Exception on_connect to server %s:%d; %s: %s" % (self.console_host, self.console_port, type(e).__name__, str(e) )
            print self.name, ": Close client side ", clientaddr
            clientsock.close()
            return False 
Example 55
Project: cerberus-core   Author: ovh   File: networking.py    GNU General Public License v3.0 5 votes vote down vote up
def get_ips_from_fqdn(fqdn):
    """
        Retrieve IPs from FQDN

        :param str fqdn: The FQDN to resolve
        :rtype: list
        :return: the list of resolved IP address for given FQDN
    """
    try:
        socket.setdefaulttimeout(5)
        ips = socket.gethostbyname_ex(fqdn)[2]
        return ips
    except (ValueError, socket.error, socket.gaierror, socket.herror, socket.timeout):
        return None 
Example 56
Project: enjoliver   Author: JulienBalestra   File: tools.py    MIT License 5 votes vote down vote up
def get_verified_dns_query(interface: dict):
    """
    A discovery machine give a FQDN. This method will do the resolution before insert in the db
    :param interface:
    :return:
    """
    fqdn_list = []
    try:
        for name in interface["fqdn"]:
            if EC.discovery_fqdn_verify is False:
                logger.warning("Adding a non verified fqdn entry: %s" % name)
                fqdn_list.append(name)
                continue

            max_tries = 2
            for i in range(max_tries):
                try:
                    first_name = socket.gethostbyaddr(interface["ipv4"])[0]
                    logger.debug("succeed to make dns request for %s:%s" % (interface["ipv4"], first_name))

                    if name[-1] == ".":
                        name = name[:-1]

                    if name == first_name:
                        fqdn_list.append(name)
                        break
                    else:
                        logger.warning(
                            "%d/%d fail to verify domain name discoveryC %s != %s socket.gethostbyaddr for %s %s"
                            % (i + 1, max_tries, name, first_name, interface["ipv4"], interface["mac"]))
                except socket.herror as e:
                    logger.error(
                        "%d/%d fail to verify name:%s ipv4:%s err: %s" % (i + 1, max_tries, name, interface["ipv4"], e))

    except (KeyError, TypeError):
        logger.warning("No fqdn for %s returning None" % interface["ipv4"])

    if fqdn_list and len(fqdn_list) > 1:
        raise AttributeError("Should be only one: %s" % fqdn_list)
    return fqdn_list[0] if fqdn_list else None 
Example 57
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testSocketError(self):
        # Testing socket module exceptions
        msg = "Error raising socket exception (%s)."
        with self.assertRaises(OSError, msg=msg % 'OSError'):
            raise OSError
        with self.assertRaises(OSError, msg=msg % 'socket.herror'):
            raise socket.herror
        with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
            raise socket.gaierror 
Example 58
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testExceptionTree(self):
        self.assertTrue(issubclass(OSError, Exception))
        self.assertTrue(issubclass(socket.herror, OSError))
        self.assertTrue(issubclass(socket.gaierror, OSError))
        self.assertTrue(issubclass(socket.timeout, OSError)) 
Example 59
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testSocketError(self):
        # Testing socket module exceptions
        msg = "Error raising socket exception (%s)."
        with self.assertRaises(OSError, msg=msg % 'OSError'):
            raise OSError
        with self.assertRaises(OSError, msg=msg % 'socket.herror'):
            raise socket.herror
        with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
            raise socket.gaierror 
Example 60
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 5 votes vote down vote up
def testExceptionTree(self):
        self.assertTrue(issubclass(OSError, Exception))
        self.assertTrue(issubclass(socket.herror, OSError))
        self.assertTrue(issubclass(socket.gaierror, OSError))
        self.assertTrue(issubclass(socket.timeout, OSError)) 
Example 61
Project: oss-ftp   Author: aliyun   File: test_socket.py    MIT License 5 votes vote down vote up
def testSocketError(self):
        # Testing socket module exceptions
        def raise_error(*args, **kwargs):
            raise socket.error
        def raise_herror(*args, **kwargs):
            raise socket.herror
        def raise_gaierror(*args, **kwargs):
            raise socket.gaierror
        self.assertRaises(socket.error, raise_error,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_herror,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_gaierror,
                              "Error raising socket exception.") 
Example 62
Project: oss-ftp   Author: aliyun   File: test_socket.py    MIT License 5 votes vote down vote up
def testExceptionTree(self):
        self.assertTrue(issubclass(socket.error, Exception))
        self.assertTrue(issubclass(socket.herror, socket.error))
        self.assertTrue(issubclass(socket.gaierror, socket.error))
        self.assertTrue(issubclass(socket.timeout, socket.error)) 
Example 63
Project: pytorify   Author: nlitsme   File: torify.py    MIT License 5 votes vote down vote up
def sockshostbyaddr(addr):
    raise socket.herror(1, "Unknown host") 
Example 64
Project: armada   Author: airshipit   File: base.py    Apache License 2.0 5 votes vote down vote up
def is_connected():
    """Verifies whether network connectivity is up.

    :returns: True if connected else False.
    """
    try:
        host = socket.gethostbyname("opendev.org")
        socket.create_connection((host, 80), 2)
        return True
    except (socket.error, socket.herror, socket.timeout):
        pass
    return False 
Example 65
Project: prometheus-network-exporter   Author: Selfnet   File: netstat.py    MIT License 5 votes vote down vote up
def lookup(ip):
    try:
        return socket.gethostbyaddr(ip)[0]
    except (socket.herror, OSError):
        return ip 
Example 66
Project: prometheus-network-exporter   Author: Selfnet   File: basedevice.py    MIT License 5 votes vote down vote up
def lookup(self, ip):
        try:
            return socket.gethostbyaddr(ip)[0]
        except (socket.herror):
            return ip 
Example 67
Project: HS602   Author: mpmc   File: controller.py    GNU General Public License v3.0 5 votes vote down vote up
def udp_msg(addr, port, msg, reply=True, timeout=5,
                encoding='utf-8'):
        """Send a UDP message.

        :param addr: Host address.
        :param port: Port to send the message on.
        :param msg: Message to send (will be converted to bytes).
        :param reply: Reply needed?
        :param timeout: Socket timeout.
        :param encoding: Message encoding.
        """
        msg = __class__.bytes(msg, encoding)
        port = __class__.port(port)
        timeout = __class__.int(timeout)

        sock = __class__.sock(addr='', port=port, timeout=timeout,
                              udp=True)
        with sock as sock:
            replies = list()
            sent = 0
            while True:
                # Send message.
                if msg:
                    sent = sock.sendto(msg, (addr, port))
                    if not sent > 0:
                        break
                    msg = msg[sent:]
                    continue

                # Receive message?
                if not reply:
                    break
                try:
                    data, [addr, port] = sock.recvfrom(2048)
                    replies += [[addr, port, data]]
                except (socket.error, socket.gaierror,
                        socket.herror, socket.timeout, OSError):
                    break
        return replies 
Example 68
Project: scanomatic   Author: Scan-o-Matic   File: mail.py    GNU General Public License v3.0 5 votes vote down vote up
def get_host_name():

    try:
        return socket.gethostbyaddr(get_my_ip())[0]
    except (IndexError, socket.herror):
        return None 
Example 69
Project: TFTHelper   Author: AliMZaini   File: test__socket_dns.py    MIT License 5 votes vote down vote up
def assertEqualResults(self, real_result, gevent_result, func):
        errors = (socket.gaierror, socket.herror, TypeError)
        if isinstance(real_result, errors) and isinstance(gevent_result, errors):
            if type(real_result) is not type(gevent_result):
                log('WARNING: error type mismatch: %r (gevent) != %r (stdlib)', gevent_result, real_result)
            return

        real_result = self._normalize_result(real_result, func)
        gevent_result = self._normalize_result(gevent_result, func)

        real_result_repr = repr(real_result)
        gevent_result_repr = repr(gevent_result)
        if real_result_repr == gevent_result_repr:
            return
        if relaxed_is_equal(gevent_result, real_result):
            return

        # If we're using the ares resolver, allow the real resolver to generate an
        # error that the ares resolver actually gets an answer to.

        if (
                RESOLVER_NOT_SYSTEM
                and isinstance(real_result, errors)
                and not isinstance(gevent_result, errors)
        ):
            return

        # From 2.7 on, assertEqual does a better job highlighting the results than we would
        # because it calls assertSequenceEqual, which highlights the exact
        # difference in the tuple
        self.assertEqual(real_result, gevent_result) 
Example 70
Project: armada   Author: att-comdev   File: test_source.py    Apache License 2.0 5 votes vote down vote up
def is_connected():
    """Verifies whether network connectivity is up.

    :returns: True if connected else False.
    """
    try:
        host = socket.gethostbyname("www.github.com")
        socket.create_connection((host, 80), 2)
        return True
    except (socket.error, socket.herror, socket.timeout):
        pass
    return False 
Example 71
Project: paasta   Author: Yelp   File: mesos_tools.py    Apache License 2.0 5 votes vote down vote up
def get_mesos_leader() -> str:
    """Get the current mesos-master leader's hostname.
    Attempts to determine this by using mesos.cli to query ZooKeeper.

    :returns: The current mesos-master hostname"""
    try:
        url = get_mesos_master().host
    except mesos_exceptions.MasterNotAvailableException:
        log.debug("mesos.cli failed to provide the master host")
        raise
    log.debug("mesos.cli thinks the master host is: %s" % url)
    hostname = urlparse(url).hostname
    log.debug("The parsed master hostname is: %s" % hostname)
    # This check is necessary, as if we parse a value such as 'localhost:5050',
    # it won't have a hostname attribute
    if hostname:
        try:
            host = socket.gethostbyaddr(hostname)[0]
            fqdn = socket.getfqdn(host)
        except (socket.error, socket.herror, socket.gaierror, socket.timeout):
            log.debug("Failed to convert mesos leader hostname to fqdn!")
            raise
        log.debug("Mesos Leader: %s" % fqdn)
        return fqdn
    else:
        raise ValueError("Expected to receive a valid URL, got: %s" % url) 
Example 72
Project: certidude   Author: laurivosandi   File: authority.py    MIT License 4 votes vote down vote up
def store_request(buf, overwrite=False, address="", user=""):
    """
    Store CSR for later processing
    """

    if not buf:
        raise ValueError("No signing request supplied")

    if pem.detect(buf):
        header, _, der_bytes = pem.unarmor(buf)
        csr = CertificationRequest.load(der_bytes)
    else:
        csr = CertificationRequest.load(buf)
        buf =  pem_armor_csr(csr)

    common_name = csr["certification_request_info"]["subject"].native["common_name"]

    if not re.match(const.RE_COMMON_NAME, common_name):
        raise ValueError("Invalid common name %s" % repr(common_name))

    request_path = os.path.join(config.REQUESTS_DIR, common_name + ".pem")


    # If there is cert, check if it's the same
    if os.path.exists(request_path) and not overwrite:
        if open(request_path, "rb").read() == buf:
            raise errors.RequestExists("Request already exists")
        else:
            raise errors.DuplicateCommonNameError("Another request with same common name already exists")
    else:
        with open(request_path + ".part", "wb") as fh:
            fh.write(buf)
        os.rename(request_path + ".part", request_path)

    attach_csr = buf, "application/x-pem-file", common_name + ".csr"
    mailer.send("request-stored.md",
        attachments=(attach_csr,),
        common_name=common_name)
    setxattr(request_path, "user.request.address", address)
    setxattr(request_path, "user.request.user", user)
    try:
        hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(address)
    except (socket.herror, OSError): # Failed to resolve hostname or resolved to multiple
        pass
    else:
        setxattr(request_path, "user.request.hostname", hostname)
    return request_path, csr, common_name 
Example 73
Project: cerberus-core   Author: ovh   File: networking.py    GNU General Public License v3.0 4 votes vote down vote up
def get_reverses_for_item(item, nature="IP", replace_exception=False):
    """
        Try to get reverses infos for given item

        :param str item: Can be an IP address, a URL or a FQDN
        :param str nature: The nature of the item
        :param bool replace_exception: Replace by NXDOMAIN or TIMEOUT
        :rtype: dict
        :return: a dict containing reverse infos
    """
    hostname = None
    reverses = {}

    if nature == "IP":
        reverses["ip"] = item
        try:
            validate_ipv46_address(item)
            reverses["ipReverse"] = socket.gethostbyaddr(item)[0]
            reverses["ipReverseResolved"] = socket.gethostbyname(reverses["ipReverse"])
        except (
            IndexError,
            socket.error,
            socket.gaierror,
            socket.herror,
            socket.timeout,
            TypeError,
            ValidationError,
        ):
            pass
    elif nature == "URL":
        reverses["url"] = item
        parsed = urlparse(item)
        if parsed.hostname:
            hostname = parsed.hostname
    else:
        reverses["fqdn"] = item
        hostname = item

    if hostname:
        try:
            reverses["fqdn"] = hostname
            reverses["fqdnResolved"] = socket.gethostbyname(hostname)
            reverses["fqdnResolvedReverse"] = socket.gethostbyaddr(
                reverses["fqdnResolved"]
            )[0]
        except socket.gaierror as ex:
            if replace_exception:
                try:
                    reverses["fqdnResolved"] = DNS_ERROR[str(ex.args[0])]
                except KeyError:
                    reverses["fqdnResolved"] = "NXDOMAIN"
        except socket.timeout:
            if replace_exception:
                reverses["fqdnResolved"] = "TIMEOUT"
        except (IndexError, TypeError, socket.error, socket.herror):
            pass

    return reverses 
Example 74
Project: gstatus   Author: gluster   File: network.py    GNU General Public License v3.0 4 votes vote down vote up
def host_aliases(host):
    """ for any given host attempt to return an alias list of names/IP """

    alias_list = [host]
    fqdn = ''
    shortname = ''
    ip_addr = ''

    if is_ip(host):

        try:
            fqdn = socket.gethostbyaddr(host)[0]

        except:
            # could get "socket.herror: [Errno 1] Unknown host"
            # indicating that reverse DNS is not working for this IP

            # If this is an IP on the local machine, use gethostname()
            if host in get_ipv4_addr():
                fqdn = socket.gethostname()
            else:
                # however, if the IP is foreign and not resolving check
                # /etc/hosts for an answer
                with open('/etc/hosts') as hosts_file:
                    ip_match = [host_entry for host_entry in hosts_file.readlines() if host in host_entry]
                if ip_match:
                    fqdn = ip_match[0].split()[1]

        shortname = fqdn.split('.')[0]
        alias_list.append(fqdn)
        alias_list.append(shortname)

    else:
        try:
            if '.' in host:
                shortname = host.split('.')[0]
                alias_list.append(shortname)
            else:
                fqdn = socket.gethostbyname_ex(host)[0]
                alias_list.append(fqdn)

            ip_addr = socket.gethostbyname(host)
        except:
            # do nothing
            pass

        alias_list.append(ip_addr)

    return sorted(alias_list) 
Example 75
Project: enjoliver   Author: blablacar   File: tools.py    MIT License 4 votes vote down vote up
def get_verified_dns_query(interface: dict):
    """
    A discovery machine give a FQDN. This method will do the resolution before insert in the db
    :param interface:
    :return:
    """
    fqdn_list = []
    try:
        for name in interface["fqdn"]:
            if EC.discovery_fqdn_verify is False:
                logger.warning("Adding a non verified fqdn entry: %s" % name)
                fqdn_list.append(name)
                continue

            # Do 5 tries
            max_tries = 5
            for i in range(max_tries):
                if i > 0:
                    time.sleep(i / 10)
                try:
                    first_name = socket.gethostbyaddr(interface["ipv4"])[0]
                    logger.debug("succeed to make dns request for %s:%s" % (interface["ipv4"], first_name))

                    if name[-1] == ".":
                        name = name[:-1]

                    if name == first_name:
                        fqdn_list.append(name)
                        break
                    else:
                        logger.warning(
                            "%d/%d fail to verify domain name discoveryC %s != %s socket.gethostbyaddr for %s %s"
                            % (i + 1, max_tries, name, first_name, interface["ipv4"], interface["mac"]))
                except socket.herror as e:
                    logger.error(
                        "%d/%d fail to verify name:%s ipv4:%s err: %s" % (i + 1, max_tries, name, interface["ipv4"], e))

    except (KeyError, TypeError):
        logger.warning("No fqdn for %s returning None" % interface["ipv4"])

    if fqdn_list and len(fqdn_list) > 1:
        raise AttributeError("Should be only one: %s" % fqdn_list)
    return fqdn_list[0] if fqdn_list else None 
Example 76
Project: Infoga   Author: The404Hacking   File: infoga.py    GNU General Public License v3.0 4 votes vote down vote up
def info(self):
		if self.allemail == []:
			self.printf.error("Not found email :(")
			sys.exit(0)
		allemail = []
		for x in self.allemail:
			if x not in allemail:
				allemail.append(x)
		try:
			for x in range(len(allemail)):
				self.printf.plus("Email: %s"%(allemail[x]))
				data = {'lang':'en'}
				data['email'] = allemail[x]
				req = requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
				req = requests.post("http://mailtester.com/testmail.php",data=data,verify=False)
				regex = re.compile("[0-9]+(?:\.[0-9]+){3}")
				ip = regex.findall(req.content)
				new = []
				for e in ip:
					if e not in new:
						new.append(e)
				for s in range(len(new)):
					req = requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
					req = requests.get("https://api.shodan.io/shodan/host/"+new[s]+"?key=UNmOjxeFS2mPA3kmzm1sZwC0XjaTTksy",verify=False)
					jso = json.loads(req.content,"utf-8")
					try:
						self.sock = socket.gethostbyaddr(new[s])[0]
					except  socket.herror as err:
						try:
							self.sock = jso["hostnames"][0]
						except KeyError as err:
							pass
					if "country_code" and "country_name" in jso:
						self.printf.ip("IP: %s (%s)"%(new[s],self.sock))
						self.printf.info("Country: %s (%s)"%(jso["country_code"],jso["country_name"]))
						self.printf.info("City: %s (%s)"%(jso["city"],jso["region_code"]))
						self.printf.info("ASN: %s"%(jso["asn"]))
						self.printf.info("ISP: %s"%(jso["isp"]))
						self.printf.info("Geolocation: %s"%("https://www.google.com/maps/@%s,%s,9z"%(jso["latitude"],jso["longitude"])))
						self.printf.info("Hostname: %s"%(jso["hostnames"][0]))
						self.printf.info("Organization: %s"%(jso["org"]))
						self.printf.info("Ports: %s"%(jso["ports"]))
						if "vulns" in jso:
							self.printf.info("Vulns: %s"%(jso["vulns"][0]))
						print ""

					elif "No information available for that IP." or "error" in jso:
						self.printf.ip("IP: %s (%s)"%(new[s],self.sock))
						self.printf.info("No information available for that ip :(",color="r")
						print ""
					else:
						self.printf.ip("IP: %s (%s)"%(new[s],self.sock))
						print ""
		except Exception as error:
			pass 
		sys.exit() 
Example 77
Project: Infoga   Author: The404Hacking   File: infoga.py    GNU General Public License v3.0 4 votes vote down vote up
def getinfo(self,email):
		self.printf.test("Checking email info...")
		try:
			data = {'lang':'en'}
			data['email'] = email 
			req = requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
			req = requests.post("http://mailtester.com/testmail.php",data=data,verify=False)
			regex = re.compile("[0-9]+(?:\.[0-9]+){3}")
			ip = regex.findall(req.content)
			new = []
			for e in ip:
				if e not in new:
					new.append(e)
			self.printf.plus("Email: %s"%email)
			for s in range(len(new)):
				req = requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
				req = requests.get("https://api.shodan.io/shodan/host/"+new[s]+"?key=UNmOjxeFS2mPA3kmzm1sZwC0XjaTTksy",verify=False)
				jso = json.loads(req.content)
				try:
					self.sock = socket.gethostbyaddr(new[s])[0]
				except socket.herror as err:
					try:
						self.sock = jso["hostnames"][0]
					except KeyError as err:
						pass
				if "country_code" and "country_name" in jso:
					self.printf.ip("IP: %s (%s)"%(new[s],self.sock))
					self.printf.info("Country: %s (%s)"%(jso["country_code"],jso["country_name"]))
					self.printf.info("City: %s (%s)"%(jso["city"],jso["region_code"]))
					self.printf.info("ASN: %s"%(jso["asn"]))
					self.printf.info("ISP: %s"%(jso["isp"]))
					self.printf.info("Geolocation: %s"%("https://www.google.com/maps/@%s,%s,9z"%(jso["latitude"],jso["longitude"])))
					self.printf.info("Hostname: %s"%(jso["hostnames"][0]))
					self.printf.info("Organization: %s"%(jso["org"]))
					self.printf.info("Ports: %s"%(jso["ports"]))
					if 'vulns' in jso:
						self.printf.info("Vulns: %s"%(jso["vulns"][0]))
					print ""
				
				elif "No information available for that IP." or "error" in jso:
					self.printf.ip("IP: %s (%s)"%(new[s],self.sock))
					self.printf.info("No information available for that ip :(",color="r")
					print ""

				else:
					self.printf.ip("IP: %s (%s)"%(new[s],self.sock))
		except Exception as error:
			pass
		sys.exit() 
Example 78
Project: pscheduler   Author: perfsonar   File: psdns.py    Apache License 2.0 4 votes vote down vote up
def dns_resolve_reverse(ip,
                        timeout=__DEFAULT_TIMEOUT__):
    """
    Resolve an IP (v4 or v6) to its hostname, returning None if not
    found or there was a timeout.
    """

    """
    Reverse-resolve a host using the system's facilities
    """

    # TODO: It would be nice of the queue/timeout code wasn't duplicated
    # TODO: Validate 'ip' as an IP and raise a ValueError

    def proc(ip_addr, queue):
        """Process the query"""
        try:
            queue.put(socket.gethostbyaddr(ip_addr)[0])
        except socket.herror:
            queue.put(None)
        except socket.gaierror as ex:
            if ex.errno != -2:
                raise ex
            queue.put(None)

    queue = Queue.Queue()
    thread = threading.Thread(target=proc, args=(ip, queue))
    thread.setDaemon(True)
    thread.start()
    try:
        return queue.get(True, timeout)
    except Queue.Empty:
        return None

    # NOTE: Don't make any attempt to kill the thread, as it will get
    # Python all confused if it holds the GIL.




#
# Bulk Resolution
# 
Example 79
Project: wifikicker   Author: viluhaxor   File: scan.py    MIT License 4 votes vote down vote up
def scanNetwork():

    def long2net(arg):
        if (arg <= 0 or arg >= 0xFFFFFFFF):
            raise ValueError("illegal netmask value", hex(arg))
        return 32 - int(round(math.log(0xFFFFFFFF - arg, 2)))

    def to_CIDR_notation(bytes_network, bytes_netmask):
        network = scapy.utils.ltoa(bytes_network)
        netmask = long2net(bytes_netmask)
        net = "%s/%s" % (network, netmask)
        if netmask < 16:
            return None

        return net

    def scan_and_print_neighbors(net, interface, timeout=1):
        hostsList = []
        try:
            ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=False)
            for s, r in ans.res:
                mac = r.sprintf("%Ether.src%")
                ip = r.sprintf("%ARP.psrc%")
                line = r.sprintf("%Ether.src%  %ARP.psrc%")
                hostsList.append([ip, mac])
                try:
                    hostname = socket.gethostbyaddr(r.psrc)
                    line += "," + hostname[0]
                except socket.herror:
                    pass
        except socket.error as e:
            if e.errno == errno.EPERM:     # Operation not permitted
                exit()
            else:
                raise
        return hostsList

    for network, netmask, _, interface, address in scapy.config.conf.route.routes:

        # skip loopback network and default gw
        if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
            continue

        if netmask <= 0 or netmask == 0xFFFFFFFF:
            continue

        # Skip APIPA network (corresponds to the 169.254.0.0/16 address range)
        # See https://fr.wikipedia.org/wiki/Automatic_Private_Internet_Protocol_Addressing for more details
        if network == 2851995648:
            continue

        net = to_CIDR_notation(network, netmask)

        if interface != scapy.config.conf.iface:
            # see http://trac.secdev.org/scapy/ticket/537
            continue

        if net:
            return scan_and_print_neighbors(net, interface) 
Example 80
Project: pychess   Author: pychess   File: ICLogon.py    GNU General Public License v3.0 4 votes vote down vote up
def showError(self, connection, error):
        text = str(error)
        if isinstance(error, IOError):
            title = _("Connection Error")
        elif isinstance(error, LogOnException):
            title = _("Log on Error")
        elif isinstance(error, EOFError):
            title = _("Connection was closed")
        elif isinstance(error, socket.error):
            title = _("Connection Error")
            text = ", ".join(map(str, error.args))
        elif isinstance(error, socket.gaierror) or \
                isinstance(error, socket.herror):
            title = _("Address Error")
            text = ", ".join(map(str, error.args))
        elif isinstance(error, AutoLogoutException):
            title = _("Auto-logout")
            text = _(
                "You have been logged out because you were idle more than 60 minutes")
        else:
            title = str(error.__class__)

        self.showNormal()

        content_area = self.infobar.get_content_area()
        for widget in content_area:
            content_area.remove(widget)
        content = Gtk.HBox()
        image = Gtk.Image()
        image.set_from_stock(Gtk.STOCK_DIALOG_WARNING, Gtk.IconSize.DIALOG)
        content.pack_start(image, False, False, 0)
        vbox = Gtk.VBox()
        label = Gtk.Label()
        label.props.xalign = 0
        label.props.justify = Gtk.Justification.LEFT
        label.set_markup("<b><big>%s</big></b>" % title)
        vbox.pack_start(label, True, False, 0)
        for line in str(text).split("\n"):
            label = Gtk.Label()
            label.set_size_request(476, -1)
            label.props.selectable = True
            label.props.wrap = True
            label.props.xalign = 0
            label.props.justify = Gtk.Justification.LEFT
            label.set_markup(line)
            vbox.pack_start(label, True, False, 0)
        content.pack_start(vbox, False, False, 7)
        content_area.add(content)
        self.widgets["messagePanel"].show_all()