Last active
March 25, 2020 19:17
-
-
Save bockor/50fb07e0edaccbd879f2f4af8c428857 to your computer and use it in GitHub Desktop.
pythonping example with exceptions error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
#Ref: https://www.ictshore.com/python/python-ping-tutorial/ | |
#Ref: https://stackoverflow.com/questions/58330533/how-to-handle-error-exceptions-with-pythonping | |
#Ref: https://kite.com/python/docs/csv.DictWriter.writerows | |
from pythonping import ping | |
import socket | |
import csv | |
with open('public_dns_names.csv', 'r') as csv_in_file, \ | |
open('results.csv', 'w') as csv_out_file: | |
csv_in = csv.reader(csv_in_file) | |
hosts = [] | |
results= [] | |
for row in csv_in: | |
hosts.append(row[0]) | |
for host in hosts: | |
try: | |
ip = socket.gethostbyname(host) | |
result = ping(ip, count=1) | |
# the machine responds the ICMP request | |
if result.success(): | |
print(host, 'ICMP_REPLIED') | |
results.append({'HOST': host, 'IP': ip, 'RESULT':'ICMP_REPLIED'}) | |
#the machine does NOT respond the ICMP request | |
else: | |
print(host, 'ICMP_IGNORED') | |
results.append({'HOST': host, 'IP': ip, 'RESULT':'ICMP_IGNORED'}) | |
# no DNS resolution for host | |
except socket.error: | |
#pass | |
print(host,'DNS_NO_RESOLUTION') | |
results.append({'HOST': host, 'RESULT':'DNS_NO_RESOLUTION'}) | |
#print(results) | |
writer = csv.DictWriter( csv_out_file, fieldnames=['HOST', 'IP', 'RESULT']) | |
writer.writeheader() | |
writer.writerows(results) | |
print('DONE') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment