How to automate telnet session using Expect?

Justin picture Justin · Jun 28, 2012 · Viewed 39.4k times · Source

I'm trying to write an expect script to automate telnet. This is what I have so far.

#!/usr/bin/expect
# Test expect script to telnet.

spawn telnet 10.62.136.252
expect "foobox login:"
send "foo1\r"
expect "Password:"
send "foo2\r"
send "echo HELLO WORLD\r"
# end of expect script.

Basically, what I want to do is telnet to the following IP address and then echo HELLO WORLD. However, it seems that the script fails after attempting to telnet...I'm not sure if it's able to accept login and password input, but it is not echoing HELLO WORLD. Instead, I just get this output:

cheungj@sfgpws30:~/justin> ./hpuxrama 
spawn telnet 10.62.136.252
Trying 10.62.136.252...
Connected to 10.62.136.252.
Escape character is '^]'.
Welcome to openSUSE 11.1 - Kernel 2.6.27.7-9-pae (7).

foobox login: foo1
Password: foo2~/justin> 

Answer

glenn jackman picture glenn jackman · Jun 29, 2012

You're sending the echo command without first expecting the prompt. Try:

# after sending the password
expect -re "> ?$"
send "echo HELLO WORLD\r"
expect eof