当前位置: 首页 > news >正文

python 检测蜂窝网络,实现掉网自动拨号

ndis

#!/usr/bin/env python3
import subprocess
import time
import redef ping_test(host="8.8.8.8", interface="wwan0", count=4, timeout=5):"""测试通过wwan0接口ping指定主机是否成功返回: True(成功)/False(失败)"""try:print(f"正在通过 {interface} 测试 {host} 连通性...")output = subprocess.check_output(["ping", "-I", interface, "-c", str(count), "-W", str(timeout), host],stderr=subprocess.STDOUT,universal_newlines=True)# 解析ping结果packet_loss = re.search(r"(\d+)% packet loss", output)if packet_loss and int(packet_loss.group(1)) > 50:print(f"⚠️ Ping {host} 丢包率过高: {packet_loss.group(1)}%")return False# 提取并显示延迟统计latency_match = re.search(r"rtt min/avg/max/mdev = ([\d.]+)/([\d.]+)/([\d.]+)/([\d.]+) ms", output)if latency_match:print(f"✅ Ping {host} 成功! 延迟: min={latency_match.group(1)}ms, avg={latency_match.group(2)}ms, max={latency_match.group(3)}ms")else:print(f"✅ Ping {host} 成功!")return Trueexcept subprocess.CalledProcessError as e:error_line = e.output.splitlines()[-1] if e.output else str(e)print(f"❌ Ping {host} 失败: {error_line}")return Falsedef restart_wwan_connection():"""重新初始化wwan0连接"""print("\n🔄 尝试恢复wwan0网络连接...")commands = [["sudo", "/home/pi/simcom-cm"],["sudo", "udhcpc", "-i", "wwan0"]]for cmd in commands:try:print(f"执行: {' '.join(cmd)}")subprocess.run(cmd, check=True, timeout=60)print("执行成功")except subprocess.TimeoutExpired:print("⚠️ 命令执行超时")return Falseexcept subprocess.CalledProcessError as e:print(f"⚠️ 命令执行失败: {e}")return Falseprint("等待网络初始化完成...")time.sleep(15)  # 等待接口稳定return Truedef main():# 配置参数config = {"ping_host": "8.8.8.8",    # 测试用的IP"interface": "wwan0",      # 网络接口"check_interval": 60,      # 正常检查间隔(秒)"retry_interval": 30,      # 失败后重试间隔(秒)"max_retries": 3           # 最大连续重试次数}retry_count = 0print(f"\n📶 开始监控 {config['interface']} 网络连接")print(f"监控目标: {config['ping_host']}")print(f"检查间隔: {config['check_interval']}秒\n")while True:if ping_test(config["ping_host"], config["interface"]):retry_count = 0  # 重置重试计数器time.sleep(config["check_interval"])else:retry_count += 1if retry_count <= config["max_retries"]:print(f"\n尝试恢复连接 ({retry_count}/{config['max_retries']})")if restart_wwan_connection():time.sleep(config["retry_interval"])else:time.sleep(config["retry_interval"] * 2)  # 失败后等待更久else:print(f"⚠️ 已达到最大重试次数 {config['max_retries']},等待下次检查...")retry_count = 0time.sleep(config["check_interval"])if __name__ == "__main__":try:main()except KeyboardInterrupt:print("\n🛑 脚本被用户中断")except Exception as e:print(f"❌ 发生未预期错误: {e}")

RNDIS&&ECM

