当前位置: 首页 > 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.xdnf.cn/news/1192321.html

相关文章:

  • 自定义定时任务功能详解
  • SGLang 核心技术详解
  • GO 从入门到精通2
  • TCP如何解决网络切换问题
  • 简单实现支付密码的页面及输入效果
  • @PathVariable与@RequestParam的区别
  • Zama+OpenZeppelin:将机密智能合约带入 DeFi 和数字资产领域
  • 拒绝SQL恐惧:用Python+pyqt打造任意Excel数据库查询系统
  • 【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 热词数量分析日期统计功能实现
  • 【数据结构】二叉树初阶详解(二):实现逻辑与代码拆解(超详版)
  • STL——vector
  • [Linux入门] 初学者入门:Linux DNS 域名解析服务详解
  • React入门学习——指北指南(第四节)
  • 雨雪雾冰全预警:交通气象站为出行安全筑起“隐形防护网”
  • 零基础学后端-PHP语言(第二期-PHP基础语法)(通过php内置服务器运行php文件)
  • 力扣112. 路径总和
  • GIS地理信息系统建设:高精度3D建模
  • 【愚公系列】《MIoT.VC》003-构建基本仿真工作站(组件的属性、行为、视频展示)
  • 基于匿名管道的多进程任务池实现与FD泄漏解决方案
  • 智慧水库管理平台数据清洗实施方案
  • C++对象模型
  • linux练习题
  • linux内核电源管理
  • JavaWeb(苍穹外卖)--学习笔记11(Filter(过滤器) 和 Interceptor(拦截器))
  • JavaScript中.splice()的用法
  • 从零开始大模型之编码注意力机制
  • HTML5 Canvas 绘制圆弧效果
  • 适用于5V/12V低输入的负载点电源应用20V/6A单片式双通道同步降压调整器
  • 面试150 IPO
  • C#其他知识点