Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import subprocess
- import json
- import time
- import csv
- from datetime import datetime
- import logging
- import os
- # Configure logging
- logging.basicConfig(
- level=logging.DEBUG,
- format='%(asctime)s - %(levelname)s - %(message)s',
- filename='gsl_speedtest.log',
- filemode='w'
- )
- console = logging.StreamHandler()
- console.setLevel(logging.INFO)
- logging.getLogger('').addHandler(console)
- # Dictionary of GSL Networks server IDs and their locations from the provided table
- gsl_servers = {
- "Amsterdam": 51395,
- "Ashburn": 48604,
- "Atlanta": 56810,
- "Brisbane": 48346,
- "Helsinki": 65088,
- "Los Angeles": 50081,
- "Madrid": 65091,
- "Melbourne": 46114,
- "New York": 46120,
- "Phoenix": 56808,
- "Sofia": 65090,
- "Sydney": 44735,
- "Taipei": 65092,
- "Tokyo": 50686,
- "Warsaw": 65089
- }
- def run_speedtest(server_id, city):
- """Run speedtest.exe for a specific server ID and return results."""
- # Get the directory of the script and construct the path to speedtest.exe
- script_dir = os.path.dirname(os.path.abspath(__file__))
- speedtest_path = os.path.join(script_dir, "speedtest.exe")
- try:
- cmd = [
- speedtest_path,
- "--accept-license",
- "--format=json",
- "--server-id", str(server_id)
- ]
- logging.info(f"Running speedtest for {city} (Server ID: {server_id}) with {speedtest_path}")
- process = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=60)
- result = json.loads(process.stdout)
- ping = result.get("ping", {}).get("latency", None)
- download = result.get("download", {}).get("bandwidth", 0) / 125000 # Convert bits/s to Mbps
- upload = result.get("upload", {}).get("bandwidth", 0) / 125000 # Convert bits/s to Mbps
- logging.info(f"Speedtest results for {city}: Ping={ping}ms, Download={download}Mbps, Upload={upload}Mbps")
- return ping, download, upload
- except subprocess.CalledProcessError as e:
- logging.error(f"Speedtest failed for {city} (ID: {server_id}): {e.stderr}")
- return None, None, None
- except json.JSONDecodeError as e:
- logging.error(f"Failed to parse JSON for {city} (ID: {server_id}): {e}")
- return None, None, None
- except FileNotFoundError:
- logging.error(f"speedtest.exe not found at {speedtest_path}")
- return None, None, None
- except Exception as e:
- logging.error(f"Unexpected error for {city} (ID: {server_id}): {e}")
- return None, None, None
- def get_speedtest_results():
- results = []
- for city, server_id in gsl_servers.items():
- logging.info(f"Starting test for {city} with server ID {server_id}")
- print(f"\nSearching for server in {city} (ID: {server_id})...")
- ping, download, upload = run_speedtest(server_id, city)
- if ping is None:
- logging.warning(f"Skipping test for {city} (ID: {server_id}) due to failure.")
- results.append({
- 'city': city,
- 'ping': None,
- 'download': None,
- 'upload': None,
- 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- })
- else:
- results.append({
- 'city': city,
- 'ping': ping,
- 'download': download,
- 'upload': upload,
- 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- })
- time.sleep(3) # Avoid overwhelming servers
- return results
- def save_results_to_csv(results, filename="gsl_speedtest_results.csv"):
- with open(filename, mode='w', newline='') as file:
- writer = csv.DictWriter(file, fieldnames=['city', 'ping', 'download', 'upload', 'timestamp'])
- writer.writeheader()
- for result in results:
- writer.writerow(result)
- logging.info(f"Results saved to {filename}")
- print(f"\nResults saved to {filename}")
- def main():
- logging.info("Starting speed test against GSL Networks servers...")
- print("Starting speed test against GSL Networks servers...")
- results = get_speedtest_results()
- print("\nTest Results:")
- print("-------------")
- for result in results:
- print(f"City: {result['city']}")
- print(f"Timestamp: {result['timestamp']}")
- if result['ping'] is None:
- print("No server found or test failed.")
- else:
- print(f"Ping: {result['ping']:.2f} ms")
- print(f"Download: {result['download']:.2f} Mbps")
- print(f"Upload: {result['upload']:.2f} Mbps")
- print("-------------")
- save_results_to_csv(results)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment