如何编写网络重连脚本

wen 实用脚本 30

本文目录导读:

如何编写网络重连脚本

  1. Linux Shell 脚本 - 检测并重连WiFi
  2. Python 脚本 - 跨平台方案
  3. 微信小程序 - 网络重连
  4. 使用说明

Linux Shell 脚本 - 检测并重连WiFi

#!/bin/bash
# 网络重连脚本
NETWORK_NAME="YourWiFiName"
INTERFACE="wlan0"
LOG_FILE="/var/log/network_reconnect.log"
# 检测网络连接函数
check_network() {
    # 尝试ping谷歌DNS
    if ping -c 1 -W 2 8.8.8.8 &> /dev/null; then
        return 0
    else
        return 1
    fi
}
# 重连网络函数
reconnect_network() {
    echo "$(date): 网络断开,尝试重连..." | tee -a $LOG_FILE
    # 方法1: 使用nmcli重连(适用于NetworkManager)
    nmcli dev disconnect $INTERFACE
    sleep 2
    nmcli dev connect $INTERFACE
    nmcli con up id "$NETWORK_NAME"
    # 方法2: 使用ifconfig(备份方案)
    # ifconfig $INTERFACE down
    # sleep 2
    # ifconfig $INTERFACE up
    sleep 5
    if check_network; then
        echo "$(date): 重连成功" | tee -a $LOG_FILE
        return 0
    else
        echo "$(date): 重连失败" | tee -a $LOG_FILE
        return 1
    fi
}
# 主循环
while true; do
    if ! check_network; then
        reconnect_network
    fi
    sleep 30  # 每30秒检测一次
done

Python 脚本 - 跨平台方案

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import subprocess
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('network_reconnect.log'),
        logging.StreamHandler()
    ]
)
class NetworkReconnector:
    def __init__(self):
        self.config = {
            'ping_host': '8.8.8.8',
            'check_interval': 30,  # 检测间隔(秒)
            'max_retries': 3,      # 最大重试次数
            'interface': None      # 网络接口(None表示自动检测)
        }
    def check_connection(self):
        """检测网络连接状态"""
        try:
            # 使用ping检测
            result = subprocess.run(
                ['ping', '-c', '1', '-W', '2', self.config['ping_host']],
                capture_output=True,
                timeout=5
            )
            return result.returncode == 0
        except:
            return False
    def reconnect(self):
        """执行网络重连"""
        system = sys.platform
        if system.startswith('linux'):
            return self._reconnect_linux()
        elif system == 'darwin':  # macOS
            return self._reconnect_macos()
        elif system == 'win32':   # Windows
            return self._reconnect_windows()
        else:
            logging.error(f"不支持的操作系统: {system}")
            return False
    def _reconnect_linux(self):
        """Linux重连逻辑"""
        try:
            # 检测可用的网络接口
            result = subprocess.run(
                ['ip', 'link', 'show', 'up'],
                capture_output=True, text=True
            )
            # 尝试多种重连方法
            methods = [
                # 方法1: 使用NetworkManager
                lambda: subprocess.run(['nmcli', 'networking', 'off'], capture_output=True),
                lambda: subprocess.run(['nmcli', 'networking', 'on'], capture_output=True),
                # 方法2: 重启网络服务
                lambda: subprocess.run(['systemctl', 'restart', 'NetworkManager'], capture_output=True),
                lambda: subprocess.run(['systemctl', 'restart', 'networking'], capture_output=True),
                # 方法3: 使用ifconfig/ip命令
                lambda: subprocess.run(['ip', 'link', 'set', 'down', self.config['interface'] or 'wlan0'], capture_output=True),
                lambda: subprocess.run(['ip', 'link', 'set', 'up', self.config['interface'] or 'wlan0'], capture_output=True)
            ]
            for method in methods:
                try:
                    method()
                    time.sleep(3)
                    if self.check_connection():
                        return True
                except:
                    continue
            return False
        except Exception as e:
            logging.error(f"Linux重连失败: {e}")
            return False
    def _reconnect_macos(self):
        """macOS重连逻辑"""
        try:
            # 获取WiFi接口
            result = subprocess.run(
                ['networksetup', '-listallhardwareports'],
                capture_output=True, text=True
            )
            # 重启WiFi
            subprocess.run(['networksetup', '-setairportpower', 'en0', 'off'], capture_output=True)
            time.sleep(2)
            subprocess.run(['networksetup', '-setairportpower', 'en0', 'on'], capture_output=True)
            return self.check_connection()
        except Exception as e:
            logging.error(f"macOS重连失败: {e}")
            return False
    def _reconnect_windows(self):
        """Windows重连逻辑"""
        try:
            # 禁用再启用网络适配器
            commands = [
                'netsh interface set interface "Wi-Fi" admin=disable',
                'timeout /t 3 /nobreak',
                'netsh interface set interface "Wi-Fi" admin=enable'
            ]
            for cmd in commands:
                subprocess.run(cmd, shell=True, capture_output=True)
            time.sleep(5)
            return self.check_connection()
        except Exception as e:
            logging.error(f"Windows重连失败: {e}")
            return False
    def run(self):
        """运行主循环"""
        logging.info("网络重连服务启动")
        consecutive_failures = 0
        while True:
            try:
                if not self.check_connection():
                    logging.warning("网络连接断开")
                    if consecutive_failures < self.config['max_retries']:
                        retry_count = 1
                        while retry_count <= self.config['max_retries']:
                            logging.info(f"第 {retry_count} 次尝试重连...")
                            if self.reconnect():
                                logging.info("重连成功")
                                consecutive_failures = 0
                                break
                            else:
                                retry_count += 1
                                time.sleep(10)
                        else:
                            consecutive_failures += 1
                            logging.error(f"重连失败,连续失败次数: {consecutive_failures}")
                    else:
                        logging.critical("达到最大重试次数,需要人工干预")
                else:
                    consecutive_failures = 0
                time.sleep(self.config['check_interval'])
            except KeyboardInterrupt:
                logging.info("服务停止")
                break
            except Exception as e:
                logging.error(f"发生错误: {e}")
                time.sleep(60)
