Max Max - 1 month ago 14
Linux Question

Use expect in bash script to provide password to SSH command

To those who want to reply that I should use SSH keys please abstain

I'm trying to use expect in an bash script to provide the SSH password. Providing the password works but I don't end up in the SSH session as I should, it goes back strait to bash.

My script:


read -s PWD

/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$'
expect "password"
send "$PWD\n"
echo "you're out"

The output of my script:

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$
usr@$'s password: you're out

I would like to have my SSH session and only when I exit it to go back to my bash script.
The reason why I am using bash before expect is because I have use a menu I can choose which unit to connect to.



Mixing bash and expect is not a good way to achieve the desired effect. I'd try to use only Expect:

eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$
#use correct prompt
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "my_password\r"
interact -o -nobuffer -re $prompt return
send "my_command1\r"
interact -o -nobuffer -re $prompt return
send "my_command2\r"

Sample solution for bash could be:

/usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$; interact }'

This will wait for enter and than return (for a moment) interactive session.