Get host from ip - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Get host from ip (/thread-7965.html) |
Get host from ip - antmar904 - Jan-31-2018 Hi All, First time post and first python script ever! :) I am trying to create a python script that will have one argument passed to it: python IPToHostName.py 1.1.1.1 I would like to get the host name of the ip address passed to that script and write that to a log file named the data and time the script was run but I am having issues. import sys import socket import time print(sys.argv[1]) #Debug n = time.strftime("%Y%m%d-%H%M%S") print(n) #Debug logfile = "C:/Stuff/Scripts/Python/%s.txt" % n IP = sys.argv[1] #Set the varible named "IP" = the sourceip from QRadar print(IP) print(logfile) with open(logfile, 'a') as f: try: host = socket.gethostbyaddr(IP.rstrip()) hostname=host[0] print >> f, '', IP.rstrip(),",",hostname except Exception as e: print >> f, '', IP.rstrip(),",NULL" RE: Get host from ip - Larz60+ - Jan-31-2018 This might be what you need: https://github.com/MaxHorstmann/ArinWhois.NET Install with pip: Install-Package ArinWhoisit is a package for calling Arin whois service I just tried to install with pip, and there is no package in PyPi. The github repository is 4 years old, and hasn't been worked on since 2014. So, you might explore the code to get some ideas. There is also another package which is in PyPi, and can be installed with pip, named whois. It's also old, but has versions for python 2 and 3. link: https://pypi.python.org/pypi/whois/0.7 RE: Get host from ip - Larz60+ - Jan-31-2018 sorry, I'm not thinking well today, all you need is: import socket socket.gethostbyaddr(ip) RE: Get host from ip - antmar904 - Jan-31-2018 Thank you for your help. I finally figured it out. This seems to be working. import sys import socket import time n = time.strftime("%Y%m%d-%H%M%S") IP = sys.argv[1] host = socket.gethostbyaddr(IP) hostname=host[0] logfile = "C:/temp/%s.txt" % n f1=open(logfile, 'a') f1.write(IP+","+hostname+"\n") f1.close() sys.exit() |