Python,ping,csv
Jason Friedman
jsf80238 at gmail.com
Mon Apr 11 20:01:00 EDT 2016
> I added a line.
> I would need to put the output into a csv file which contained the
> results of the hosts up and down.
> Can you help me?
>
> import subprocess
> from ipaddress import IPv4Network
> for address in IPv4Network('10.24.59.0/24').hosts():
> a = str(address)
> res = subprocess.call(['ping', '-c', '3', address])
>
"""Typical output from ping:
$ ping -c 3 10.2.2.2
PING 10.2.2.2 (10.2.2.2) 56(84) bytes of data.
--- 10.2.2.2 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 1999ms
$ ping -c 3 localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.030 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.040 ms
64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.042 ms
--- localhost ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.030/0.037/0.042/0.007 ms
"""
import csv
import ipaddress
import re
import subprocess
import sys
NETWORK = "192.168.1.0"
MASK = "24"
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(("Address", "% success"))
for address in ipaddress.IPv4Network('%s/%s' % (NETWORK,
MASK)).hosts():
print("Pinging %s ..." % address, file=sys.stderr)
command = "ping -c 3 %s" % address
output = subprocess.getoutput(command)
match = re.search(r"(\d+)% packet loss", output)
if match:
percent_lost = match.group(1)
writer.writerow((str(address), 100 - int(percent_lost)))
else:
# If we reach this point the ping command output
# was not in the expected output format
writer.writerow((str(address), ""))
More information about the Python-list
mailing list