Explore Courses Blog Tutorials Interview Questions
0 votes
in Linux by (18.4k points)

I'm trying to use the Expect in my Bash script to provide my SSH password. Providing the password works, but I am end up in some other SSH session. It goes back to the Bash.

My script:


read -s PWD

/usr/bin/expect <<EOD

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no [email protected]$'

expect "password"

send "$PWD\n"


echo "you're out"

The output of my script:

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no [email protected]$

[email protected]$'s password: you're out

I want to have my SSH session only when I exit it and go back to my Bash script.

I wanted this because I have to use a menu. I wanted to choose which unit/device to connect to.

1 Answer

0 votes
by (36.8k points)

Mixing both 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 [email protected]$

# Use the 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 [email protected]$; interact }'

It waits for the Enter and then return to (for a moment) the interactive session.

To know about Linux join the Linux training

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 4, 2021 in Linux by blackindya (18.4k points)
0 votes
1 answer

Browse Categories