Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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:

#!/bin/bash

read -s PWD

/usr/bin/expect <<EOD

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com'

expect "password"

send "$PWD\n"

EOD

echo "you're out"

The output of my script:

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com

usr@$myhost.example.com'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:

#!/usr/bin/expect

eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com

# 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"

interact

Sample solution for bash could be:

#!/bin/bash

/usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com; 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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...