Python: Check IPs for DNS entries and see if host is UP or DOWN. Export info to a CSV file

Checks IPs if they have a DNS entry. If they do it checks if the host is up. If an IP does not have a DNS entry it reports it. It does not report if an IP with out a DNS is down or not

import socket
import subprocess
import  netifaces
import csv
 
def checkPING(IP):
    try:
        ping = subprocess.check_output(['ping', '-c1', ip])
        return "Host is UP"
    except:
        return "Host is DOWN"
 
def checkDNS(IP):
    try:
        dns = socket.gethostbyaddr(ip)
        return dns[0]
    except:
        return "No DNS entry found"
 
 
ip_list = []
dns_list = []
status_list = []
 
csvfile= open('file.csv', 'w')
for loop_ip in range (62):
    ip = '10.0.0.%d' % loop_ip
    print ip, checkDNS(ip), checkPING(ip)
    #data = ip+" ",checkDNS(ip)+" ",checkPING(ip)
    #data_list.append(data)
    ip_list.append(ip)
    dns_list.append(checkDNS(ip))
    status_list.append(checkPING(ip))
writer = csv.writer(csvfile, dialect='excel')
writer.writerows(zip(ip_list, dns_list, status_list))
 
 
'''
#These lines will print each element of the list on a row
writer.writerow(ip_list)
writer.writerow(dns_list)
writer.writerow(status_list)
'''
 
'''
#Also possible threading implementation
for threads_1 in range(1):
    threads_ping.append(threading.Thread(target=executeCheck()))
    threads_ping[-1].start


for threads_2 in range(num_dns):
    threads_dns = append(threading.Thread(target=checkDNS))
    threads_dns.start()

for threads in threads_ping:
    threads.join()

for threads in threads_dns:
    threads.join()
'''
 
OUTPUT:
10.0.0.5 No DNS entry found Host is UP
10.0.0.6 No DNS entry found Host is DOWN
10.0.0.7 No DNS entry found Host is DOWN
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.