受一个朋友委托,编写一段vbs代码实现断网就强行关闭计算机的功能,他说为学生机房上课时使用,上课时总有学生想脱离老师的监视,为此,会拔掉网线或者禁用网卡,所以,弄个vbs脚本检测网卡状态,如果断网马上强行关机。
代码一
dim objwmiservice,objshell set objwmiservice = getobject("winmgmts:\\.\root\cimv2") set objshell = createobject("wscript.shell") '实现实时监测 do while true dim objnetworks,objnetwork set 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 if next set objnetworks=nothing '延时10秒 wscript.sleep 1000*10 loop
注:方法一是通过检测网卡的状态来进行相应的操作。
方法二
strip="192.168.1.1" '实时监测 do while true set objshell = createobject("wscript.shell") if not isonline_1(strip) then objshell.run "shutdown -s -f -t 30 -c " & chr(34) & "机器即将关闭" & chr(34) wscript.quit end if wscript.sleep 1000*10 loop
=========此段函数仅供参考,不会在主程序中调用===========
通过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 loop end function
纯vbs进行ping操作,这样不会弹出dos窗口,不会被发现。
function isonline_1(urlstr) isonline_1 = false strcomputer = "." 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 next end function
注:方法二是通过ping一个指定的ip地址,用于检测网卡的运行状态,如果网卡无法通讯或者通讯失败这样就无法返回ping的结果,根据这个结果判断是否进行强制关机操作。由此,还有个“意外收获”那就是,当断掉指定的ip地址连接后,所有机器会自动关闭计算机,因此,此段程序还可以有别的用途,自己想吧!!!
总结:以上两种方法都是为了检测网卡的运行状态才进行相应的操作的,只是实现方法完全不同,这你就要根据情况自行选择了!!!
发表评论