Python socket.gethostbyaddr() Examples

The following are code examples for showing how to use socket.gethostbyaddr(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: SupercomputerInABriefcase   Author: SupercomputerInABriefcase   File: discovery.py    (license) View Source Project 10 votes vote down vote up
def discover(data: ConnectionData) -> None:
    assert isinstance(data, ConnectionData)
    ip_net, iface = data
    try:
        ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_net), iface=iface, timeout=2, verbose=False)
        for s, r in ans:
            line = r.sprintf("%Ether.src%  %ARP.psrc%")
            try:
                hostname = socket.gethostbyaddr(r.psrc)
                line += '  ' + hostname[0]
            except socket.herror:
                pass
            print(line)
    except PermissionError:
        print('Cannot execute necessary code, did you run as root?')
        sys.exit(1)
    except:
        raise 
Example 2
Project: hostapd-mana   Author: adde88   File: unix.py    (license) View Source Project 7 votes vote down vote up
def addUTMPEntry(self, loggedIn=1):
        if not utmp:
            return
        ipAddress = self.avatar.conn.transport.transport.getPeer().host
        packedIp ,= struct.unpack('L', socket.inet_aton(ipAddress))
        ttyName = self.ptyTuple[2][5:]
        t = time.time()
        t1 = int(t)
        t2 = int((t-t1) * 1e6)
        entry = utmp.UtmpEntry()
        entry.ut_type = loggedIn and utmp.USER_PROCESS or utmp.DEAD_PROCESS
        entry.ut_pid = self.pty.pid
        entry.ut_line = ttyName
        entry.ut_id = ttyName[-4:]
        entry.ut_tv = (t1,t2)
        if loggedIn:
            entry.ut_user = self.avatar.username
            entry.ut_host = socket.gethostbyaddr(ipAddress)[0]
            entry.ut_addr_v6 = (packedIp, 0, 0, 0)
        a = utmp.UtmpRecord(utmp.UTMP_FILE)
        a.pututline(entry)
        a.endutent()
        b = utmp.UtmpRecord(utmp.WTMP_FILE)
        b.pututline(entry)
        b.endutent() 
