Running a Telnet session from VBA

2019-02-17 18:34发布

问题:

I have a VBA library that does FTP, I'd like to do telnet as well. At the moment I'm shelling out to a Perl script that does the telnet based on a text file, but I'd like to drive the telnet connection natively from within the VBA. Does anyone have any source for this? I don't want to use an add-in, I need the code to be self-contained.

回答1:

If you can use the MS WinSock control (also see using winsock in VBA)

More resources:

MSDN Library: Using the Winsock Control

(Visual Basic) Winsock Control

if not, you could use cmd.exe and SendKeys perhaps:

Disclaimer: I copied the below code from the second of the links below, and modified it slightly for VBA.

sub telNETScript()
On Error Resume Next
Dim WshShell as object

set WshShell=CreateObject("WScript.Shell")
WshShell.run "cmd.exe"
WScript.Sleep 1000

'Send commands to the window as needed - IP and commands need to be customized
'Step 1 - Telnet to remote IP'
WshShell.SendKeys "telnet xx.xx.xx.73 9999"
WshShell.SendKeys ("{Enter}")
WScript.Sleep 1000

'Step 2 - Issue Commands with pauses'
WshShell.SendKeys ("{Enter}")
WScript.Sleep 1000
WshShell.SendKeys "5"
WshShell.SendKeys ("{Enter}")
WScript.Sleep 1000

'Step 3 - Exit Command Window
WshShell.SendKeys "exit"
WshShell.SendKeys ("{Enter}")
WScript.Quit

end sub

SendKeys is not the best or most reliable solution, but it was all I could find when I did this 12 years ago in my last job.

More info:

Telnet & Excel - Microsoft.excel.programming

How to automate Telnet commands using VBScript