场景: 买了一块pcie转无线的网卡,使用云电脑的时候频繁出现重新连接,导致体验很差,测一测是不是自己的网卡导致的问题。
下面是py代码
import os import platform import subprocess import time from datetime import datetime # 配置参数 TARGET = "8.8.8.8" # 监测目标(IP/域名) CHECK_INTERVAL = 5 # 监测间隔(秒) LOG_FILE = "network_log.txt" # 日志文件路径 def ping(target): """执行 Ping 测试,返回是否成功(隐藏详细输出)""" param = "-n 1" if platform.system().lower() == "windows" else "-c 1" command = f"ping {param} {target}" # 屏蔽 Ping 的输出(Windows 和 Linux/macOS 兼容) with open(os.devnull, 'w') as devnull: response = subprocess.call(command, stdout=devnull, stderr=devnull) return response == 0 def beep(): """触发系统蜂鸣声(Windows/Linux/macOS 兼容)""" try: if platform.system() == "Windows": import winsound winsound.Beep(1000, 500) # 频率 1000Hz,持续 500ms else: print("\a") # Linux/macOS 终端响铃 except: pass def log_event(message): """记录事件到日志文件""" timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") log_line = f"[{timestamp}] {message}\n" with open(LOG_FILE, "a") as f: f.write(log_line) def main(): log_event("=== network check start ===") last_status = None try: while True: is_online = ping(TARGET) current_time = datetime.now().strftime("%H:%M:%S") if is_online: status = "在线" if last_status == "离线": log_event("network restart!") else: status = "离线" beep() # 断网报警 if last_status != "离线": log_event("network close!") # 动态刷新控制台输出(一行显示) print(f"\r当前状态: {status} | 检测时间: {current_time}", end="", flush=True) last_status = status time.sleep(CHECK_INTERVAL) except KeyboardInterrupt: log_event("=== stop check ===") print("\n监测已停止。日志已保存至:", LOG_FILE) if __name__ == "__main__": main()
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...