Example: Internet Speed Tacker
Prerequisites
sudo apt install speedtest-cli
internet_speed_tracker.py
#!/usr/bin/env python3
import subprocess
import csv
import os
from datetime import datetime
#--------------CONFIGURATIONs--------------
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_FILE = os.path.join(BASE_DIR, "speed_log.csv")
def run_speed_test():
try:
# Run speedtest in simple mode
result = subprocess.check_output(["speedtest-cli", "--simple"]).decode("utf-8")
# These settings parse the text. For example: Ping: 20 ms, Download: 50.5 Mbit/s, etc
lines = result.split('\n')
ping = lines[0].split()[1]
download = lines[1].split()[1]
upload = lines[2].split()[1]
return ping, download, upload
#These settings keep Speedtest from crashing by logging zeroes when the internet is totally down
except Exception:
return "0", "0", "0"
def main():
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
ping, download, upload = run_speed_test()
# Check if file exists to add headers if it doesn't
file_exists = os.path.isfile(LOG_FILE)
with open(LOG_FILE, mode='a', newline='') as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["Timestamp", "Ping (ms)", "Download (Mbit/s)", "Upload (Mbit/s)"])
writer.writerow([timestamp, ping, download, upload])
if __name__ == "__main__":
main()
Configure systemd
/etc/systemd/system/internet-speed-tracker.service
[Service]
ExecStart=/usr/bin/python3 "home/alang/internet_speed_tracker.py"
User=alang
/etc/systemd/system/internet-speed-tracker.timer
[Timer]
OnBootSec=5min
OnUnitActiveSec=2min
Persistent=true
[Install]
WantedBy=timers.target
Start the service
sudo systemctl daemon-reload
sudo systemctl enable --now internet-speed-tracker.timer
No comments to display
No comments to display