Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automate telnet session using Expect?

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> 
like image 350
Justin Avatar asked Jun 28 '12 18:06

Justin


3 Answers

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
like image 44
glenn jackman Avatar answered Nov 04 '22 00:11

glenn jackman


It's hard to tell, but from the output you're pasting it looks like:

  1. Your script isn't waiting for login to complete before sending the next command.
  2. Your script is exiting and closing the process before you can see any output.

There are no guarantees in life, but I'd try this as a first step:

#!/usr/bin/expect -f

spawn telnet 10.62.136.252
expect "foobox login:"
send "foo1\r"
expect "Password:"
send "foo2\r"

# Wait for a prompt. Adjust as needed to match the expected prompt.
expect "justin>"
send "echo HELLO WORLD\r"

# Wait 5 seconds before exiting script and closing all processes.
sleep 5

Alternatives

If you can't get your script to work by manually programming it, try the autoexpect script that comes with Expect. You can perform your commands manually, and autoexpect will generate an Expect typescript based on those commands, which you can then edit as needed.

It's a good way to find out what Expect actually sees, especially in cases where the problem is hard to pin down. It's saves me a lot of debugging time over the years, and is definitely worth a try if the solution above doesn't work for you.

like image 161
Todd A. Jacobs Avatar answered Nov 04 '22 02:11

Todd A. Jacobs


Have you seen this StackOverflow Question?

He seems to have got things working by using curly braces.

like image 33
rkyser Avatar answered Nov 04 '22 01:11

rkyser