Example 3
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def getOSCTarget(self, address):
		"""Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
		'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
		Returns (None, ['',{}]) if address not found.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if (type(address) == tuple): 
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
					
			if (address in list(self.targets.keys())):
				try:
					(host, _, _) = socket.gethostbyaddr(host)
				except socket.error:
					pass
	
				return ((host, port), self.targets[address])

		return (None, ['',{}]) 
Example 4
Project: devtools-parser   Author: WPO-Foundation   File: devtools_parser.py    (license) View Source Project 6 votes vote down vote up
def get_base_page_info(self, page_data):
        """Find the reverse-ip info for the base page"""
        domain = urlparse.urlsplit(page_data['final_url']).hostname
        try:
            import socket
            addr = socket.gethostbyname(domain)
            host = str(socket.gethostbyaddr(addr)[0])
            page_data['base_page_ip_ptr'] = host
        except Exception:
            pass
        # keep moving up the domain until we can get a NS record
        while domain is not None and 'base_page_dns_soa' not in page_data:
            try:
                import dns.resolver
                dns_servers = dns.resolver.query(domain, "NS")
                dns_server = str(dns_servers[0].target).strip('. ')
                page_data['base_page_dns_ns'] = dns_server
            except Exception:
                pass
            pos = domain.find('.')
            if pos > 0:
                domain = domain[pos + 1:]
            else:
                domain = None 
Example 5
Project: spiderfoot   Author: wi-fi-analyzer   File: sfp_dns.py    (license) View Source Project 6 votes vote down vote up
def resolveIP(self, ipaddr):
        ret = list()
        self.sf.debug("Performing reverse-resolve of " + ipaddr)

        if ipaddr in self.resolveCache:
            self.sf.debug("Returning cached result for " + ipaddr + " (" +
                          str(self.resolveCache[ipaddr]) + ")")
            return self.resolveCache[ipaddr]

        try:
            addrs = self.sf.normalizeDNS(socket.gethostbyaddr(ipaddr))
            self.resolveCache[ipaddr] = addrs
            self.sf.debug("Resolved " + ipaddr + " to: " + str(addrs))
            return addrs
        except BaseException as e:
            self.sf.debug("Unable to resolve " + ipaddr + " (" + str(e) + ")")
            self.resolveCache[ipaddr] = list()
            return ret

    # Resolve a host 
Example 6
Project: spiderfoot   Author: wi-fi-analyzer   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example 7
Project: TCP-IP   Author: JackZ0   File: configurator.py    (license) View Source Project 6 votes vote down vote up
def get_name_from_ip(self, addr):  # pylint: disable=no-self-use
        """Returns a reverse dns name if available.

        :param addr: IP Address
        :type addr: ~.common.Addr

        :returns: name or empty string if name cannot be determined
        :rtype: str

        """
        # If it isn't a private IP, do a reverse DNS lookup
        if not common.private_ips_regex.match(addr.get_addr()):
            try:
                socket.inet_aton(addr.get_addr())
                return socket.gethostbyaddr(addr.get_addr())[0]
            except (socket.error, socket.herror, socket.timeout):
                pass

        return "" 
Example 8
Project: legos.nettools   Author: Legobot   File: ping.py    (license) View Source Project 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 9
Project: Network-Scanner-PORT-ALIVE   Author: C3s1um133   File: neighbors_parser.py    (license) View Source Project 6 votes vote down vote up
def scan_and_print_neighbors(net, interface, timeout=1):
	global ips_o
	print_fmt("\n\033[94m[ARP]\033[0m %s sur %s" % (net, interface))
	try:
		ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=False)
		for s, r in ans.res:
			line = r.sprintf("%Ether.src%  %ARP.psrc%")
			ips_o.append(line.split(' ')[2])
			line = mac_address_id(line)
			try:
				hostname = socket.gethostbyaddr(r.psrc)
				line += " " + hostname[0]
			except socket.herror:
				pass
			except KeyboardInterrupt:
				print '\033[91m[-]\033[0m L\'utilisateur a choisi l\'interruption du process.'
				break
			logger.info("\033[96m[ONLINE]\033[0m " + line)
	except socket.error as e:
		if e.errno == errno.EPERM:
			logger.error("\033[91m[-]\033[0m %s. Vous n'etes pas root?", e.strerror)
		else:
			raise 
Example 10
Project: hakkuframework   Author: 4shadoww   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example 11
Project: hakkuframework   Author: 4shadoww   File: __init__.py    (license) View Source Project 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 12
Project: check_katello_sync   Author: stdevel   File: ForemanAPIClient.py    (license) View Source Project 6 votes vote down vote up
def validate_hostname(hostname):
        """
        Validates that the Foreman API uses a FQDN as hostname.
        Also looks up the "real" hostname if "localhost" is specified.
        Otherwise, the picky Foreman API won't connect.

        :param hostname: the hostname to validate
        :type hostname: str
        """
        if hostname == "localhost":
            #get real hostname
            hostname = socket.gethostname()
        else:
            #convert to FQDN if possible:
            fqdn = socket.gethostbyaddr(hostname)
            if "." in fqdn[0]:
                hostname = fqdn[0]
        return hostname 
Example 13
Project: temboard-agent   Author: dalibo   File: inventory.py    (license) View Source Project 6 votes vote down vote up
def _hostname_linux(self):
        """
        Returns system hostname.
        """
        # Default value found using platform
        hostname = platform.node()
        try:
            # Try to get hostname (FQDN) using 'hostname -f'
            (rc, out, err) = exec_command([which('hostname'), '-f'])
            if rc == 0:
                hostname = out.encode('utf-8').strip()
        except Exception:
            try:
                # Try to get hostname (FQDN) using socket module
                (hostname, _, _) = socket.gethostbyaddr(socket.gethostname())
                hostname = hostname.strip()
            except Exception:
                pass
        return hostname 
Example 14
Project: opsmgr   Author: open-power-ref-design-toolkit   File: resource_mgr.py    (license) View Source Project 6 votes vote down vote up
def _check_address(address):
    ipv4 = ""
    hostname = ""
    if is_valid_address(address):
        ipv4 = address
        try:
            hostname = socket.gethostbyaddr(address)[0]
        except Exception:
            pass  # no DNS
    else:
        hostname = socket.getfqdn(address)
        try:
            ipv4 = socket.gethostbyname(hostname)
        except Exception:
            pass  # host not valid or offline
    return ipv4, hostname 
Example 15
Project: Belati   Author: aancw   File: __init__.py    (license) View Source Project 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 16
Project: zippy   Author: securesystemslab   File: test_socket.py    (license) View Source Project 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            return
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            return
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 17
Project: certbot   Author: nikoloskii   File: configurator.py    (license) View Source Project 6 votes vote down vote up
def get_name_from_ip(self, addr):  # pylint: disable=no-self-use
        """Returns a reverse dns name if available.

        :param addr: IP Address
        :type addr: ~.common.Addr

        :returns: name or empty string if name cannot be determined
        :rtype: str

        """
        # If it isn't a private IP, do a reverse DNS lookup
        if not common.private_ips_regex.match(addr.get_addr()):
            try:
                socket.inet_aton(addr.get_addr())
                return socket.gethostbyaddr(addr.get_addr())[0]
            except (socket.error, socket.herror, socket.timeout):
                pass

        return "" 
Example 18
Project: xunfeng   Author: ysrc   File: crack_smb.py    (license) View Source Project 6 votes vote down vote up
def ip2hostname(ip):
    try:
        hostname = socket.gethostbyaddr(ip)[0]
        return hostname
    except:
        pass
    try:
        query_data = "\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x20\x43\x4b\x41\x41" + \
                     "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41" + \
                     "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x00\x00\x21\x00\x01"
        dport = 137
        _s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _s.sendto(query_data, (ip, dport))
        x = _s.recvfrom(1024)
        tmp = x[0][57:]
        hostname = tmp.split("\x00", 2)[0].strip()
        hostname = hostname.split()[0]
        return hostname
    except:
        pass 
Example 19
Project: xunfeng   Author: ysrc   File: scan.py    (license) View Source Project 6 votes vote down vote up
def ip2hostname(self,ip):
        try:
            hostname = socket.gethostbyaddr(ip)[0]
            return hostname
        except:
            pass
        try:
            query_data = "\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x20\x43\x4b\x41\x41" + \
                         "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41" + \
                         "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x00\x00\x21\x00\x01"
            dport = 137
            _s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            _s.settimeout(3)
            _s.sendto(query_data, (ip, dport))
            x = _s.recvfrom(1024)
            tmp = x[0][57:]
            hostname = tmp.split("\x00", 2)[0].strip()
            hostname = hostname.split()[0]
            return hostname
        except:
            pass 
Example 20
Project: oil   Author: oilshell   File: test_socket.py    (license) View Source Project 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 21
Project: python2-tracer   Author: extremecoders-re   File: test_socket.py    (license) View Source Project 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 22
Project: python2-tracer   Author: extremecoders-re   File: dnslookup-2.py    (license) View Source Project 6 votes vote down vote up
def dnslookup(self, str):
        """ Perform DNS lookup on str.  If first character of digit is numeric,
            assume that str contains an IP address.  Otherwise, assume that str
            contains a hostname."""
        if str == '': str = ' '
        if str[0] in string.digits:
            try:
                value = socket.gethostbyaddr(str)[0]
            except:
                value = 'Lookup failed'
        else:
            try:
                value = socket.gethostbyname(str)
            except:
                value = 'Lookup failed'
        return value 
Example 23
Project: python2-tracer   Author: extremecoders-re   File: dnslookup-1.py    (license) View Source Project 6 votes vote down vote up
def dnslookup(str):
    """ Perform DNS lookup on str.  If first character of digit is numeric,
        assume that str contains an IP address.  Otherwise, assume that str
        contains a hostname."""
    if str == '': str = ' '
    if str[0] in string.digits:
        try:
            value = socket.gethostbyaddr(str)[0]
        except:
            value = 'Lookup failed'
    else:
        try:
            value = socket.gethostbyname(str)
        except:
            value = 'Lookup failed'
    return value 
Example 24
Project: Project-ET   Author: p0rt22   File: Project-ET.py    (license) View Source Project 6 votes vote down vote up
def traceIP(target):
		try:
			base = GeoIP('GeoLiteCity.dat')
			data = base.record_by_addr(target)
			dnsName = socket.gethostbyaddr(target)[0]
			formatedData = '''IP: {}
City: {}
State/Province: {}
Country: {}
Continent: {}
Zip/Postal code: {}
Timezone: {}
Latitude: {}
Longitude: {}
DNS name: {}'''.format(target, data['city'], data['region_code'], data['country_name'], data['continent'], data['postal_code'], data['time_zone'], str(data['latitude']), str(data['longitude']), dnsName)
			print formatedData
			# compares target to database and print results to console
			
			askSave = raw_input('Save data? Y/n: ').lower()
			if askSave == 'y':
				ipFileName = raw_input('Filename: ')
				
				with open(ipFileName, 'w') as fileName:
					fileName.write(formatedData)

				print 'Output saved as {}'.format(ipFileName)

			else:
				pass
			# asks user if they want to save the output

			pause()
			main()

		except socket.herror:
			pass 
Example 25
Project: ysrc   Author: myDreamShadow   File: crack_smb.py    (license) View Source Project 6 votes vote down vote up
def ip2hostname(ip):
    try:
        hostname = socket.gethostbyaddr(ip)[0]
        return hostname
    except:
        pass
    try:
        query_data = "\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x20\x43\x4b\x41\x41" + \
                     "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41" + \
                     "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x00\x00\x21\x00\x01"
        dport = 137
        _s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _s.sendto(query_data, (ip, dport))
        x = _s.recvfrom(1024)
        tmp = x[0][57:]
        hostname = tmp.split("\x00", 2)[0].strip()
        hostname = hostname.split()[0]
        return hostname
    except:
        pass 
Example 26
Project: ysrc   Author: myDreamShadow   File: scan.py    (license) View Source Project 6 votes vote down vote up
def ip2hostname(self,ip):
        try:
            hostname = socket.gethostbyaddr(ip)[0]
            return hostname
        except:
            pass
        try:
            query_data = "\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x20\x43\x4b\x41\x41" + \
                         "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41" + \
                         "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x00\x00\x21\x00\x01"
            dport = 137
            _s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            _s.sendto(query_data, (ip, dport))
            x = _s.recvfrom(1024)
            tmp = x[0][57:]
            hostname = tmp.split("\x00", 2)[0].strip()
            hostname = hostname.split()[0]
            return hostname
        except:
            pass 
Example 27
Project: sslstrip-hsts-openwrt   Author: adde88   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example 28
Project: sslstrip-hsts-openwrt   Author: adde88   File: unix.py    (license) View Source Project 6 votes vote down vote up
def addUTMPEntry(self, loggedIn=1):
        if not utmp:
            return
        ipAddress = self.avatar.conn.transport.transport.getPeer().host
        packedIp ,= struct.unpack('L', socket.inet_aton(ipAddress))
        ttyName = self.ptyTuple[2][5:]
        t = time.time()
        t1 = int(t)
        t2 = int((t-t1) * 1e6)
        entry = utmp.UtmpEntry()
        entry.ut_type = loggedIn and utmp.USER_PROCESS or utmp.DEAD_PROCESS
        entry.ut_pid = self.pty.pid
        entry.ut_line = ttyName
        entry.ut_id = ttyName[-4:]
        entry.ut_tv = (t1,t2)
        if loggedIn:
            entry.ut_user = self.avatar.username
            entry.ut_host = socket.gethostbyaddr(ipAddress)[0]
            entry.ut_addr_v6 = (packedIp, 0, 0, 0)
        a = utmp.UtmpRecord(utmp.UTMP_FILE)
        a.pututline(entry)
        a.endutent()
        b = utmp.UtmpRecord(utmp.WTMP_FILE)
        b.pututline(entry)
        b.endutent() 
Example 29
Project: wptagent   Author: WPO-Foundation   File: devtools_parser.py    (license) View Source Project 6 votes vote down vote up
def get_base_page_info(self, page_data):
        """Find the reverse-ip info for the base page"""
        domain = urlparse.urlsplit(page_data['final_url']).hostname
        try:
            import socket
            addr = socket.gethostbyname(domain)
            host = str(socket.gethostbyaddr(addr)[0])
            page_data['base_page_ip_ptr'] = host
        except Exception:
            pass
        # keep moving up the domain until we can get a NS record
        while domain is not None and 'base_page_dns_soa' not in page_data:
            try:
                import dns.resolver
                dns_servers = dns.resolver.query(domain, "NS")
                dns_server = str(dns_servers[0].target).strip('. ')
                page_data['base_page_dns_ns'] = dns_server
            except Exception:
                pass
            pos = domain.find('.')
            if pos > 0:
                domain = domain[pos + 1:]
            else:
                domain = None 
Example 30
Project: cheapstream   Author: miltador   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example 31
Project: web_ctp   Author: molebot   File: test_socket.py    (license) View Source Project 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            return
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            return
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 32
Project: ssh   Author: GDGVIT   File: scanner.py    (license) View Source Project 6 votes vote down vote up
def TCP_connect(ip, port_number, delay, hosts):
    host_name = 'Unknown'
    TCPsock = socket.socket()
    TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    TCPsock.settimeout(delay)
    try:
        host_name = socket.gethostbyaddr(ip)[0]
        # print(host_name)
    except socket.herror:
        pass
    try:
        TCPsock.connect((ip, port_number))
        if 'SSH' in str(TCPsock.recv(256)):
            hosts.append((host_name, ip))
            # print(host_name,ip)
    except (OSError, ConnectionRefusedError):
        pass 
Example 33
Project: MgmtAppForLinuxMachines_flask   Author: yugokato   File: validation.py    (license) View Source Project 6 votes vote down vote up
def is_aws(ipaddr):
        if Validation.check_internet_connection():
            if ipaddr in Validation.__aws_cache:
                return True
            elif ipaddr in Validation.__no_aws_cache:
                return False
            else:   # if ipaddr not in chache
                try:
                    result = socket.gethostbyaddr(ipaddr)
                    for line in result:
                        if 'compute.amazonaws.com' in line:
                            Validation.__aws_cache.append(ipaddr)
                            return True
                except socket.herror:
                    Validation.__no_aws_cache.append(ipaddr)
        return False 
Example 34
Project: Infrax-as-Code-1000-webservers-in-40-minutes   Author: ezeeetm   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example 35
Project: FuzzFlow   Author: talos-vulndev   File: helper.py    (license) View Source Project 6 votes vote down vote up
def register_host(self):
        print "[*] Trying to register the host..."
        platform_id = self.get_platform_id()
        arch_id = self.get_arch_id()
        mac = self.get_mac()
        hostname, alias_list, addr_list = socket.gethostbyaddr(self.get_default_ip())
        ip = addr_list[0]
        host_payload = {
            'name' : hostname,
            'mac' : mac,
            'ip' : ip,
            'platform_id': platform_id,
            'arch_id': arch_id
        }

        self.host = Rest.get_host_by_mac(mac)
        if self.host is not None:
            print "[!] Host with mac address %s has already been registered." % mac
            Rest.update_host(self.host['id'], host_payload)
        else:
            self.host = Rest.create_host(host_payload)

        return self.host 
Example 36
Project: smarthome   Author: smarthomeNG   File: __init__.py    (license) View Source Project 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 37
Project: kekescan   Author: xiaoxiaoleo   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example 38
Project: kekescan   Author: xiaoxiaoleo   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example 39
Project: commons   Author: Tendrl   File: ceph_help.py    (license) View Source Project 6 votes vote down vote up
def existing_mons(parameters):
    mons = json.loads(
        NS._int.client.read(
            "clusters/%s/maps/mon_map/data" %
            parameters["TendrlContext.integration_id"]
        ).value
    )['mons']

    created_mons = []
    for mon in mons:
        mon_ip = mon['addr'].split(':')[0]
        mon_host_name = socket.gethostbyaddr(mon_ip)[0]
        created_mons.append(
            {
                "address": mon_ip,
                "host": mon_host_name
            }
        )

    return created_mons 
Example 40
Project: pefile.pypy   Author: cloudtracer   File: test_socket.py    (license) View Source Project 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 41
Project: ouroboros   Author: pybee   File: test_socket.py    (license) View Source Project 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except OSError:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except OSError:
            # Probably a similar problem as above; skip this test
            self.skipTest('name lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 42
Project: ndk-python   Author: gittor   File: test_socket.py    (license) View Source Project 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            return
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            return
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 43
Project: apt2   Author: Exploit-install   File: gethostname.py    (license) View Source Project 6 votes vote down vote up
def process(self):
        # load any targets we are interested in
        self.getTargets()

        # loop over each target
        for t in self.targets:
            # verify we have not tested this host before
            if not self.seentarget(t):
                # add the new IP to the already seen list
                self.addseentarget(t)
                self.display.verbose(self.shortName + " - Connecting to " + t)
                try:
                    results = socket.gethostbyaddr(t)
                    self.fire("newHostName")
                    kb.add('host/' + t + '/hostname/' + results[0])
                except:
                    pass

        return 
Example 44
Project: apt2   Author: wi-fi-analyzer   File: gethostname.py    (license) View Source Project 6 votes vote down vote up
def process(self):
        # load any targets we are interested in
        self.getTargets()

        # loop over each target
        for t in self.targets:
            # verify we have not tested this host before
            if not self.seentarget(t):
                # add the new IP to the already seen list
                self.addseentarget(t)
                self.display.verbose(self.shortName + " - Connecting to " + t)
                try:
                    results = socket.gethostbyaddr(t)
                    self.fire("newHostName")
                    kb.add('host/' + t + '/hostname/' + results[0])
                except:
                    pass

        return 
Example 45
Project: game   Author: chrisnorman7   File: server.py    (license) View Source Project 6 votes vote down vote up
def on_connect(self, caller):
    """Add account and player to caller.connection."""
    con = caller.connection
    try:
        con.host = gethostbyaddr(con.host)[0]
        con.logger.name = '%s:%d' % (con.host, con.port)
    except Exception as e:
        con.logger.warning('Could not resolve the hostname:')
        con.logger.exception(e)
    con.connected_at = datetime.utcnow()
    con.account = None
    con.player = None
    con.notify(self.options.welcome_msg)
    reactor.callLater(
        self.options.login_timeout,
        do_timeout,
        con
    ) 
Example 46
Project: LiveScript   Author: rekliner   File: OSC.py    (license) View Source Project 6 votes vote down vote up
def getOSCTarget(self, address):
		"""Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
		'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
		Returns (None, ['',{}]) if address not found.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if (type(address) == types.TupleType): 
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
					
			if (address in self.targets.keys()):
				try:
					(host, _, _) = socket.gethostbyaddr(host)
				except socket.error:
					pass
	
				return ((host, port), self.targets[address])

		return (None, ['',{}]) 
