Created
December 6, 2019 11:05
-
-
Save Cyklan/033974ced3d74ea28627b73c8b0a4323 to your computer and use it in GitHub Desktop.
Ping an IP and log its availability
This file contains 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
import datetime | |
import os | |
import platform | |
import sys | |
import threading | |
def how_to_use(): | |
print("Usage: python3 ping.py [ip adress] [log|csv] [interval]\n") | |
print("\tip adress = server adress to ping\n") | |
print("\tlog = save to log file") | |
print("\tcsv = save to csv file\n") | |
print("\tinterval = logging interval in seconds") | |
exit() | |
def get_command(ip): | |
operating_system = platform.system() | |
if (operating_system == "Windows"): | |
command = f"ping {ip} -n 1 | echo Pinging {ip}" | |
else: | |
command = f"ping {ip} -c 1 2>&1 >/dev/null | echo Pinging {ip}" | |
return command | |
def ping(ip, command, output): | |
timestamp = datetime.datetime.now() | |
available = "available" if os.system(command) == 0 else "unavailable" | |
log_output = f"{timestamp}: Server {ip} {available}\n" | |
csv_output = f"{timestamp},{ip},{available}\n" | |
if str.lower(output) == "log": | |
return log_output | |
if str.lower(output) == "csv": | |
return csv_output | |
def write_to_file(ip, result, output): | |
if output == "log": | |
filename = f"{ip}.log" | |
elif output == "csv": | |
filename = f"{ip}.csv" | |
if (os.path.exists(filename)): | |
append_write = "a" | |
else: | |
append_write = "w" | |
f = open(filename, append_write) | |
f.write(result) | |
f.close() | |
def monitor(): | |
interval = float(sys.argv[3]) | |
threading.Timer(interval, monitor).start() | |
ip = sys.argv[1] | |
output = sys.argv[2] | |
command = get_command(ip) | |
result = ping(ip, command, output) | |
write_to_file(ip, result, output) | |
if len(sys.argv) is not 4: | |
print("Invalid Argument length\n") | |
how_to_use() | |
if (sys.argv[2] != "csv" and sys.argv[2] != "log"): | |
print("Invalid file extension") | |
print("Argument must either be 'csv' or 'log'\n") | |
how_to_use() | |
if not sys.argv[3].isdigit(): | |
print("Invalid interval") | |
print("Argument is not a number\n") | |
how_to_use() | |
monitor() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment