Building Python Script to test if servers are offline

Question:

I am new to python so forgive my ignorance. I am trying to build a script to find and remove servers that have been removed from DNS vs servers that still resolve.

The issue I am having is I know the function will error out on servers with no DNS. How do separate the 2 into different buckets

servers = open("test2.txt", 'r')

 

for server in servers:

try:

    result = socket.gethostbyname(server)

    break

except Exception:

    print("No DNS")

else:

    print(server)
Asked By: user2091722

||

Answers:

You could make two lists, one for each and with try except looping until the end of file. Txt file needs to be formatted as such that there is 1 ip address per line, and then we add servers with no DNS entry into unresolved with the exception. For example try this

import socket

resolved_servers = []
unresolved_servers = []

path = "C:/temp/servers.txt"
servers = open(path, 'r')

for server in servers:
    try:
        result = socket.gethostbyname(server)
        resolved_servers.append(server)
    except Exception:
        unresolved_servers.append(server)

print("Resolved servers:", resolved_servers)
print("Unresolved servers:", unresolved_servers)
Answered By: Ietu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.