Skip to content

Instantly share code, notes, and snippets.

@dadepo
Created October 16, 2019 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dadepo/c63a1b5a7dd7877d35cb57fe8e5f27f6 to your computer and use it in GitHub Desktop.
Save dadepo/c63a1b5a7dd7877d35cb57fe8e5f27f6 to your computer and use it in GitHub Desktop.
import time
import subprocess
import datetime
import sys
import re
import csv
def format_timestamp(timestamp):
return timestamp.strftime("%d_%m_%Y_%H_%M_%S")
# parse the inputs
host_to_ping = sys.argv[1]
try:
duration_to_ping = int(sys.argv[2])
except:
duration_to_ping = 10 # seconds
try:
output_of_ping = sys.argv[3]
except:
output_of_ping = "result"
print(f'The target of the ping is: {host_to_ping}')
print(f'The duration of the ping is: {duration_to_ping}')
command = f'ping -c1 {host_to_ping}'
ping_stop_time = datetime.datetime.now() + datetime.timedelta(seconds=duration_to_ping)
byte_sent = 0
from_address = ""
icmp_seq = 0
ttl = 0
duration = 0
packet_lost = 0
toCsv = []
while datetime.datetime.now() < ping_stop_time:
proc = subprocess.run(command.split(), stdout=subprocess.PIPE)
output = proc.stdout.decode("utf-8")
splitted = output.split("\n")
if len(splitted) <= 1:
result = {"comment": splitted}
continue
second_line = splitted[1]
entries = second_line.split(" ")
result = dict(byte_sent=entries[0],
from_address=entries[3].rstrip(":"),
icmp_seq=entries[4].split("=")[1],
ttl=entries[5].split("=")[1],
duration=entries[6].split("=")[1],
packet_lost=re.search(r"(\d\.\d)(%)", splitted[4]).group(1),
comment="success")
toCsv.append(result)
time.sleep(1)
print(f"results = {toCsv}")
keys = toCsv[0].keys()
with open(f'{output_of_ping}_{format_timestamp(datetime.datetime.now())}_duration_({duration_to_ping}).txt', 'w') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCsv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment