定时重新拨号的脚本怎么写

wen 实用脚本 1

本文目录导读:

定时重新拨号的脚本怎么写

  1. 场景一:Linux 服务器/路由器 (使用 PPPoE 拨号)
  2. 场景二:Windows 操作系统
  3. 场景三:使用 Python 脚本 (跨平台)
  4. 重要提示

下面为你提供几种不同环境下的定时重新拨号脚本,你可以根据你的操作系统(Windows、Linux)和场景(路由器、服务器、个人电脑)选择合适的方法。

Linux 服务器/路由器 (使用 PPPoE 拨号)

这是最常见的场景,通常用于宽带的自动重连。

方案:使用 pppoe-stop + pppoe-start + cron

  1. 创建重拨脚本 (/usr/local/bin/reconnect.sh)

    #!/bin/bash
    # 路径可能因发行版而异,常见的是 pppoe-stop 和 pppoe-start
    # 或者使用 ifdown / ifup
    # 请根据你的拨号接口名修改 (eth0, ppp0, 或 wan)
    echo "开始重新拨号:$(date)"
    # 方法1: 使用 pppoe 命令 (适用于 rp-pppoe)
    # sudo /usr/sbin/pppoe-stop
    # sleep 3
    # sudo /usr/sbin/pppoe-start
    # 方法2: 使用 ifupdown 工具 (更推荐)
    # 假设你的拨号接口在 /etc/network/interfaces 中定义为 dsl-provider
    sudo ifdown dsl-provider
    sleep 5
    sudo ifup dsl-provider
    # 方法3: 使用 systemd (如果使用 netctl 或 systemd-networkd)
    # sudo systemctl restart netctl@dsl-provider
    echo "重拨完成:$(date)"
    # 可选:检查是否成功
    if ping -c 2 -W 2 114.114.114.114 > /dev/null 2>&1; then
        echo "网络连通正常"
    else
        echo "警告:重拨后网络可能未连通"
    fi
  2. 赋予执行权限

    chmod +x /usr/local/bin/reconnect.sh
  3. 创建定时任务 (crontab)

    使用 crontab -e 命令,添加一行(例如每天凌晨3点重拨):

    0 3 * * * /usr/local/bin/reconnect.sh >> /var/log/reconnect.log 2>&1

    关于时间的解释:分 时 日 月 周

    • */30 * * * * :每30分钟执行一次
    • 0 */6 * * * :每6小时执行一次

方案:使用 expect 脚本(如果PPPoE需要交互式密码)

如果你的拨号程序需要交互式输入用户名密码,可以使用 expect

  1. 安装 expect

    # Debian/Ubuntu
    sudo apt-get install expect -y
    # CentOS/RHEL
    sudo yum install expect -y
  2. 创建自动拨号脚本

    #!/usr/bin/expect -f
    set timeout 30
    set user "your_username"
    set password "your_password"
    spawn pppoe-start
    expect "username:"
    send "$user\r"
    expect "password:"
    send "$password\r"
    expect eof

Windows 操作系统

方案:使用 PowerShell 脚本 + 任务计划程序

  1. 创建 PowerShell 脚本 (Reconnect.ps1)

    # 定义你的拨号连接名称 (在 控制面板\网络和共享中心 中看到的名称)
    $connectionName = "宽带连接"
    Write-Output "开始断开连接:$(Get-Date)"
    # 断开连接
    rasdial $connectionName /disconnect
    Start-Sleep -Seconds 10
    Write-Output "开始重新拨号:$(Get-Date)"
    # 重新拨号 (需要用户名和密码)
    rasdial $connectionName "your_username" "your_password"
    Write-Output "重拨完成:$(Get-Date)"
    # 简单的网络连通性测试
    if (Test-Connection -ComputerName "114.114.114.114" -Count 2 -Quiet) {
        Write-Output "网络连通成功"
    } else {
        Write-Output "警告:重拨后网络可能未连通"
    }

    注意:rasdial 需要管理员权限才能执行断开操作。

  2. 设置任务计划程序

    • 打开 taskschd.msc
    • 创建基本任务
    • 触发器:选择每天、每小时或根据你的需要设置
    • 操作:启动程序
      • 程序或脚本:Powershell.exe
      • 添加参数:-File "C:\路径\你的脚本\Reconnect.ps1"
    • 勾选“使用最高权限运行”

