Vbs实现监测断网就关机的实现代码
受一个朋友委托,编写一段vbs代码实现断网就强行关闭计算机的功能,他说为学生机房上课时使用,上课时总有学生想脱离老师的监视,为此,会拔掉网线或者禁用网卡,所以,弄个vbs脚本检测网卡状态,如果断网马上强行关机。
Dim objWMIService,objShellSet objWMIService = Getobject("winmgmts:\\.\root\cimv2")Set objShell = CreateObject("WScript.Shell")'实现实时监测do while trueDim objNetworks,objNetworkSet objNetworks = objWMIService.execQuery("Select * From Win32_NetworkAdapter where NetConnectionID='本地连接'")For Each objNetwork In objNetworks if objNetwork.NetConnectionStatus 2 then 'objShell.run "shutdown -s -f -t 30 -c " chr(34) "由于计算机网络断开,机器即将关闭" chr(34) msgbox "网络已断开" exit for end ifNextset objNetworks=nothing'延时10秒WScript.sleep 1000*10Loop
注:方法一是通过检测网卡的状态来进行相应的操作。
strIP="192.168.1.1"'实时监测do while trueSet objShell = CreateObject("WScript.Shell")If Not IsOnline_1(strIP) Then objShell.run "shutdown -s -f -t 30 -c " chr(34) "机器即将关闭" chr(34) wscript.quitEnd Ifwscript.sleep 1000*10loop
=========此段函数仅供参考,不会在主程序中调用===========
通过dos窗口的方式ping,但是,屏幕上会出现黑色dos窗口,每运行一次下面的函数都会弹出一次dos和色窗口,很快就会被人发现。
Function IsOnline(strComputer) IsOnline = false strCommand = "%comspec% /c ping -n 2 -w 500 " strComputer "" Set objExecObject = objShell.Exec(strCommand) Do While Not objExecObject.StdOut.AtEndOfStream strText = objExecObject.StdOut.ReadAll() If Instr(strText, "Reply") 0 Then IsOnline = true End If LoopEnd Function
纯vbs进行ping操作,这样不会弹出dos窗口,不会被发现。
Function IsOnline_1(URLstr) IsOnline_1 = falsestrComputer = "."Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" strComputer "\root\cimv2")Set colPings = objWMIService.ExecQuery ("Select * From Win32_PingStatus where Address = '" URLstr "'") For Each objPing in colPings if instr(objPing.ProtocolAddress,URLstr) 0 then IsOnline_1=true exit for end if NextEnd Function
注:方法二是通过ping一个指定的IP地址,用于检测网卡的运行状态,如果网卡无法通讯或者通讯失败这样就无法返回Ping的结果,根据这个结果判断是否进行强制关机操作。由此,还有个 意外收获 那就是,当断掉指定的IP地址连接后,所有机器会自动关闭计算机,因此,此段程序还可以有别的用途,自己想吧!!!
总结:以上两种方法都是为了检测网卡的运行状态才进行相应的操作的,只是实现方法完全不同,这你就要根据情况自行选择了!!!
Vbs实现监测断网就关机的实现代码