1
votes

I have a batch file that starts up a telnet session and executes a few command with using a vbs script:

start telnet.exe another.hostname
timeout /t 1 /nobreak > NUL
cscript c:\scripts\sendtelnet.vbs 1

My vbs script looks like this:

WScript.sleep 1000
arg = Wscript.Arguments.Item(0)
WScript.sleep 1000
cmd = "RUN CMD D "&arg&"{ENTER}"
WScript.sleep 1000
set OBJECT=WScript.CreateObject("WScript.Shell")
WScript.sleep 6000
OBJECT.SendKeys "administrator{ENTER}" 
WScript.sleep 200
OBJECT.SendKeys "mypass{ENTER}"
WScript.sleep 200
OBJECT.SendKeys cmd
WScript.sleep 5000
OBJECT.SendKeys "QUIT{ENTER}" 
WScript.sleep 500 
OBJECT.SendKeys "{ENTER}" 
WScript.sleep 100 
OBJECT.SendKeys " "

I can run this test about 10 times, but it'll only work about 8 out of 10 times. I've witnessed the test fail, and what happens is the telnet window is opened, but it hangs on the "username" prompt, eventually the telnet session just times out and the window never closes.

Why would this only work sometimes? Do I need to increase the sleep times perhaps? I have tried to sleep 6000 ms, and it seems like its long enough. I've been trying lots of things but I keep getting stuck on this part, I'm willing to try anything at this point, please any advice?

1
Are you losing focus? Success = OBJECT.AppActivate("title of telnet window here") before sending keys - Alex K.
Thats a really good suggestion, Alex, I'll try this. - SSH This

1 Answers

2
votes

Telnet is flaky all by itself. I get similar behavior from time to time when manually logging into a switch or router. Try logging in and out of the telnet server 10-20 times and see if it's hanging at the username prompt. I don't think your script is to blame although the sendkeys method in vbscript is horrible anyway. It only works sometimes and under specific conditions. I'd suggest putting

object.appactivate ("C:\windows\system32\telnet.exe") 

in your vbscript just before

cmd = "RUN CMD D "&arg&"{ENTER}"

as well. That way you at least know the keystrokes are going to the right window. You might want to take a look at AutoIT. It's much more robust for sending keys to windows.