Guest User

Untitled

a guest
Sep 1st, 2025
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.75 KB | None | 0 0
  1. import subprocess
  2. import json
  3. import time
  4. import csv
  5. from datetime import datetime
  6. import logging
  7. import os
  8.  
  9. # Configure logging
  10. logging.basicConfig(
  11. level=logging.DEBUG,
  12. format='%(asctime)s - %(levelname)s - %(message)s',
  13. filename='gsl_speedtest.log',
  14. filemode='w'
  15. )
  16. console = logging.StreamHandler()
  17. console.setLevel(logging.INFO)
  18. logging.getLogger('').addHandler(console)
  19.  
  20. # Dictionary of GSL Networks server IDs and their locations from the provided table
  21. gsl_servers = {
  22. "Amsterdam": 51395,
  23. "Ashburn": 48604,
  24. "Atlanta": 56810,
  25. "Brisbane": 48346,
  26. "Helsinki": 65088,
  27. "Los Angeles": 50081,
  28. "Madrid": 65091,
  29. "Melbourne": 46114,
  30. "New York": 46120,
  31. "Phoenix": 56808,
  32. "Sofia": 65090,
  33. "Sydney": 44735,
  34. "Taipei": 65092,
  35. "Tokyo": 50686,
  36. "Warsaw": 65089
  37. }
  38.  
  39. def run_speedtest(server_id, city):
  40. """Run speedtest.exe for a specific server ID and return results."""
  41. # Get the directory of the script and construct the path to speedtest.exe
  42. script_dir = os.path.dirname(os.path.abspath(__file__))
  43. speedtest_path = os.path.join(script_dir, "speedtest.exe")
  44.  
  45. try:
  46. cmd = [
  47. speedtest_path,
  48. "--accept-license",
  49. "--format=json",
  50. "--server-id", str(server_id)
  51. ]
  52. logging.info(f"Running speedtest for {city} (Server ID: {server_id}) with {speedtest_path}")
  53. process = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=60)
  54. result = json.loads(process.stdout)
  55. ping = result.get("ping", {}).get("latency", None)
  56. download = result.get("download", {}).get("bandwidth", 0) / 125000 # Convert bits/s to Mbps
  57. upload = result.get("upload", {}).get("bandwidth", 0) / 125000 # Convert bits/s to Mbps
  58. logging.info(f"Speedtest results for {city}: Ping={ping}ms, Download={download}Mbps, Upload={upload}Mbps")
  59. return ping, download, upload
  60. except subprocess.CalledProcessError as e:
  61. logging.error(f"Speedtest failed for {city} (ID: {server_id}): {e.stderr}")
  62. return None, None, None
  63. except json.JSONDecodeError as e:
  64. logging.error(f"Failed to parse JSON for {city} (ID: {server_id}): {e}")
  65. return None, None, None
  66. except FileNotFoundError:
  67. logging.error(f"speedtest.exe not found at {speedtest_path}")
  68. return None, None, None
  69. except Exception as e:
  70. logging.error(f"Unexpected error for {city} (ID: {server_id}): {e}")
  71. return None, None, None
  72.  
  73. def get_speedtest_results():
  74. results = []
  75. for city, server_id in gsl_servers.items():
  76. logging.info(f"Starting test for {city} with server ID {server_id}")
  77. print(f"\nSearching for server in {city} (ID: {server_id})...")
  78.  
  79. ping, download, upload = run_speedtest(server_id, city)
  80.  
  81. if ping is None:
  82. logging.warning(f"Skipping test for {city} (ID: {server_id}) due to failure.")
  83. results.append({
  84. 'city': city,
  85. 'ping': None,
  86. 'download': None,
  87. 'upload': None,
  88. 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  89. })
  90. else:
  91. results.append({
  92. 'city': city,
  93. 'ping': ping,
  94. 'download': download,
  95. 'upload': upload,
  96. 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  97. })
  98. time.sleep(3) # Avoid overwhelming servers
  99.  
  100. return results
  101.  
  102. def save_results_to_csv(results, filename="gsl_speedtest_results.csv"):
  103. with open(filename, mode='w', newline='') as file:
  104. writer = csv.DictWriter(file, fieldnames=['city', 'ping', 'download', 'upload', 'timestamp'])
  105. writer.writeheader()
  106. for result in results:
  107. writer.writerow(result)
  108. logging.info(f"Results saved to {filename}")
  109. print(f"\nResults saved to {filename}")
  110.  
  111. def main():
  112. logging.info("Starting speed test against GSL Networks servers...")
  113. print("Starting speed test against GSL Networks servers...")
  114. results = get_speedtest_results()
  115.  
  116. print("\nTest Results:")
  117. print("-------------")
  118. for result in results:
  119. print(f"City: {result['city']}")
  120. print(f"Timestamp: {result['timestamp']}")
  121. if result['ping'] is None:
  122. print("No server found or test failed.")
  123. else:
  124. print(f"Ping: {result['ping']:.2f} ms")
  125. print(f"Download: {result['download']:.2f} Mbps")
  126. print(f"Upload: {result['upload']:.2f} Mbps")
  127. print("-------------")
  128.  
  129. save_results_to_csv(results)
  130.  
  131. if __name__ == "__main__":
  132. main()
Advertisement
Add Comment
Please, Sign In to add comment