Convert List of Domain Names to their IP - Python

Hello All,

In this post we are going to use python socket module and file handling to convert a file of confirmed malicious domain names into their respective IP address.  After the list has been processed one could take the list of IP addresses and add these to your company/personal firewall.

Below is a list of actual bad domains[you probably shouldn't visit these ;) ]
This is list we will be using in our demonstration

Image below is the output after the script is run.  

*notice that 9 domains went into the grinder and only 5 IP addresses came out.  If you look at the python code more closely you will see  "Try..Except" where we raise an exception for a specific error "socket.gaierror."  When the socket module attempts to resolve the domain name, some domains are not able to be resolved so an error is sent.  A possible cause of this is the domain is not in action any more.  However getting the 5 as output shows that these bad websites are still reachable.

General Functionality:
-Script opens a file of bad domains
-cleans the input and sends the value to a function that puts that value through a functionality of the socket module that retrieves IP address
-Finally the retrieved IP addresses are exported to an output file.

Deeper Dive:
1-2: import modules
5-6: create file object and create a list "row" that contains all the lines of the file "malwaredomainlist.txt"
17-24: for each line in row send domain to getIP function, returned IP, send IP to output function to be added to output.txt 

There are other ways to retrieve the IP address of a website like:

nslookup <site address>


ping <site address>

These tools are great and useful, however if you have a huge batch of domains to process, having a python script on hand can be extremely useful and time saving.


Popular Posts