通过 VBA Excel Plink SSH 访问并终止 cmd 提示符

Plink SSH access through VBA Excel and terminating the cmd prompt

我编写了一个宏来遍历 IP 地址列表和 运行 SSH 通过 plink.exe。 IP 用于网络安全设备。

如果 SSH 可访问,输出将是 "login as:",这意味着我可以通过 SSH 连接到设备。 cmd 的输出被读取到 excel 中的单元格,并显示在 table 中,因为该设备是可访问的。

问题是在执行顶级 IP 的代码后,plink.exe window 没有关闭,我必须手动关闭 window 以再次循环代码以转到下一个IP。如果不知何故,我可以自动关闭程序中的 window,这样它就可以 运行 通过所有 IP(大约有 100 个 IP)。

重要的是我不想在 "login as:" 之后向 cmd 发送任何登录信息。我想终止程序并在获取输出后立即关闭 cmd window 。您的帮助将不胜感激。

Sub SSH()
On Error GoTo ErrHandler
i = 3
j = 200
While (ActiveSheet.Cells(i, 3) <> "")

'Retrieve IP address from the cell

strCompAddress = ActiveSheet.Cells(i, 3)

Dim strShellCommand As String
Dim filename As String
Dim Run As String
Dim pointer As String

'Plink file location from a cell in different sheet
filename = Sheet1.Cells(8, 2).Value
pointer = "-ssh"

Run = filename & " " & pointer & " " & strCompAddress
Set osh = CreateObject("Wscript.Shell")
Set oEx = osh.Exec(Run)

'The output is inserted to a cell specified
strBuf = oEx.StdOut.ReadAll
ActiveSheet.Cells(j, 21) = strBuf

i = i + 1
j = j + 1
Wend
Exit Sub
ErrHandler: MsgBox "Please check the filename/address."
End Sub

Wscript.Shell.Exec method returns a WshScriptExec object which has a Terminate 方法。 Terminate 方法就是您想要的。

你可以这样使用它

Public Sub test()

    Dim WshShell, oExec
    Set WshShell = CreateObject("WScript.Shell")

    Set oExec = WshShell.Exec("calc")
    oExec.Terminate

    MsgBox oExec.Status

End Sub

编辑

理想情况下,您可以像这样实现

strBuf = oEx.StdOut.ReadAll
ActiveSheet.Cells(j, 21) = strBuf
oEx.Terminate

不过。我怀疑 ReadAll 只要程序是 运行 就会继续阅读。您想只读一行然后退出,所以就这样做吧。

strBuf = oEx.StdOut.ReadLine
ActiveSheet.Cells(j, 21) = strBuf
oEx.Terminate ' now kill plink

我能够找出问题所在。我必须让应用程序等待一段时间才能终止它,因此能够根据需要获得输出。感谢您的帮助。

Set oEx = osh.Exec(Run)
Application.Wait (Now + TimeValue("0:00:5"))
oEx.Terminate