Skip to content

Instantly share code, notes, and snippets.

@waleedahmad
Last active March 10, 2018 10:42
Show Gist options
  • Save waleedahmad/5a53fab127d433e26d1e676dbdc74a06 to your computer and use it in GitHub Desktop.
Save waleedahmad/5a53fab127d433e26d1e676dbdc74a06 to your computer and use it in GitHub Desktop.
Python Ping test script with multiple hosts support and configurable delay time.
import sys
import json
import time
import datetime
import subprocess
import threading
from urllib.request import urlopen
threads = []
hits = 0
misses = 0
# delays between ping requests
timeout = 0
# ping servers
hosts = [
['Europe East 1', 'vie.valve.net'],
['Europe East 2', '185.25.182.1'],
['Europe West 1', 'lux.valve.net'],
['Europe West 2', '146.66.158.1'],
['SE Asia 1', 'sgp-1.valve.net'],
['SE Asia 2', 'sgp-2.valve.net'],
['Dubai', 'dxb.valve.net'],
]
def current_timestamp():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def log_time_out(log_file, message):
with open(log_file + '.txt', "a") as file:
file.write(message + '\n')
def get_ip_address():
return urlopen("http://ip.42.pl/raw").read().decode('UTF-8')
def get_isp_details(ip):
return urlopen("https://ipinfo.io/"+ip+"/json").read().rstrip().decode('UTF-8')
def show_isp_info(ip):
print('**** ISP Details ***')
print(json.dumps(json.loads(get_isp_details(ip)), indent=4, sort_keys=True))
def display_hosts(hosts):
print('Testing Servers')
for host in hosts:
print(host)
def ping(hostname):
p = subprocess.Popen('ping -n 1 ' + hostname, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
status = p.stdout.read().rstrip().decode('UTF-8').splitlines()[2]
if status.startswith('Request timed out.'):
return False
else:
return True
def test_server(server):
while True:
if not ping(host[1]):
log_time_out(server[0] + '_' + server[1], current_timestamp() + ' : Request Timeout')
print(current_timestamp(), ' : Request Timeout - ', server[1])
sys.stdout.flush()
time.sleep(timeout)
print('Start Time : '+ current_timestamp())
show_isp_info(get_ip_address())
display_hosts(hosts)
for host in hosts:
t = threading.Thread(target=test_server, args=(host,))
threads.append(t)
t.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment