[英]How to enable and disable network connection when connection to interntet is dropped while everything is logged?
我正在尝试创建一个批处理,Powershell(Win8.1)或Python(3.4)中的脚本。 该脚本将每隔15分钟左右循环一次,以测试Internet连接是否仍然有效。 如果连接处于活动状态,则脚本将打印带有时间戳的“通过”并保存到日志文件中。 如果Internet连接中断或断开,则脚本将在记录时间和测试结果时禁用并重新启用网络适配器。 我想我已经缩小了相当可靠的批处理文件的范围。
我遇到的问题是,当我使用具有管理员权限的脚本运行脚本,从而允许执行powershell命令时,日志文件不会更新。 当我运行没有管理员权限的批处理文件时,日志文件会更新,但是powershell命令不起作用。
我还尝试了使用命令行代码代替Powershell命令的相同脚本,我只是觉得Powershell更快:
netsh interface set interface "Ethernet" DISABLED
netsh interface set interface "Ethernet" ENABLED
到目前为止,我的代码:
@setlocal enableextensions enabledelayedexpansion
@echo off
rem Google DNS Most reliable IP for ping testing.
set ip=8.8.8.8
:retest
cls
echo.
echo %TIME%: Testing Internet Connection...
ping -n 1 %ip% | find "TTL"
if not errorlevel 1 set error=Pass
if errorlevel 1 set error=Fail
echo.
echo Time: %TIME% Result: %error%
echo Time: %TIME% Result: %error% >> Server_Restarts.log
echo.
goto %error%
:Pass
echo Retest in 15 minutes..
timeout /T 900 /NOBREAK
goto retest
:Fail
echo Restarting Network..
echo Connection Failed at %TIME%.. >> Server_Restarts.log
timeout /t 5 /nobreak
echo. >> Server_Restarts.log
echo.
echo Restarting Network at Date: %DATE% and Time:%TIME%..
echo Restarting Network at Date: %DATE% and Time:%TIME%.. >> Server_Restarts.log
echo %TIME% Disabling Network Connection..
Powershell.exe Disable-NetAdapter -Name * -Confirm:$false
echo %TIME% Enabling Network Connection..
Powershell.exe Enable-NetAdapter -Name "Ethernet"
echo Network Connection Reset at %TIME%..
echo Network Connection Reset at Date: %DATE% and Time:%TIME%.. >> Server_Restarts.log
echo. >> Server_Restarts.log
timeout /t 5 /nobreak
goto retest
您使用的是相对路径,因此位置可能有所不同。 如果右键单击并使用“以管理员身份运行”,它将文件保存在c:\\windows\\system32\\Server_Restarts.log
。 使用日志文件的绝对路径或将其与批处理文件保存在同一目录中,如下所示:
Time:%TIME%.. >> "%~dp0Server_Restarts.log"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.