Abhinandan Aithal
Abhinandan Aithal

Reputation: 171

Hitting a return at password prompt in expect script instead of sending password

I am trying to have an expect script inside a bash to login to a router, execute a command and store output in a text file.

#!/usr/bin/bash
FQDN=$1
LogFile=/tmp/Router_${FQDN}.txt
> $LogFile
expect -d  <<EOF > $LogFile
set timeout 20
set FQDN [lindex $argv 0]
set Username "user"
set Password "***$$$"
spawn ssh $Username@$FQDN
expect "*assword:"
send "$Password\r"
expect "#"
send "some command\r"
expect "#"
send "exit\r"
sleep 1
exit
expect eof
EOF
cat $LogFile

I am getting the below error message.

system personnel  =\r\r\n= may provide the evidence of such monitoring to law enforcement officials.    =\r\r\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==\r\r\npassword: "
send: sending "\n" to { exp6 }

expect: does "" (spawn_id exp6) match glob pattern "#"? no
password:
Enter old password:

Based on the error it appears that script is hitting the {return} key "\r" which is not to be sent at password prompt.

I don't have a return once i ssh. Not sure where i am going wrong.


This is my expect script which is working fine. Its only when i code this inside a bash script its failing.

#!/usr/bin/expect -f

set timeout 20
set FQDN [lindex $argv 0]
set Username "user"
set Password "***$$$"
spawn ssh -o "StrictHostKeyChecking no" $Username@$FQDN
expect "*assword: "
send "$Password\r"
expect "#"
send "some command\r"
expect "#"
send "exit\r"
sleep 1
exit

-Abhi

Upvotes: 0

Views: 2418

Answers (1)

Barmar
Barmar

Reputation: 780879

In a here-doc, variables like $Username and $Password are being expanded by the shell, so they're not seen as literals for Expect to expand. Since those shell variables aren't set anywhere, they're being expanded to null strings. As a result, it's executing ssh @$FQDN and sending an empty password.

You need to escape the $ so that Expect can process them.

You also don't need the set FQDN line in the Expect script, since you're using the shell variable for that.

#!/usr/bin/bash
FQDN=$1
LogFile=/tmp/Router_${FQDN}.txt
> $LogFile
expect -d  <<EOF > $LogFile
set timeout 20
set Username "user"
set Password "***$$$"
spawn ssh \$Username@$FQDN
expect "*assword:"
send "\$Password\r"
expect "#"
send "some command\r"
expect "#"
send "exit\r"
sleep 1
exit
expect eof
EOF
cat $LogFile

Or you could set them as shell variables, just like FQDN.

#!/usr/bin/bash
FQDN=$1
Username=user
Password="***$$$"
LogFile=/tmp/Router_${FQDN}.txt
> $LogFile
expect -d  <<EOF > $LogFile
set timeout 20
spawn ssh $Username@$FQDN
expect "*assword:"
send "$Password\r"
expect "#"
send "some command\r"
expect "#"
send "exit\r"
sleep 1
exit
expect eof
EOF
cat $LogFile

Upvotes: 1

Related Questions