Using Python to resolve multiple hostnames to IP addresses

As a Network Engineer, I work with IP addresses all day long. But most of the time I am handed out hostnames rather than IP addresses to work with. I can of course use nslookup or ping to quickly resolve the hostnames to IP addresses but imagine having more than 10 hosts to manage? I would have to run ping 10 times to resolve all the hosts. I’m sure you are thinking whether there are other ways to automate this? Of course, there are multiple ways to achieve this, however, from my experience I find the Python method to be far more efficient.

In this blog, I will show you two rather simple methods for this simple task. The first one is to create a text file with all the hosts in it and then use Python to resolve them and save it to a different file.

The second method is the quickest one where you just need to copy the hostnames to your clipboard (ctrl +c), run the script and then paste (ctrl +v). The newly pasted contents will have the hostname to IP mapping.

Method - 1

I have two files in my directory as shown below, one file contains a list of hostnames and the other one is the script itself. I randomly added a host Gthy67865.com to the list to show you what happens when a host is unresolvable.

suresh@MAC:~|⇒  ls /Users/suresh/Python/host
input.txt             
script_host.py
suresh@MAC:~cat input.txt

bbc.co.uk
bmw.com
Gthy67865.com
apple.com
slack.com
cisco.com
import socket

with open(r'/Users/suresh/Python/host/input.txt', 'r') as r_file:
    with open(r'/Users/sureshPython/host/ips.txt', 'w') as w_file:
        for hostname in r_file.readlines():
            hostname = hostname.strip()
            try:
                print('Resolving : ' + hostname)
                ip = socket.gethostbyname(hostname)
                w_file.write(hostname + ' - ' + ip + '\n')
            except:
                print('Unable to resolve: ' + hostname)

When I run the script, python reads the input.txt file and resolves all the hosts in the list ips.txt as shown below.

suresh@MAC:~python script_host.py

Resolving : bbc.co.uk
Resolving : bmw.com
Resolving : Gthy67865.com
Unable to resolve: Gthy67865.com
Resolving : apple.com
Resolving : slack.com
Resolving : cisco.com
suresh@MAC:~cat ips.txt

bbc.co.uk - 151.101.0.81
bmw.com - 160.46.226.165
apple.com - 17.253.144.10
slack.com - 18.169.61.189
cisco.com - 72.163.4.185
  • import socket - Python comes with a set of modules called the standard library such as random and socket. Before you can use the functions in a module, you should import them with an import statement. As shown above, if I want to use gethostbyname function within socket, I must import the socket module.
  • with statement allows the execution of initialization and finalisation code around a block of code. Usually, when you open a file within Python, the file must be closed after the code execution. with statement simplifies this by ensuring the file is properly closed.
  • open() function opens the file and returns the corresponding file object.
  • We can place an r before the beginning of the quotation mark of a string to make it a raw string which completely ignores any escape characters (backlashes for example)
  • 'r' opens a file for reading. All we want the script to do is, open the input.txt file for reading. We don't want python to edit this file.
  • 'w' opens the file for writing. If the file doesn't exist, Python will create a file for us.
  • for loop executes a code block a certain number of times.
  • readlines() method return all lines in a file, as a list. Each line is an item in that list. In this example, we are looping through the list items (hostname) by using a for loop.
  • strip() method returns a copy of the string without any whitespace characters at the beginning or end.
  • Errors can be handled by try and except statements. For example, our script will fail/crash if any of the host in the list has a typo (unresolvable) If any of the hostname is unresolvable, the code execution moves to the except clause.
  • socket gethostbyname function returns the IP address of the host.

Method - 2

The second method is the quickest one where you just need to copy the hostnames to your clipboard (ctrl +c) , run the script and then paste (ctrl +v). The newly pasted contents will have the hostname to IP mapping. You can install pyperclip module by using pip3 install pyperclip command.

I'm going to copy the following contents to my clipboard, run the script and then paste the content back.

ctrl + c

gov.uk
google.co.uk
random6785rtg.com
sony.com
lg.com
import socket
import pyperclip

hostnames = pyperclip.paste()
host_list = hostnames.split('\n')

for i in range(len(host_list)):
    try:
        print('Resolving: ' + host_list[i])
        host_list[i] = host_list[i] + ' - ' + str(socket.gethostbyname(host_list[i]))
    except:
        print('Unable to resolve: ' + host_list[i])

hostnames = '\n'.join(host_list)
pyperclip.copy(hostnames)
suresh@MAC:~python copy_host.py

Resolving: gov.uk
Resolving: google.co.uk
Resolving: random6785rtg.com
Unable to resolve: random6785rtg.com
Resolving: sony.com
Resolving: lg.com
ctrl + v

gov.uk - 151.101.128.144
google.co.uk - 142.250.179.227
random6785rtg.com
sony.com - 52.54.18.9
lg.com - 76.223.18.25
  • pyperclip module comes with copy() and paste() functions that can access the local computer's clipboard.

Thanks for reading. As always, your feedback and comments are always welcome.