if __name__ == "__main__":
    reconnector = NetworkReconnector()
    reconnector.run()

微信小程序 - 网络重连

// 网络重连工具类
class NetworkReconnect {
  constructor(options = {}) {
    this.maxRetries = options.maxRetries || 5;
    this.retryInterval = options.retryInterval || 3000;
    this.currentRetries = 0;
    this.isReconnecting = false;
    this.callbacks = {
      onReconnecting: null,
      onReconnected: null,
      onFailed: null
    };
  }
  // 检测网络状态
  checkNetwork() {
    return new Promise((resolve) => {
      wx.getNetworkType({
        success: (res) => {
          resolve(res.networkType !== 'none');
        },
        fail: () => {
          resolve(false);
        }
      });
    });
  }
  // 重新连接网络
  async reconnect() {
    if (this.isReconnecting) return;
    this.isReconnecting = true;
    this.currentRetries = 0;
    return new Promise(async (resolve) => {
      const tryReconnect = async () => {
        if (this.currentRetries >= this.maxRetries) {
          this.isReconnecting = false;
          if (this.callbacks.onFailed) {
            this.callbacks.onFailed();
          }
          resolve(false);
          return;
        }
        this.currentRetries++;
        if (this.callbacks.onReconnecting) {
          this.callbacks.onReconnecting(this.currentRetries);
        }
        // 尝试打开系统设置
        wx.showModal({
          title: '网络连接失败',
          content: `请检查网络设置,是否前往设置?(第${this.currentRetries}次尝试)`,
          success: async (res) => {
            if (res.confirm) {
              wx.openSetting({
                success: async (settingResult) => {
                  // 检查设置后重新检测网络
                  const isConnected = await this.checkNetwork();
                  if (isConnected) {
                    this.isReconnecting = false;
                    if (this.callbacks.onReconnected) {
                      this.callbacks.onReconnected();
                    }
                    resolve(true);
                  } else {
                    // 继续尝试
                    setTimeout(tryReconnect, this.retryInterval);
                  }
                }
              });
            } else {
              // 用户取消,继续尝试
              setTimeout(tryReconnect, this.retryInterval);
            }
          }
        });
      };
      tryReconnect();
    });
  }
  // 设置回调
  setCallbacks(callbacks) {
    this.callbacks = { ...this.callbacks, ...callbacks };
  }
  // 监听网络状态变化
  startNetworkMonitor() {
    wx.onNetworkStatusChange((res) => {
      if (res.isConnected) {
        // 网络状态恢复
        this.currentRetries = 0;
        this.isReconnecting = false;
      } else {
        // 网络断开,尝试重连
        this.reconnect();
      }
    });
  }
}
// 使用示例
const networkReconnect = new NetworkReconnect({
  maxRetries: 3,
  retryInterval: 5000
});
networkReconnect.setCallbacks({
  onReconnecting: (retryCount) => {
    console.log(`正在重连,第${retryCount}次尝试`);
    wx.showToast({
      title: '正在重连...',
      icon: 'loading',
      duration: 5000
    });
  },
  onReconnected: () => {
    console.log('网络重连成功');
    wx.showToast({
      title: '网络已恢复',
      icon: 'success'
    });
  },
  onFailed: () => {
    console.log('网络重连失败');
    wx.showToast({
      title: '网络重连失败',
      icon: 'none'
    });
  }
});
// 启动网络监控
networkReconnect.startNetworkMonitor();

使用说明

Linux Shell 脚本

  • 保存为 network_reconnect.sh
  • 添加执行权限: chmod +x network_reconnect.sh
  • 运行: ./network_reconnect.sh &

Python 脚本

  • 需要 Python 3.x 环境
  • 保存为 network_reconnect.py
  • 运行: python3 network_reconnect.py

配置建议

根据实际需求调整以下参数:

  • check_interval: 检测间隔时间
  • max_retries: 最大重试次数
  • ping_host: 用于检测的服务器地址
  • interface: 网络接口名称

注意事项

  • Windows 系统可能需要管理员权限
  • Linux 系统可能需要 sudo 权限
  • 建议设置日志记录以便排查问题
  • 在生产环境中使用时,请根据实际网络环境调整参数

选择适合您系统的脚本,并根据实际需求进行相应调整。

抱歉,评论功能暂时关闭!