树莓派环境下网络吞吐量监测Python方案及API需求问询
Got it, let's get your network throughput monitoring sorted on the Raspberry Pi—since you already have InfluxDB and Grafana in place, this should fit right in. Here are the tools, code, and workflows I recommend:
Recommended Python Libraries & Compatible APIs
These are all pure-Python or ARM-compatible, so they work seamlessly on Raspberry Pi:
speedtest-cli (for public throughput testing)
This is a maintained, pure-Python implementation of speedtest-style functionality. No binary dependencies that might fail on ARM, so it's perfect for Pi. It measures both download and upload speeds, and outputs easily parseable data for your monitoring stack.iperf3-python (for controlled, private throughput testing)
If you have access to a remote server (or can spin up a cheap cloud instance), iperf3 gives you consistent, customizable tests. The Python wrapper lets you automate client-side tests against an iperf3 server—great for getting repeatable data to share with your ISP for compliance.
Python Code Example (Speedtest + InfluxDB Integration)
First, install the required packages:
pip install speedtest-cli influxdb-client
Then create a script (e.g., network_monitor.py) that runs tests at intervals and writes data to InfluxDB:
import time import speedtest from influxdb_client import InfluxDBClient, Point, WritePrecision from influxdb_client.client.write_api import SYNCHRONOUS # Update these with your InfluxDB details INFLUXDB_URL = "http://your-influxdb-ip:8086" INFLUXDB_TOKEN = "your-influxdb-token" INFLUXDB_ORG = "your-org-name" INFLUXDB_BUCKET = "network-monitoring" # Initialize clients st = speedtest.Speedtest() influx_client = InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG) write_api = influx_client.write_api(write_options=SYNCHRONOUS) def run_throughput_test(): try: # Select optimal server (you can hardcode a server ID for consistency) st.get_best_server() # Run tests and convert to Mbps download_speed = st.download() / 1_000_000 upload_speed = st.upload() / 1_000_000 ping = st.results.ping # Create InfluxDB data point point = Point("throughput") \ .tag("device", "raspberry-pi") \ .field("download_mbps", round(download_speed, 2)) \ .field("upload_mbps", round(upload_speed, 2)) \ .field("ping_ms", round(ping, 2)) \ .time(time.time_ns(), WritePrecision.NS) # Write to InfluxDB write_api.write(bucket=INFLUXDB_BUCKET, org=INFLUXDB_ORG, record=point) print(f"Test completed: Down {download_speed:.2f} Mbps, Up {upload_speed:.2f} Mbps, Ping {ping:.2f} ms") except Exception as e: print(f"Test failed: {str(e)}") if __name__ == "__main__": # Run test every 15 minutes (adjust interval as needed) TEST_INTERVAL = 900 while True: run_throughput_test() time.sleep(TEST_INTERVAL)
Iperf3 Alternative Code Snippet
If you prefer more controlled iperf3 tests (better for ISP compliance reports), install the library first:
pip install iperf3
Here's a client test snippet you can integrate with the InfluxDB code above:
import iperf3 def run_iperf_test(): client = iperf3.Client() client.duration = 10 # Test for 10 seconds client.server_hostname = "your-iperf3-server-ip" client.port = 5201 result = client.run() if result.error: print(f"Iperf test failed: {result.error}") return None else: return { "download_mbps": round(result.received_Mbps, 2), "upload_mbps": round(result.sent_Mbps, 2), "ping_ms": round(result.min_rtt, 2) }
Integrating with Grafana
Since you already have Grafana set up:
- Add your InfluxDB as a data source (use the same URL/token/org/bucket from the script)
- Build your dashboard:
- Add a Time Series panel to plot
download_mbpsandupload_mbpsover time - Add Stat panels to show current ping, download, and upload speeds
- Set up alerts to notify you if throughput drops below a threshold (e.g., 80% of your subscribed speed)
- Add a Time Series panel to plot
Bonus: Automate & Maintain
- Make the script run on boot by creating a systemd service file (e.g.,
/etc/systemd/system/network-monitor.service):
Enable it with:[Unit] Description=Network Throughput Monitor After=network.target [Service] User=pi ExecStart=/usr/bin/python3 /home/pi/network_monitor.py Restart=always [Install] WantedBy=multi-user.targetsudo systemctl daemon-reload sudo systemctl enable network-monitor.service sudo systemctl start network-monitor.service - For ISP compliance reports, use Grafana's export feature to generate PDF/PNG charts of your throughput history, or pull raw data from InfluxDB to run your DA/ML analysis on network fluctuations.
内容的提问来源于stack exchange,提问作者Oliver Prislan

