Use Expect in a Bash script to provide a password to an SSH command Use Expect in a Bash script to provide a password to an SSH command linux linux

Use Expect in a Bash script to provide a password to an SSH command


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

#!/usr/bin/expecteval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com# Use the correct promptset prompt ":|#|\\\$"interact -o -nobuffer -re $prompt returnsend "my_password\r"interact -o -nobuffer -re $prompt returnsend "my_command1\r"interact -o -nobuffer -re $prompt returnsend "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 }'

This will wait for Enter and then return to (for a moment) the interactive session.


The easiest way is to use sshpass. This is available in Ubuntu/Debian repositories and you don't have to deal with integrating expect with Bash.

An example:

sshpass -p<password> ssh <arguments>sshpass -ptest1324 ssh user@192.168.1.200 ls -l /tmp

The above command can be easily integrated with a Bash script.

Note: Please read the Security Considerations section in man sshpass for a full understanding of the security implications.


Add the 'interact' Expect command just before your EOD:

#!/bin/bashread -s PWD/usr/bin/expect <<EODspawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.comexpect "password"send "$PWD\n"interactEODecho "you're out"

This should let you interact with the remote machine until you log out. Then you'll be back in Bash.