本文目录导读:

我来为您提供一个自动检查并恢复网络的脚本方案,这里提供几个不同场景的版本:
Windows 批处理脚本
@echo off网络自动检测与恢复工具
color 0A
:start
cls
echo ========================================
echo 网络自动检测与恢复工具
echo ========================================
echo 正在检测网络连接...
echo.
ping -n 3 8.8.8.8 >nul 2>&1
if %errorlevel% equ 0 (
echo [成功] 网络连接正常
timeout /t 60 /nobreak >nul
goto start
) else (
echo [失败] 网络连接异常,尝试恢复...
goto repair
)
:repair
echo.
echo 步骤1: 释放IP地址...
ipconfig /release >nul
timeout /t 2 /nobreak >nul
echo 步骤2: 更新IP地址...
ipconfig /renew >nul
timeout /t 5 /nobreak >nul
echo 步骤3: 刷新DNS缓存...
ipconfig /flushdns >nul
echo 步骤4: 重置网络栈...
netsh winsock reset >nul
netsh int ip reset >nul
echo 步骤5: 重置网络适配器...
wmic path win32_networkadapter where "NetEnabled=true" call disable >nul
timeout /t 3 /nobreak >nul
wmic path win32_networkadapter where "NetEnabled=true" call enable >nul
echo.
echo 等待网络恢复...
timeout /t 10 /nobreak >nul
echo.
echo 再次检测网络...
ping -n 3 8.8.8.8 >nul 2>&1
if %errorlevel% equ 0 (
echo [成功] 网络已恢复!
) else (
echo [失败] 网络恢复失败,请检查硬件连接
echo 尝试备用DNS...
netsh interface ip set dns "以太网" static 114.114.114.114
netsh interface ip add dns "以太网" 223.5.5.5 index=2
)
echo.
echo 按任意键返回检测循环...
pause >nul
goto start
Linux Shell 脚本
#!/bin/bash
# 网络自动检测与恢复脚本
LOG_FILE="/var/log/network_monitor.log"
CHECK_INTERVAL=60 # 检测间隔(秒)
TARGETS=("8.8.8.8" "114.114.114.114" "223.5.5.5")
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
check_network() {
for target in "${TARGETS[@]}"; do
if ping -c 2 -W 3 "$target" > /dev/null 2>&1; then
return 0
fi
done
return 1
}
repair_network() {
log_message "开始网络恢复..."
# 重启网络服务
log_message "重启网络服务..."
if systemctl restart network 2>/dev/null || systemctl restart NetworkManager 2>/dev/null; then
sleep 5
fi
# 重置网络接口
log_message "重置网络接口..."
for interface in $(ip link show | grep -oP '(?<=: ).*?(?=:)' | grep -v lo); do
ifconfig "$interface" down
sleep 2
ifconfig "$interface" up
done
# 刷新DNS缓存
if command -v systemd-resolve &> /dev/null; then
systemd-resolve --flush-caches
elif command -v nscd &> /dev/null; then
systemctl restart nscd
fi
# 重新获取IP
dhclient -r
dhclient
sleep 10
}
# 主循环
while true; do
if check_network; then
log_message "网络连接正常"
else
log_message "网络连接异常"
repair_network
if check_network; then
log_message "网络恢复成功"
else
log_message "网络恢复失败,需要人工干预"
# 发送告警(可选)
# mail -s "网络故障告警" admin@example.com < /var/log/network_monitor.log
fi
fi
sleep "$CHECK_INTERVAL"
done
Python 跨平台脚本
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import subprocess
import platform
import socket
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('network_monitor.log'),
logging.StreamHandler()
]
)
class NetworkMonitor:
def __init__(self):
self.os_type = platform.system()
self.check_targets = ['8.8.8.8', '114.114.114.114', '223.5.5.5']
self.check_interval = 60 # 检测间隔(秒)
def ping(self, host):
"""Ping检测"""
param = '-n' if self.os_type == 'Windows' else '-c'
command = ['ping', param, '3', '-W', '3', host]
try:
output = subprocess.run(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=10
)
return output.returncode == 0
except subprocess.TimeoutExpired:
return False
except Exception as e:
logging.error(f"Ping错误: {e}")
return False
def check_network(self):
"""检查网络连接"""
for target in self.check_targets:
if self.ping(target):
return True
return False
def windows_repair(self):
"""Windows网络修复"""
logging.info("执行Windows网络修复...")
commands = [
'ipconfig /release',
'ipconfig /renew',
'ipconfig /flushdns',
'netsh winsock reset',
'netsh int ip reset'
]
for cmd in commands:
try:
subprocess.run(cmd, shell=True, check=False)
time.sleep(2)
except Exception as e:
logging.error(f"执行命令失败 {cmd}: {e}")
# 重启网络适配器
try:
import wmi
c = wmi.WMI()
for nic in c.Win32_NetworkAdapter(NetEnabled=True):
if '以太网' in nic.Name or 'Wi-Fi' in nic.Name:
nic.Disable()
time.sleep(5)
nic.Enable()
except:
# 备用方法:使用netsh
subprocess.run('netsh interface set interface "以太网" disable', shell=True)
time.sleep(3)
subprocess.run('netsh interface set interface "以太网" enable', shell=True)
time.sleep(5)
def linux_repair(self):
"""Linux网络修复"""
logging.info("执行Linux网络修复...")
# 重启网络服务
services = ['network', 'NetworkManager', 'systemd-networkd']
for service in services:
subprocess.run(['systemctl', 'restart', service],
capture_output=True, timeout=30)
# 重置网络接口
try:
interfaces = subprocess.run(
['ip', 'link', 'show'],
capture_output=True,
text=True
)
for line in interfaces.stdout.split('\n'):
if ': ' in line and 'lo:' not in line:
iface = line.split(': ')[1].split(':')[0].strip()
subprocess.run(['ip', 'link', 'set', iface, 'down'])
time.sleep(2)
subprocess.run(['ip', 'link', 'set', iface, 'up'])
except Exception as e:
logging.error(f"重置网络接口失败: {e}")
# 刷新DNS
subprocess.run(['systemd-resolve', '--flush-caches'], capture_output=True)
# 重新获取IP
subprocess.run(['dhclient', '-r'], capture_output=True)
subprocess.run(['dhclient'], capture_output=True)
def repair_network(self):
"""执行网络修复"""
try:
if self.os_type == 'Windows':
self.windows_repair()
else:
self.linux_repair()
# 等待网络恢复
time.sleep(15)
except Exception as e:
logging.error(f"网络修复过程出错: {e}")
def run(self):
"""主运行循环"""
logging.info(f"网络监控工具启动 - 操作系统: {self.os_type}")
while True:
try:
if self.check_network():
logging.info("网络连接正常")
else:
logging.warning("网络连接异常,开始修复...")
self.repair_network()
if self.check_network():
logging.info("网络修复成功")
else:
logging.error("网络修复失败,需要人工干预")
# 尝试备用DNS
if self.os_type == 'Windows':
subprocess.run(
'netsh interface ip set dns "以太网" static 8.8.8.8',
shell=True
)
except KeyboardInterrupt:
logging.info("用户中断,程序退出")
sys.exit(0)
except Exception as e:
logging.error(f"监控过程出错: {e}")
time.sleep(self.check_interval)
if __name__ == "__main__":
monitor = NetworkMonitor()
monitor.run()
配置为系统服务
Windows 计划任务配置:
schtasks /create /tn "NetworkMonitor" /tr "C:\path\network_monitor.bat" /sc minute /mo 5
Linux 系统服务配置 (systemd):
[Unit] Description=Network Monitor After=network.target [Service] ExecStart=/usr/local/bin/network_monitor.sh Restart=always RestartSec=10 [Install] WantedBy=multi-user.target
使用说明
- Windows用户:将批处理脚本保存为
network_monitor.bat,以管理员身份运行 - Linux用户:将Shell脚本保存为
network_monitor.sh,给予执行权限chmod +x network_monitor.sh,以root运行 - Python脚本:需要安装Python3及所需依赖包,可根据需要修改检测目标和间隔时间
脚本会自动循环检测网络,并在发现异常时自动执行一系列恢复操作,请根据实际网络环境调整检测目标和恢复策略。