SSH and Expect – Simple Script to Execute Remote Command and Display Output

expectssh

I am trying to connect to a network router and execute show status on it.
Currently i am using:

spawn ssh -o StrictHostKeyChecking=no admin@192.168.20.254
expect " * ? password:*\r"
send -- "secretPassword\r"
sleep 5
send -- "show status\r"
sleep 10
send -- "exit\r"

It dosen't work, i get stuck at admin@192.168.20.254's password:i've tried entering the password but it does not work, i get:

server1:~# secretPassword
-bash: server1: command not found
server1:~#

What am i doing so wrong here … ?

Best Answer

Try doing it like this

#!/usr/bin/expect -f
set timeout 120
spawn ssh -o StrictHostKeyChecking=no admin@192.168.20.254
expect "*?assword:*"
send -- "secretPassword\r"
sleep 5
send -- "show status\r"
sleep 10
send -- "exit\r"
expect eof

If your device is slow to respond you probably need to set a suitable timeout.

Related Topic