Skip to content

Instantly share code, notes, and snippets.

@airdrummingfool
Last active August 29, 2015 14:04
Show Gist options
  • Save airdrummingfool/572fc6c42c5c2a0b5a5a to your computer and use it in GitHub Desktop.
Save airdrummingfool/572fc6c42c5c2a0b5a5a to your computer and use it in GitHub Desktop.
Pinger.py: for tracking network downtime. `python pinger.py <ip> <backup ip> [-v] [-t <tolerance>] [-l <logfile>]`
"""
pinger.py
Tommy Goode
tgoode.com
"""
import os, sys, time
import datetime
import getopt
VERBOSITY_OFF = 0
VERBOSITY_LOW = 1
# input parsing
try:
opts, args = getopt.getopt(sys.argv[1:],"hvt:l:",["tolerance=", "logfile="])
except getopt.GetoptError:
print 'pinger.py <ip> <backup ip> [-v] [-t <tolerance>] [-l <logfile>]'
sys.exit(2)
verbosity = VERBOSITY_OFF
logfile = None
tolerance = 3
for opt, arg in opts:
if opt == '-h':
print 'pinger.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt == '-v':
verbosity = VERBOSITY_LOW
elif opt in ("-t", "--tolerance"):
argi = int(arg)
if argi >= 0 and argi < 10:
tolerance = argi + 1
else:
print 'Tolerance must be between 0 and 9 (entered: ' + arg +').'
exit(1)
elif opt in ("-l", "--logfile"):
logfile = arg
if len(args) < 1:
print 'Please specify an IP address to ping.'
exit(1)
ip = args[0]
backup_ip = args[1] if len(args) >= 2 else None
is_windows = os.name == 'nt'
# print function for non-line breaks and debugging
def debug_print(str, level=VERBOSITY_OFF, linebreak=True):
if level > verbosity:
return
sys.stdout.write(str)
if linebreak:
sys.stdout.write('\n')
sys.stdout.flush()
def debug_log(str):
if logfile is None:
return
log = open(logfile, 'a')
log.write(str + '\n')
log.close()
# ping method declaration
def ping(hostname, backup_hostname=None):
ping_format = "ping -n 1 -w 2000 {} > NUL" if is_windows else "ping -c 1 -t 2 {} > /dev/null 2>&1"
response = os.system(ping_format.format(hostname))
if response == 0:
return True
if backup_hostname == None:
return False
backup_response = os.system(ping_format.format(backup_hostname))
if backup_response == 0:
debug_print('h', VERBOSITY_LOW, linebreak=False)
return True
else:
return False
# ping given IP
is_down = False
fail_date = None
up_date = datetime.datetime.now()
fail_counter = 0
debug_print('Pinger started at {}. IP {}, backup {}'.format(datetime.datetime.now(), ip, backup_ip), VERBOSITY_OFF)
debug_log('Pinger started at {}. IP {}, backup {}'.format(datetime.datetime.now(), ip, backup_ip))
try:
while True:
if ping(ip, backup_ip):
debug_print(' ', VERBOSITY_LOW, linebreak=False)
if is_down:
up_date = datetime.datetime.now()
if not is_windows:
os.system("say bro the internet is finally back &")
debug_print('\ninternet returned at {} after {} failed checks totaling {} seconds'.format(up_date, fail_counter, (up_date-fail_date).total_seconds()), VERBOSITY_OFF)
debug_log('{},{},{}\n'.format(fail_date,up_date, fail_counter))
fail_date = None
fail_counter = 0
is_down = False
else:
debug_print('.', VERBOSITY_LOW, linebreak=False)
if fail_date == None:
fail_date = datetime.datetime.now()
fail_counter += 1
if fail_counter == tolerance:
if not is_windows:
os.system("say yo yo yo the internet is down again sucka &")
debug_print('\ninternet went down at {}'.format(fail_date), VERBOSITY_OFF)
is_down = True
time.sleep(2)
except(KeyboardInterrupt):
debug_print('\nPinger stopped at {}'.format(datetime.datetime.now()), VERBOSITY_OFF)
debug_log('Pinger stopped at {}'.format(datetime.datetime.now()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment