capture command line output in vbscript

2019-08-05 10:30发布

Got a simple script that executes a command to a server - briefly:

//Create shell
set WshShell=CreateObject("WScript.Shell")
WshShell.run "cmd.exe"

//send commands
WshShell.SendKeys "telnet IP_ADDRESS"
WshShell.Sendkeys "dir"

Server offers feedback which I want to capture. I just need to capture the first line into a variable, and then just print that variable out to confirm.

Can you help? Thanks.

2条回答
SAY GOODBYE
2楼-- · 2019-08-05 11:00

It might not be the best method, but worked for me:

Windows telnet command can save the output in client side using -f arguments. Therefore, you could use:

WshShell.SendKeys "telnet -f D:\output\telnet.out IP_ADDRESS"

and at the end of your script, simply process the content of telnet.out

查看更多
你好瞎i
3楼-- · 2019-08-05 11:06

Do not use the Windows telnet client for automation purposes. The telnet client that ships with Windows was made for interactive use only.

I'd use plink (from the PuTTY suite) in batch mode for this:

plink.exe -telnet -batch IP_ADDRESS dir

The tool doesn't require installation, so you can simply deploy it alongside your script.

Run it either in a batch file using head/tail, or in a VBScript using the Exec method, so you can read from StdOut:

addr     = "62.39.x.x"
port     = 24
timeout  = 300 'seconds
timedOut = False

cmdline = "echo ""mute near get"" | plink.exe -telnet -batch " & addr & " -P " & port

Set sh = CreateObject("WScript.Shell")

'change working directory to directory containing script and plink executable
Set fso = CreateObject("Scripting.FileSystemObject")
sh.CurrentDirectory = fso.GetParentFolderName(WScript.ScriptFullName)

'wait until command completes or timeout expires
expiration = DateAdd("s", timeout, Now)
Set cmd = sh.Exec("%COMSPEC% /c " & cmdline)
Do While cmd.Status = 0 And Now < expiration
  WScript.Sleep 100
Loop
If cmd.Status = 0 Then
  cmd.Terminate
  timedOut = True
End If

WScript.Echo  cmd.StdOut.ReadAll

If cmd.ExitCode <> 0 Then
  WScript.Echo "Command terminated with exit code " & cmd.ExitCode & "."
  WScript.Echo cmd.StdErr.ReadAll
  WScript.Quit 1
ElseIf timedOut Then
  WScript.Echo "Command timed out."
  WScript.Echo cmd.StdErr.ReadAll
  WScript.Quit 2
End If
查看更多
登录 后发表回答