Example 47
Project: nav   Author: UNINETT   File: radiuslib.py    (license) View Source Project 6 votes vote down vote up
def lookup_ip_address(self, ip):
        """
        Perform a reverse DNS lookup for ip.

        Uses self.cache to speed up results when the same ip is
        lookup up several times during one session.

        :param ip: IP address to look up
        """

        if ip is None:
            return None
        if ip not in self.cache:
            try:
                self.cache[ip] = gethostbyaddr(ip)[0]
            except (herror, gaierror):
                # if lookup fails, return the input address
                self.cache[ip] = ip

        return self.cache[ip] 
Example 48
Project: nav   Author: UNINETT   File: utils.py    (license) View Source Project 6 votes vote down vote up
def hostname(ip):
    """
    Performs a DNS reverse lookup for an IP address and caches the result in
    a global variable, which is really, really stupid.

    :param ip: And IP address string.
    :returns: A hostname string or a False value if the lookup failed.

    """
    addr = unicode(ip)
    if addr in _cached_hostname:
        return _cached_hostname[addr]

    try:
        dns = gethostbyaddr(addr)
    except herror:
        return False

    _cached_hostname[addr] = dns[0]
    return dns[0] 
Example 49
Project: nav   Author: UNINETT   File: edit.py    (license) View Source Project 6 votes vote down vote up
def resolve_ip_and_sysname(name):
    """Given a name that can be either an ip or a hostname/domain name, this
    function looks up IP and hostname.

    name - ip or hostname

    Returns:
     - tuple with ip-addres and sysname
    """
    try:
        ip_addr = IP(name)
    except ValueError:
        ip_addr = IP(gethostbyname(name))
    try:
        sysname = gethostbyaddr(unicode(ip_addr))[0]
    except SocketError:
        sysname = unicode(ip_addr)
    return (ip_addr, sysname) 
Example 50
Project: recon-ng   Author: captainhooligan   File: ssh.py    (license) View Source Project 6 votes vote down vote up
def module_thread(self, host, user, password):
	    s = pxssh.pxssh()
		try:
		    self.verbose('Trying host: {0} with User: {1} and Password: {2}'.format(host, user, password))
			s.login(host, user, password)
			self.alert('Login successful for {}'.format(host))
			try:
			    name = gethostbyaddr(host)[0]
			except:
			    name = ''
			try:
			    self.verbose('Adding host: {} to credentials.'.format(host))
				self.add_credentials(ip_address=host, username=user, password=password)
				self.add_hosts(ip_address=host, host=name)
			except Exception as e:
			    self.error('Unable to add credentials. Error: {}'.format(e))
			s.logout()