使用 Python 脚本 (跨平台)

如果你希望有更灵活的检查逻辑、日志记录或断线检测,Python 是个好选择。

  1. 安装依赖

    pip install requests schedule
  2. 创建 Python 脚本 (auto_reconnect.py)

    import os
    import time
    import subprocess
    import platform
    import requests
    import schedule
    # ===== 配置区域 =====
    # 你的拨号信息
    CONNECTION_NAME = "宽带连接"  # Windows 下用
    USERNAME = "your_username"
    PASSWORD = "your_password"
    # 检测间隔(秒)
    CHECK_INTERVAL = 60  
    # ping 失败,等待多少秒再重拨
    WAIT_BEFORE_RECONNECT = 10  
    # ===== 核心函数 =====
    def is_connected():
        """检测网络是否连通"""
        try:
            # 尝试访问一个稳定快速的网站
            response = requests.get("http://connectivitycheck.gstatic.com/generate_204", timeout=10)
            return response.status_code == 204
        except requests.exceptions.RequestException:
            return False
    def reconnect():
        """执行重拨操作"""
        system = platform.system()
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 开始执行重拨...")
        if system == "Windows":
            # 断开连接
            subprocess.run(["rasdial", CONNECTION_NAME, "/disconnect"], capture_output=True)
            time.sleep(WAIT_BEFORE_RECONNECT)
            # 重新连接
            result = subprocess.run(["rasdial", CONNECTION_NAME, USERNAME, PASSWORD], capture_output=True, text=True)
            if result.returncode == 0:
                print("Windows 重拨成功")
            else:
                print(f"Windows 重拨失败: {result.stderr}")
        elif system == "Linux":
            # Linux 下执行 pppoe-stop/start 或 ifdown/ifup
            # 这里是个示例,你需要根据你的实际配置修改
            os.system("sudo ifdown dsl-provider")
            time.sleep(WAIT_BEFORE_RECONNECT)
            os.system("sudo ifup dsl-provider")
            print("Linux 重拨执行完成")
        time.sleep(10)  # 等待网络稳定
    def check_and_reconnect():
        """检查网络状态并决定是否重拨"""
        if not is_connected():
            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 检测到网络断开,准备重拨...")
            reconnect()
            if is_connected():
                print("重拨后网络已恢复")
            else:
                print("重拨后网络仍未恢复,将在下一次检查时再次尝试")
        else:
            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 网络正常")
    # ===== 主程序 =====
    if __name__ == "__main__":
        print("自动重拨脚本启动...")
        # 立即执行一次检查
        check_and_reconnect()
        # 设置定时任务:每 CHECK_INTERVAL 秒执行一次
        schedule.every(CHECK_INTERVAL).seconds.do(check_and_reconnect)
        while True:
            schedule.run_pending()
            time.sleep(1)

重要提示

  1. 权限问题

    • Linux 下 ifdown/ifup 通常需要 root 权限,建议将脚本所有者设为 root 并设置 setuid,或者使用 sudo 执行。
    • Windows 下 rasdial 的断开操作需要管理员权限。
  2. 安全检查:如果重拨过于频繁,运营商可能会认为你的线路异常而触发风控,建议:

    • 设定合理的间隔(例如至少1小时以上)
    • 最好先检测网络是否真的断开,再执行重拨
  3. 日志记录:建议将脚本的输出重定向到一个日志文件,方便排查问题。

  4. 生产环境:如果是关键业务服务器,建议使用更健壮的方案,systemd.timer 或专业的监控工具,并配合邮件告警。

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