Created
May 7, 2014 21:47
-
-
Save growse/b4fda1b647f0bc2d18c0 to your computer and use it in GitHub Desktop.
Script to measure gateway ping and wifi strength/bitrate and pipe into graphite.
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
#!/usr/bin/env python | |
import argh | |
import sh | |
import subprocess | |
import ping | |
import socket | |
import time | |
import sys | |
import re | |
internet_host = '8.8.8.8' | |
def find_gateway(): | |
gateway_line = sh.traceroute(internet_host).split('\n')[1] | |
return gateway_line.strip().split()[1] | |
def ping_host(host_name): | |
delay = ping.do_one(host_name, 9, 64) | |
if not delay: | |
return None | |
return round(delay * 1000, 4) | |
def send_metric(name, value): | |
sock = socket.socket() | |
sock.connect(("localhost", 2003)) | |
sock.send("%s %d %d\n" % (name, float(value), int(time.time()))) | |
sock.close() | |
def is_ipv4(ip): | |
match = re.match("^(\d{0,3})\.(\d{0,3})\.(\d{0,3})\.(\d{0,3})$", ip) | |
if not match: | |
return False | |
quad = [] | |
for number in match.groups(): | |
quad.append(int(number)) | |
if quad[0] < 1: | |
return False | |
for number in quad: | |
if number > 255 or number < 0: | |
return False | |
return True | |
def main(): | |
failures = 0 | |
gateway_host = find_gateway() | |
if not is_ipv4(gateway_host): | |
print "Error: not valid gateway {}".format(gateway_host) | |
sys.exit(1) | |
print 'Measuring ping latency to {}'.format(gateway_host) | |
try: | |
while True: | |
essid = '' | |
bitrate = 0 | |
signallevel = 0 | |
cmd = subprocess.Popen('iwconfig wlan0', shell=True, | |
stdout=subprocess.PIPE) | |
for line in cmd.stdout: | |
if 'ESSID' in line: | |
essid = line.split()[3].replace('ESSID:', '').strip('"') | |
elif 'Bit Rate' in line: | |
bitrate = line.split()[1].replace('Rate=', '') | |
elif 'Link Quality' in line: | |
signallevel = line.split()[3].replace('level=', '') | |
elif 'Not-Associated' in line: | |
print 'No signal' | |
if essid != '': | |
send_metric('wifi.{}.bitrate'.format(essid), bitrate) | |
send_metric('wifi.{}.signallevel'.format(essid), signallevel) | |
gateway_ping_time = ping_host(gateway_host) | |
if not gateway_ping_time: | |
failures += 1 | |
send_metric("network.dropout", failures) | |
print 'packet loss' | |
else: | |
send_metric("network.ping_time", gateway_ping_time) | |
print gateway_ping_time | |
failures = 0 | |
time.sleep(10) | |
except KeyboardInterrupt: | |
pass | |
if __name__ == '__main__': | |
argh.dispatch_command(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment