简单使用psutil库来监控并记录局域网内计算机的上传和下载速度到一个CSV文件。现在使用这个示例来创建一个网络速度监控系统,可以更长时间地记录网络速度数据。记录后,我们将数据结果自动上传到远程服务器。
import psutil
import time
import csv
# 创建一个CSV文件来记录网络速度数据
csv_file = "network_speed.csv"
def get_network_speed(interval=1, duration=60):
with open(csv_file, mode='w', newline='') as file:
fieldnames = ['Time', 'Interface', 'Download Speed (KB/s)', 'Upload Speed (KB/s)']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
end_time = time.time() + duration
while time.time() < end_time:
net_info = psutil.net_io_counters(pernic=True)
for interface, data in net_info.items():
if interface != 'lo': # 排除回环接口
download_speed = data.bytes_recv / interval / 1024 # 下载速度(KB/s)
upload_speed = data.bytes_sent / interval / 1024 # 上传速度(KB/s)
current_time = time.strftime("%Y-%m-%d %H:%M:%S")
writer.writerow({'Time': current_time, 'Interface': interface, 'Download Speed (KB/s)': download_speed, 'Upload Speed (KB/s)': upload_speed})
time.sleep(interval)
if __name__ == "__main":
print("开始监控网络速度...")
get_network_speed()
print(f"监控结束,数据已记录到 {csv_file}")
要将测试结果上传到任何其他远程服务器,我们需要与服务器之间建立通信并按照特定的协议发送数据。这通常需要服务器端和客户端代码。首先,你需要确保目标服务器支持接收和处理你要上传的数据。通常,服务器端会提供API或其他接口,以便客户端可以将数据发送给服务器。
下面这段简单的Python示例代码,用于使用HTTP POST方法将速度测试结果上传到服务器:
import requests
# URL 是服务器的接收数据的端点
url = "https://www.os-monitor.com/ "
# 测试结果数据
download_speed = 50.0 # 下载速度(Mbps)
upload_speed = 20.0 # 上传速度(Mbps)
# 将数据组织为JSON
data = {
"download_speed": download_speed,
"upload_speed": upload_speed
}
# 发送POST请求
response = requests.post(url, json=data)
# 检查响应
if response.status_code == 200:
print("数据上传成功")
else:
print("数据上传失败")
本文只是抛砖引玉,实际的上传过程可能更复杂,可能需要身份验证或其他安全措施,具体取决于服务器的要求。你需要与服务器端进行合作,并了解他们提供的API文档或通信协议,以确保数据上传的正确。