Last active
July 7, 2020 10:24
-
-
Save lepiku/60a664e3102cc0cbe78ece24145beb5a to your computer and use it in GitHub Desktop.
Ping a server (example google) to check for internet consistency. (for windows only)
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 subprocess | |
from time import sleep | |
hostname = "74.125.24.106" | |
host_desc = "Google" | |
amount = 10 | |
time_unstable = 40 | |
time_very_unstable = 100 | |
time_missing = 1000 | |
def ping() -> int: | |
p = subprocess.Popen(["ping.exe","-n", "1", hostname], | |
stdout=subprocess.PIPE, | |
shell=True) | |
response = p.communicate()[0] | |
for s in response.split(): | |
if s[:5] == b'time=': | |
response_time = int(s[5:-2]) | |
return response_time | |
return -1 | |
def avg_ping(response_list): | |
total = 0 | |
for x in response_list: | |
if x != -1: | |
total += x | |
else: | |
total += time_missing | |
return total / len(response_list) | |
def ping_status(avg): | |
if avg >= time_very_unstable or avg == -1: | |
status = "VERY UNSTABLE" | |
elif avg >= time_unstable: | |
status = "unstable" | |
else: | |
status = "stable" | |
return status | |
def main(): | |
response_list = [] | |
print("Pinging", hostname, ":", host_desc, "\n") | |
print("{} {:<7} {:<7} {}".format("s", "current", "average", "status")) | |
while True: | |
current_time = ping() | |
response_list.append(current_time) | |
response_list = response_list[-amount:] | |
if current_time == -1: | |
s = "M" | |
elif current_time > time_unstable: | |
s = "!" | |
else: | |
s = " " | |
avg = avg_ping(response_list) | |
print("{} {:>7.2f} {:>7.2f} {}".format( | |
s, current_time, avg, ping_status(avg))) | |
sleep(1) | |
if __name__ == "__main__": | |
try: | |
main() | |
except KeyboardInterrupt: | |
print("KeyboardInterrupt") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment