gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:06:25 26 4
gpt4 key购买 nike

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

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

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

重要的部分是我不想在“登录为:”之后向 cmd 发送任何登录信息。我想在输出后立即终止程序并关闭 cmd 窗口。您的帮助将不胜感激。

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 方法返回 WshScriptExec 具有 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

关于excel - 通过 VBA Excel Plink SSH 访问并终止 cmd 提示符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32128645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com