使用VBA自动执行从Excel到Telnet的过程

时间:2016-03-16 20:07:00

标签: vba excel-vba telnet excel

所以我正在尝试自动化从Excel到Telnet的过程,我想知道我是否可以使用VBA代码。基本上我正在做的是将IP /端口从excel复制到telnet并通过telnet运行它们以查看IP是否正在响应。 IP是第三方监视器,已经设置并且经常出现问题。

我在网上发现了这个代码,它的功能似乎与我想做的相似。

Sub Start_Telnet_Session()
    'Declare Variables
    Dim Data As String
    Dim Winsock1

    'Server IP, Port & Login Credentials
    TelnetServer = ThisWorkbook.Sheets(1).Cells(1, 1)
    TelnetPort = ThisWorkbook.Sheets(1).Cells(2, 1)
    TelnetUser = ThisWorkbook.Sheets(1).Cells(3, 1)
    TelnetPassword = ThisWorkbook.Sheets(1).Cells(4, 1)
    TelnetCommands = ThisWorkbook.Sheets(1).Cells(5, 1)

    'Create WinSock Object & Connect to Server
    Set Winsock1 = New MSWinsockLib.Winsock
    Winsock1.RemoteHost = TelnetServer
    Winsock1.RemotePort = TelnetPort
    Winsock1.Connect

    'Wait Till connection is Success
    Do Until Winsock1.State = 7
        DoEvents
        If Winsock1.State = sckError Then
            Exit Sub
        End If
    Loop

    'Send UserName
    Winsock1.SendData TelnetUser & vbCrLf
        DoEvents: Application.Wait (Now + TimeValue("0:00:05"))

    'Send Password if you Server Requires one
    Winsock1.SendData TelnetPassword & vbCrLf
        DoEvents: Application.Wait (Now + TimeValue("0:00:05"))

    'Send Commands One by one & Get response from Server
    i = 5
    While TelnetCommands <> ""
        DoEvents: Application.Wait (Now + TimeValue("0:00:01"))

        Winsock1.SendData TelnetCommands & vbCrLf
        DoEvents: Application.Wait (Now + TimeValue("0:00:05"))
        'Get Response
        Winsock1.GetData Data
        Data = VBA.Replace(Data, vbLf, "")
        Data = VBA.Replace(Data, vbCr, vbNewLine)
        MsgBox Data

        i = i + 1
        TelnetCommands = ThisWorkbook.Sheets(1).Cells(i, 1)
    Wend

    MsgBox "Process Completed - Closing Telnet Connection"
    Winsock1.Close
End Sub

0 个答案:

没有答案