Skip to content

Instantly share code, notes, and snippets.

@ShailMurtaza
Last active February 15, 2026 18:16
Show Gist options
  • Select an option

  • Save ShailMurtaza/ebf8eaaebc34802725562f57ad49d186 to your computer and use it in GitHub Desktop.

Select an option

Save ShailMurtaza/ebf8eaaebc34802725562f57ad49d186 to your computer and use it in GitHub Desktop.
This Python Script will display host server latency and packet loss
from ping3 import ping
from concurrent.futures import ThreadPoolExecutor, as_completed
import tabulate
from time import sleep, time
from os import system
tabulate.PRESERVE_WHITESPACE = True
def get_server():
with open("servers.txt", "r") as r:
data = r.read()
data = data.strip().split("\n")
data = [x.split(" ") for x in data]
return data
def ping_host(host):
attempts = 3
success = 0
for i in range(attempts):
res = ping(host, unit='ms')
if res:
success += 1
packet_loss = (attempts - success) / attempts * 100
return (res, packet_loss)
def ping_list(servers):
results = [None] * len(servers)
with ThreadPoolExecutor(max_workers=30) as executor:
future_map = {
executor.submit(ping_host, host): i
for i, (_, host) in enumerate(servers)
}
for future in as_completed(future_map):
index = future_map[future]
res, packet_loss = future.result()
name = servers[index][0]
if res:
results[index] = (name, f"{res:.2f} ms", f"{packet_loss:.2f}%")
else:
results[index] = (name, "!!!!", f"{packet_loss:.2f}%")
return tabulate.tabulate(
results,
headers=("Host", "Ping", "Packet Loss"),
tablefmt="rounded_outline"
)
iterations = 0
servers = get_server()
while True:
prev_time = time()
table = ping_list(servers)
new_time = time()
iterations += 1
system("cls")
print(f"{iterations} | {new_time-prev_time:.2f}s")
print(table)
sleep(0.5)
@ShailMurtaza
Copy link
Author

ShailMurtaza commented Oct 25, 2025

3rd Revision

Replaced dictionary with list for jobs to print them in the same order as written in server.txt file

@ShailMurtaza
Copy link
Author

4th Revision

Resolved Bug.
Display hostname as same as result pings. as_completed will return results which completed first.

@ShailMurtaza
Copy link
Author

5th Revision

Feature
Display results in same order as provided in text file of servers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment