Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get host from ip
#1
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"
Reply
#2
This might be what you need: https://github.com/MaxHorstmann/ArinWhois.NET
Install with pip:
Install-Package ArinWhois
it 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
Reply
#3
sorry, I'm not thinking well today,

all you need is:
import socket
socket.gethostbyaddr(ip)
Reply
#4
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  where to host my python script tomtom 1 1,231 Feb-09-2022, 06:45 AM
Last Post: ndc85430
  Failing to connect to a host with WMI tester_V 6 4,278 Aug-10-2021, 06:25 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020