用于验证RDP连接的VBS脚本

时间:2014-06-25 14:15:48

标签: vbscript

我正在处理VBS脚本以确认RDP连接是否在远程服务器上运行。 我知道有些管理员在默认的RDP端口3389上通过Telnet进行检查。但是,它并不完全可靠。我需要打开一个到服务器的RDP连接,捕获结果,如果连接是否正常,请在文本文件中记录结果并关闭刚刚打开的窗口。 我的代码如下:

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("servers.txt", ForReading)
Set oFSO = CreateObject("Scripting.FilesyStemObject")
Outputfile="RDP.txt"
Set ofile = ofso.createTextFile(OutputFile, True)
ofile.writeline "computer" &vbtab& "Status"
Dim arrFileLines(), computer, pingable
i = 0
Do Until objFile.AtEndOfStream
 Redim Preserve arrFileLines(i)
 arrFileLines(i) = objFile.ReadLine
 i = i + 1
Loop
objFile.Close

For Each computer in arrFileLines

 Select Case RDPTest(computer)
  Case "RDP is working"
   wscript.echo computer &""& " RDP is working"
   ofile.writeline computer &""& vbtab & " RDP is working"
  Case "RDP is NOT working"
   wscript.echo computer & " RDP is not working"
   ofile.writeline computer &""& vbtab & " RDP is NOT working"

 End Select

 'WScript.Echo strLine
Next
Private Function RDPTest(ByVal strComputer)
 Dim objShell, objExecObject, strText
 Set objShell = CreateObject("Wscript.Shell")
 Set wshShell = CreateObject("WScript.Shell") 

 Set objExecObject = wshShell.Exec("%comspec% /c mstsc /v:" & strComputer) 'Calls RDP Connection to the target server as per servers.txt list
 ret = wshShell.AppActivate(strComputer & " - Remote Desktop") 'Check out if the RDP window is opened for the target server
     If ret = True Then 
         RDPTest = "RDP is working" 'Confirms RDP is working
         wshShell.SendKeys "%{F4}"  'Close up the RDP window

 Else  
     RDPTest = "RDP is NOT working" 'Confirms RDP is not working
     wshShell.SendKeys "%{F4}"      'Close up the RDP-error window
 End If 

  Do While Not objExecObject.StdOut.AtEndOfStream
  strText = strText & objExecObject.StdOut.ReadLine()
 Loop

调用远程服务器并通过servers.txt列表中提供的servername打开RDP的部分正在运行。问题在于确认RDP窗口打开的部分,并关闭它发布结果。我需要帮助来解决它。 由于代码无法识别刚刚由脚本打开的RDP窗口,因此它不会关闭窗口而不会将连接报告为正常工作。 我通过手动打开RDP到服务器来测试它,然后运行脚本,并且在运行脚本之前打开的窗口被脚本重新识别,但它没有关闭。

我提前感谢你对这个问题的任何帮助。

1 个答案:

答案 0 :(得分:0)

Exec在后​​台异步运行命令,即调用立即返回,并且不等到RDP会话建立。在ExecAppActivate之间添加一些延迟,检查应该有效:

Set objExecObject = wshShell.Exec("%comspec% /c mstsc /v:" & strComputer)
WScript.Sleep 2000  'wait 2 seconds
ret = wshShell.AppActivate(strComputer & " - Remote Desktop")