powershell 监控, 重启网卡

本文介绍了一个使用Powershell编写的脚本,该脚本用于监控Windows服务器的网络状态,并在检测到网络中断时自动重启指定的网卡。通过Ping测试检查多个IP地址的连通性,实现对外网和内网的监控。

#powershell 监控, 重启网卡

一台Windows服务器,由于负荷较大,偶尔会网络中断,就写了个powershell脚本,监控ip是否通,不通就重启网卡

 

cls
$host.UI.RawUI.WindowTitle = ‘……VM监控……’
$host.UI.RawUI.ForegroundColor='Green'
#version V1.3.9
#t1间隔时间s
$t1=5
$log='C:\Router.log.txt'
#region
$nu=0
$n1="##########"
$n2="监控总次数"
$cq1=0
$cq2=0
$ip1='192.168.0.1'
$ip2='172.16.11.145'
$ip3='172.16.11.8'
#endregion
if(Test-Path $log){}else
    {
    "初始化log"
    echo $n1 >$log
    echo $n2 >>$log
    echo $nu >>$log
    echo $n1 >>$log
    }
while(1 -lt 2)
{
    sleep $t1
    cls
    $log1=Get-Content $log
    $nu=$log1[2]
    $nu=[int]$nu + 1
    #print
    echo $n1
    echo "$($n2):$($nu)"
    echo "监控间隔:$($t1)s"
    echo "重启网卡:$($cq1)"
    echo "重启路由:$($cq2)"
    echo $n1
    #write
    echo $n1 >$log
    echo $n2 >>$log
    echo $nu >>$log
    echo $log1[3..($log1.count-1)] >>$log

    #check
    if ((Get-WmiObject -query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip1'").StatusCode -eq 0)
    {
        "The router is online!"
        #检测内网
        if ((Get-WmiObject -query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip2'").StatusCode -eq 0)
            {  "The Lan is online!" }
            elseif ((Get-WmiObject -query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip3'").StatusCode -eq 0)
            {  "The Lan is online!" }
            else
            {
            "重启内网网卡" 
            $cq1=$cq1 + 1
            echo "重启内网网卡, $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss.ffff')">>$log
            Get-NetAdapter -Name '本地连接' | Restart-NetAdapter
            Get-NetAdapter -Name 'Lan' | Restart-NetAdapter
            sleep 30
            }
    }
    else
    {
      "The router is offline!"
     "重启路由网卡"
     $cq1=$cq1 + 1
     echo "重启路由网卡, $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss.ffff')">>$log
     Get-NetAdapter -Name 'Wan2' | Restart-NetAdapter
     Get-NetAdapter -Name 'Lan2' | Restart-NetAdapter
     sleep 30
     #再次检测
    if ((Get-WmiObject -query "SELECT * FROM Win32_PingStatus WHERE Address = '$ip1'").StatusCode -eq 0)
         { "The route is online!" }
         else
         {
        "重启  router"
        $cq2=$cq2 + 1
        echo "重启  router, $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss.ffff')">>$log
        $vname='ikuai-router'
        Restart-VM $vname -Force
        sleep 100
         }
    }
}
​

 

转载于:https://www.cnblogs.com/elvi/p/7718434.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值