This question already has an answer here:
Read a list of hostnames and resolve to IP addresses
(1 answer)
Closed 1 year ago.
I have create a script to resolve IP to hostname. The script does not resolve the hostname, it gives the following error:
cannot resolve hostname: 10.10.10.10
[Errno 11004] getaddrinfo failed
cannot resolve hostname: 10.10.10.10 [Errno 11004] getaddrinfo failed
Please suggest. I'm new to python. The text file contains more than 1000 IPs.
#!/usr/bin/python
import socket
pfile = open ('C:\\Python27\\scripts\\test.txt')
while True:
IP = pfile.readline()
if not IP:
break
try:
host = socket.gethostbyaddr("IP")
print host, IP
except socket.gaierror, err:
print "cannot resolve hostname: ", IP, err
pfile.close()
There are two problems here.
First, as FatalError pointed out, you're not looking up the value of the IP variable, but the string "IP".
Second, pfile.readline() is going to leave a trailing newline at the end of the IP string, so it's still going to fail.
So:
host = socket.gethostbyaddr(IP.rstrip())
Also, on some platforms, if your DNS isn't working, gethostbyaddr will fail even when given an IP address. So, you may want to do a simple test on the machine you're running the script on (if it's not the same machine you're already using for SO)—e.g., open a browser and go to Google.
As far as I can tell, there are different problems.
The line:
host = socket.gethostbyaddr("IP")
will fail because of the string. To fix this, use host = socket.gethostbyaddr(IP).
Furthermore, the error you posted here is caused by 10.10.10.10 being a private IP. The ranges 10.0.0.0–10.255.255.255, 172.16.0.0–172.31.255.255 and 192.168.255.255 are private network blocks; socket.gethostbyaddr() is not able to resolve these addresses. See https://www.rfc-editor.org/rfc/rfc1918 for more information about private blocks.
After a little Googling, I got it to work in Python 3 as follows:
import socket
pfile = open ('C:\\TEMP\\IPs.txt')
while True:
IP = pfile.readline()
try:
host = socket.gethostbyaddr(IP.rstrip())
print(IP,host)
except Exception as e:
print(IP,"NULL")
pfile.close()
This works:
import socket
IP = "www.google.ca"
host = socket.gethostbyaddr(IP)
print host, IP
Related
Trying to get host-IP Through Python, using socket module -
Occasionally, i get address 127.0.0.1 and not the real IP Address - i.e 10.210.24.24
I've adjusted my code per the answer in:
Socket IO returns 127.0.0.1 as host address and not 192.168.0.* on my device
But still get random encounters of 127.0.0.1.
The issue occurs in automation - Which SSH's into the remote host (10.210.24.24 for example),
And runs the below code snippet.
Trying to reproduce manually - i always get the correct IP Address.
My code is as follows:
self.host_name = socket.gethostname()
try:
host_ip = socket.gethostbyname(self.host_name)
if host_ip == "127.0.0.1":
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
host_ip = s.getsockname()[0]
self.host_ip = host_ip
except Exception as e: # In case DNS Resolving fails
logger.warning("Failed setting '%s' IP | %s", self.host_name, str(e))
self.host_ip = ""
I'm trying to understand what am I missing here:
Why would "randomly", i would get 127.0.0.1 instead of the actual host IP.
Given the fact the host definitely has IP Assigned (Since i'm using SSH root# in order to run the script)
How to overcome this issue and make sure i always get the correct IP Address?
In case more debug info is needed -
What logs should i look into once this issue does occur?
I can add "fail handling" to at least dump those logs when the issue occurs in my automation.
System is Debian 11, Python 3.9.
Thanks
Has anyone found a way to specify a DNS server for OpenSSL connections on a Linux OS? We have internal and external DNS servers and I am building a monitor for SSL certificate usage. I need the ability to specify a DNS server to be used on hostname connections. It works just fine against the internal DNS, but I am having difficulty finding a way to tie in a DNS server. I am fairly new to changing networks through Python and am not sure where to begin. Is it possible to do this through the dns.resolver module's nameservers function?
This looks like a viable solution for Windows, but I am hoping to find something similar for Linux.
How to Change DNS Servers Programmatically in Windows?
Below is my code that works against the default DNS host.
def readCerts(self,host,port,cast):
"""readCerts prompts terminal for username.
Attributes:
host: Host or IP of SSL connection
port: Port of SSL connection
cast: Format of returned results (JSON currently only structure supported)
Response:
Returns certificate attributes in specified format
"""
sslContext = SSL.Context(SSL.SSLv23_METHOD)
apiSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sslConnection = SSL.Connection(sslContext,apiSocket)
try:
sslConnection.connect((host,port))
except Exception as e:
raise e
else:
#Block the socket
sslConnection.setblocking(1)
#Set the hostname field for servers that support SNI. Format must be in bytestring.
sslConnection.set_tlsext_host_name(host.encode('utf-8'))
try:
sslConnection.do_handshake()
except:
pass
else:
#print "handshake succeeded"
sslConnection.close()
if cast.upper()=='JSON':
attributes = self._FormatJSON(sslConnection.get_peer_cert_chain())
return attributes
I am fairly new to Python (just started today) but am really struggling with this:
#! /usr/bin/python
import socket
s=socket.socket()
s.connect(("<my ip addres>", 22))
answer=s.recv(1024)
print(answer)
s.close
I believe I am meant to be getting some sort of 'banner' response but it gives nothing for a few minutes before spouting the following error:
TimeoutError: [Errno 60] Operation timed out
Why would this be happening?
First of all make sure you connect to port 22. Then make sure your operating system's firewall doesn't block incoming connections to port 22. In case the address you have configured for the server is "localhost" and try to connect from another machine you won't be able to connect. In that case you shoud use "" as ip address.
I configured my windows machine's DNS server to 127.0.0.1 and on localhost I created a basic python server:
from socket import *
serverPort = 53
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('127.0.0.1', serverPort))
print "The server is ready to receive on port: {}".format(serverPort)
while 1:
try:
message, clientAddress = serverSocket.recvfrom(512)
except:
continue
print clientAddress, message
modifiedMessage = "127.0.0.1"
serverSocket.sendto(modifiedMessage, clientAddress)
PS :I know that DNS is a binary protocol and sending ASCII text won't do any good, but I am not trying to make a resolver, I am trying to see with transperancy that how the former works.
When I srarted the server, I am greated with the following output:
(('127.0.0.1', 53945), '.\x9c\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 53945), '.\x9c\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 53945), '.\x9c\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 61362), '\xefc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 50065), '\xb5\xfc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 61362), '\xefc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 61362), '\xefc\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01')
(('127.0.0.1', 52718), '\xc7\x15\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x05tiles\x08services\x07mozilla\x03com\x00\x00\x01\x00\x01')
But unlike as I enticipated, I am still able to open websites. And Wireshark told me that I am making connection to 8.8.8.8(IDK how?).
I tried flushing the DNS cashe from my machine, nada.
What am I missing?
PPS: If I remove the try/catch clause I get this error(a few seconds after the execution of the program):
error: [Errno 10054] An existing connection was forcibly closed by the remote host
You probably have configured Googles 8.8.8.8 as a fallback DNS server.
And since you are destroying the DNS answers, whoever is receiving these broken answers is falling back to the secondary server. The whole path of DNS queries on a typical UN*X machine is quite complicated and the whole system is usually quite robust.
I am trying to log into a FTP server that I am only running locally in my network. To do this I have to use my ip address to use as the server address (see code below). However each time I get a gaierror: [Errno 11004] getaddrinfo failed error.
Can anyone look at my code and see if I am making any error that may be the cause of this address issue? Also I can log into the ftp server fine from my browser so I know the server is up and running correctly, also anonymous login to the server is allowed .
#import the ftp lib.
from ftplib import FTP
#enter the address of the ftp server to use, use ip address since server is ran locally
ftp = FTP('ftp://192.168.1.130')
#logs into the ftp server
ftp.login()
You're including the protocol with the hostname which is incorrect. What's happening is the library is trying to resolve "ftp://192.168.1.130" (instead of "192.168.1.130"), which isn't a valid address.
#Wrong
ftp = FTP('ftp://192.168.1.130')
#Right
ftp = FTP('192.168.1.130')
http://docs.python.org/library/ftplib.html
According to ftplib documentation, you shoud just give him the host address/IP, and not a string representing an URL. So here, you should simply do:
ftp = FTP('192.168.1.130')