#!/usr/bin/env python3
import subprocess
import time
import redef ping_test(host="8.8.8.8", interface="usb0", count=4, timeout=5):"""Test ping connectivity to specified host via usb0 interfaceReturns: True(success)/False(failure)"""try:print(f"Testing connectivity to {host} via {interface}...")output = subprocess.check_output(["ping", "-I", interface, "-c", str(count), "-W", str(timeout), host],stderr=subprocess.STDOUT,universal_newlines=True)# Parse ping resultspacket_loss = re.search(r"(\d+)% packet loss", output)if packet_loss and int(packet_loss.group(1)) > 50:print(f"⚠️ High packet loss to {host}: {packet_loss.group(1)}%")return False# Extract and display latency statslatency_match = re.search(r"rtt min/avg/max/mdev = ([\d.]+)/([\d.]+)/([\d.]+)/([\d.]+) ms", output)if latency_match:print(f"✅ Ping {host} successful! Latency: min={latency_match.group(1)}ms, avg={latency_match.group(2)}ms, max={latency_match.group(3)}ms")else:print(f"✅ Ping {host} successful!")return Trueexcept subprocess.CalledProcessError as e:error_line = e.output.splitlines()[-1] if e.output else str(e)print(f"❌ Ping {host} failed: {error_line}")return Falsedef restart_network_connection():"""Attempt to restore usb0 connection"""print("\n🔄 Attempting to restore usb0 network connection...")try:print("Executing: sudo dhclient -v usb0")subprocess.run(["sudo", "dhclient", "-v", "usb0"], check=True, timeout=60)print("Command executed successfully")except subprocess.TimeoutExpired:print("⚠️ Command timed out")return Falseexcept subprocess.CalledProcessError as e:print(f"⚠️ Command failed: {e}")return Falseprint("Waiting for network initialization...")time.sleep(15)  # Wait for interface to stabilizereturn Truedef main():# Configuration parametersconfig = {"ping_host": "8.8.8.8",    # Test IP"interface": "usb0",       # Network interface"check_interval": 60,      # Normal check interval (seconds)"retry_interval": 30,      # Retry interval after failure (seconds)"max_retries": 3           # Maximum consecutive retries}retry_count = 0print(f"\n📶 Starting {config['interface']} network connection monitoring")print(f"Monitoring target: {config['ping_host']}")print(f"Check interval: {config['check_interval']} seconds\n")while True:if ping_test(config["ping_host"], config["interface"]):retry_count = 0  # Reset retry countertime.sleep(config["check_interval"])else:retry_count += 1if retry_count <= config["max_retries"]:print(f"\nAttempting connection recovery ({retry_count}/{config['max_retries']})")if restart_network_connection():time.sleep(config["retry_interval"])else:time.sleep(config["retry_interval"] * 2)  # Wait longer after failureelse:print(f"⚠️ Reached maximum retries {config['max_retries']}, waiting for next check...")retry_count = 0time.sleep(config["check_interval"])if __name__ == "__main__":try:main()except KeyboardInterrupt:print("\n🛑 Script interrupted by user")except Exception as e:print(f"❌ Unexpected error occurred: {e}")

添加到开机自启动(可选)

crontab -e@reboot sleep 10 && export XDG_RUNTIME_DIR=/run/user/1000 && /usr/bin/python3 /home/pi/audio.py >> /home/pi>
http://www.dtcms.com/a/300265.html

相关文章:

  • nacos启动报错:Unable to start embedded Tomcat。
  • ChatIm项目文件上传与获取
  • 配置nodejs
  • 面试150 数据流的中位数
  • 6.数组和字符串
  • 从稀疏数据(CSV)创建非常大的 GeoTIFF(和 WMS)
  • 【时时三省】(C语言基础)返回指针值的函数
  • TRIM功能
  • 《代码随想录》刷题记录
  • 速通python加密之MD5加密
  • Datawhale AI 夏令营:让AI理解列车排期表 Notebook(Baseline拆解)
  • JVM常见工具
  • Java 对象秒变 Map:字段自由伸缩的优雅实现
  • KTO:基于行为经济学的大模型对齐新范式——原理、应用与性能突破
  • 2025测绘程序设计国赛实战 | 基于统计滤波算法的点云去噪
  • 使用binutils工具分析目标文件(贰)
  • U514565 连通块中点的数量
  • 缓存一致性:从单核到异构多核的演进之路
  • HarmonyOS中的PX、 VP、 FP 、LPX、Percentage、Resource 详细区别是什么
  • HCIP--MGRE实验
  • CT、IT、ICT 和 DICT区别
  • Windows卷影复制的增量备份
  • 在VS Code中运行Python:基于Anaconda环境或Python官方环境
  • 人大金仓 kingbase 连接数太多, 清理数据库连接数
  • Go的内存管理和垃圾回收
  • “Datawhale AI夏令营”「结构化数据的用户意图理解和知识问答挑战赛」1
  • 使用Clion开发STM32(Dap调试)
  • 基于华为ENSP的OSPF数据报文保姆级别详解(3)
  • LeetCode——1695. 删除子数组的最大得分
  • TI MSPM0蓝牙串口通信数据包制作