Using Python to resolve multiple hostnames to IP addresses

Using Python to resolve multiple hostnames to IP addresses
In: NetDevOps, Python

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 to the list to show you what happens when a host is unresolvable.

suresh@MAC:~|⇒  ls /Users/suresh/Python/host
suresh@MAC:~cat input.txt
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()
                print('Resolving : ' + hostname)
                ip = socket.gethostbyname(hostname)
                w_file.write(hostname + ' - ' + ip + '\n')
                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.


Resolving :
Resolving :
Resolving :
Unable to resolve:
Resolving :
Resolving :
Resolving :
suresh@MAC:~cat ips.txt - - - - -
  • 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
import socket
import pyperclip

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

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

hostnames = '\n'.join(host_list)

Unable to resolve:
ctrl + v - - - -
  • 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.

Written by
Suresh Vina
Tech enthusiast sharing Networking, Cloud & Automation insights. Join me in a welcoming space to learn & grow with simplicity and practicality.
More from Packetswitch
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Packetswitch.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.