How to automate telnet session using Expect?

I am trying to write a wait script for telnet automation. This is what I still have.

#!/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 for the next IP address, and then the HELLO WORLD echo. However, it seems that the script crashes after trying telnet ... I'm not sure if it can accept input and password, but this does not repeat 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> 
+6
source share
4 answers

You send the echo command without first waiting for the invitation. Try:

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

It’s hard to say, but from the output, it looks like this:

  • Your script does not wait for registration to complete before sending the next command.
  • Your script terminates and closes the process before you can see any output.

There are no guarantees in life, but I would 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 auto-sensing the script that comes with Expect. You can execute your commands manually, and autoexpect will generate Expect typescript based on these commands, which can then be edited if necessary.

This is a good way to find out what Expect actually sees, especially when the problem is difficult to identify. This will save me a lot of debugging time over the years, and it is definitely worth a try if the above solution does not work for you.

+2
source

Have you seen fooobar.com/questions/899429 / ... ?

Everything seems to work for him using curly braces.

+1
source

Here is a simplified version

 #!/usr/bin/expect # just do a chmod 755 one the script # ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT # if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed set ip [lindex $argv 0] set port [lindex $argv 1] set timeout 5 spawn telnet $ip $port expect "'^]'." 
0
source

Source: https://habr.com/ru/post/919272/


All Articles