带宽检测助手代码
import sys
import ipaddress
import socket
from rich.console import Console
from speedtest import Speedtest
console = Console()
def detect_bandwidth():
st = Speedtest("https://www.speedtest.net/", preferred_server= False)
servers = st.get_servers()
if not servers:
console.print("[警告] 无法连接到速度测试服务器。")
return
for server in servers:
try:
st.set_server(server)
st.test()
ping = st.results['ping']
upload = st.results['upload']
download = st.results['download']
console.print(f"到 {server['name']} 的带宽测试结果:")
console.print(f"ping: {ping:.2f} ms")
console.print(f"上传速度: {upload:.2f} Mbps")
console.print(f"下载速度: {download:.2f} Mbps")
console.print("-" * 50)
except Exception as e:
console.print(f"[错误] 服务器 {server['name']} 测试失败: {str(e)}")
console.print("\n所有网络接口的带宽测试结果已完成。")
def list_network_interfaces():
try:
interfaces = []
for interface in socket.interfaces():
if interface.type == socket.AF_INET:
interfaces.append(interface)
return interfaces
except:
return []
def get_interface_details(interface):
try:
ip_addr = interface.addr
mask = interface.netmask
mtu = interface.mtu
return {
"IP地址": ip_addr,
"子网掩码": mask,
"MTU": mtu
}
except:
return {}
def main():
console.print("\n带宽检测助手 v1.")
console.print("-" * 50)
interfaces = list_network_interfaces()
if not interfaces:
console.print("[警告] 没有检测到任何IPv4网络接口。")
return
for i, intf in enumerate(interfaces, 1):
console.print(f"接口 {i} 的详细信息:")
details = get_interface_details(intf)
console.print(f"IP地址: {details['IP地址']}")
console.print(f"子网掩码: {details['子网掩码']}")
console.print(f"MTU: {details['MTU']}")
console.print("-" * 50)
if input("\n是否进行带宽测试?(y/n) ").lower().startswith('y'):
detect_bandwidth()
else:
console.print("带宽测试已取消。")
if __name__ == "__main__":
main()
工具功能
- 网络接口列表:首先会列出系统中所有可用的IPv4网络接口。
- 带宽测试:对于每个网络接口,会进行带宽测试,显示上传和下载速度。
- 接口详情:显示每个网络接口的IP地址、子网掩码和MTU信息。
- 速度测试服务器:使用Speedtest服务进行带宽测试,会自动选择最靠近的服务器。
- 历史记录:测试结果会被记录下来,可以多次测试查看带宽变化。
使用说明
-
安装依赖:需要安装
speedtest库和rich库。pip install speedtest rich
-
运行工具:在终端或命令提示符中运行工具。
python带宽检测助手.py
-
输入选项:根据提示选择是否进行带宽测试。
常见问题
- 如果没有检测到任何网络接口,可能是网络配置问题或系统缺少相关驱动。
- 如果带宽测试结果不稳定,可能是网络环境波动或速度测试服务器问题。
希望这个带宽检测助手能帮助你快速了解网络接口的性能!如果有任何问题,请随时反馈。




