Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Building Python Script to test if servers are offline

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')

 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for server in servers:

try:

    result = socket.gethostbyname(server)

    break

except Exception:

    print("No DNS")

else:

    print(server)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading