在vbscript中捕获命令行输出 [英] capture command line output in vbscript

查看:64
本文介绍了在vbscript中捕获命令行输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

得到一个简单的脚本来执行对服务器的命令-简要地:

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.

可以帮忙吗?谢谢.

推荐答案

请勿出于自动化目的使用Windows telnet 客户端.Windows附带的 telnet 客户端仅用于交互式使用.

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

我会使用 plink (来自 PuTTY套件)批处理模式:

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.

使用 head / tail ,或在VBScript中使用 Exec 方法,因此您可以从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

这篇关于在vbscript中捕获命令行输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