【问题标题】:capture command line output in vbscript在 vbscript 中捕获命令行输出
【发布时间】:2017-02-14 22:30:10
【问题描述】:

得到了一个简单的脚本,可以对服务器执行命令 - 简单地说:

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

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

服务器提供了我想要获取的反馈。我只需要将第一行捕获到一个变量中,然后打印该变量即可确认。

你能帮忙吗?谢谢。

【问题讨论】:

    标签: windows command-line vbscript


    【解决方案1】:

    请勿将 Windows telnet 客户端用于自动化目的。 Windows 附带的telnet 客户端仅供交互使用。

    我会在批处理模式下使用plink(来自PuTTY suite):

    plink.exe -telnet -batch IP_ADDRESS dir
    

    该工具不需要安装,因此您只需将其与脚本一起部署即可。

    使用head/tail 在批处理文件中运行它,或者使用Exec 方法在VBScript 中运行它,这样您就可以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
    

    【讨论】:

    • 另一个可编写脚本的 telnet 是 Albert Yale 的 Telnet Scripting Tool v.1.0
    • 感谢您的时间-我需要运行的实际命令是“mute near get”-这是我输入的内容,但它似乎没有将其传递给服务器:如果你能得到我通过那个,将不胜感激.. plink -telnet -batch 62.39.x.x -P 24 "mute near get"
    • 它“似乎没有将其传递给服务器”究竟是如何做到的?在命令提示符下手动运行命令会得到什么?
    • 它似乎只有在我这样做时才有效:echo "mute near get" | plink -telnet -batch 62.39.x.x -P 24 它现在将其打印为 telnet 输出的最后一行 - 您能否详细说明如何使用 exec 方法捕获它?这是我的最后一个问题....提前致谢。谢谢。
    • 感谢您的所有帮助。我们快到了,但不幸的是它并没有结束,直到我按下 CTRL-c。我想也许我可能需要发送一个额外的退出命令或以另一种方式退出 do while 循环。
    【解决方案2】:

    这可能不是最好的方法,但对我有用:

    Windows telnet 命令可以使用 -f 参数将输出保存在客户端。因此,您可以使用:

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

    在脚本结束时,只需处理 telnet.out 的内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 2017-02-26
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多