1

I am trying to connect to my router through telnet using this script:

#!/usr/bin/expect -f

set timeout 20

# router user name
set name "admin"

# router password
set pass "admin"

# router IP address
set routerip "192.168.1.1"

# Read command as arg to this script
set routercmd "cat /var/1.leases" 

# start telnet
spawn telnet $routerip

# send username & password
expect "username:"
send -- "$name\n"
expect "password:"
send -- "$pass\n"

# get out of ISP's  Stupid menu program, go to shell
expect "TBS>>"
send --  "sh\n"

# execute command
expect -re ".*\$"
send -- "$routercmd\n"

# exit
send -- "^D"

Now the script works fine up to the send -- "sh\n" part. It gets to the shell prompt which appears like : ~ $ (tilda-space-dollar-space). However, I am unable to issue the command after this. It basically just doesn't work after that.

Can anybody tell why? Is their some mistake I am making?

Hennes
  • 65,804
  • 7
  • 115
  • 169
shivams
  • 1,804

1 Answers1

0

Okay. I cracked it. It had to do something with wrong pattern matching in the expect part in the final lines of the code.

What I, first of all, did was generate a recorded script using autoexpect. This tool is used to records your sessions and generate a script based on that. To do so, I first installed the autoexpect package (available in expect-dev package on Debian based systems) and then recorded my session:

sudo apt-get install expect-dev          #Since I'm on Ubuntu
autoexpect telnet 192.168.1.1

autoexpect automatically generated a script for me. When I ran this script, it was reaching till the execution of my command and executing it in the router, but was then unable to exit. Taking hints from this script and reading the expect man page, I finally figured out that there was some problem with the pattern recognition. I finally modified the script accordingly, and this is what finally works:

#I am mentioning here only the end part of the complete script which was faulty
# execute command
expect "~ \$ "
send -- "$routercmd\r"

expect "~ \$ "
send -- "exit\r"

expect -- "TBS>>"
send -- "exit\r"

expect -- "*Are you sure to logout?*" 
send -- "y"
expect eof

So, the lesson learnt was that we should use autoexpect to automatically generate scripts. And then if there is some fault in those auto-generated scripts, it would most probably be due to wrong pattern recognition in the expect part.

In my case, the essentially faulty part was:

expect -re ".*\$"    #WRONG
expect "~ \$ "       #RIGHT

The faulty parts will depend completely on your session, whom you are contacting. Contacting a mail-server through telnet will return different outputs and you will have to match accordingly.

shivams
  • 1,804