Automate SSH logins when a password is required

Today I learned how to automate SSH logins when a password is required. In order to make this happen we need to first install expect

Install Expect

brew install expect

Create bash scripts

cd /usr/bin/local
touch exp
touch ssh-custom
chmod u+x exp ssh-custom

Open the exp file and enter in the following:

#!/usr/bin/expect -f
set timeout 20

set cmd [lrange $argv 0 end]

# Check if SSHPASS is set
if {[info exists env(SSHPASS)]} {
    set password $env(SSHPASS)
} else {
    puts "Error: SSHPASS environment variable not set."
    exit 1

spawn ssh $cmd
expect "password for your-username:"
send "$password\r"

The string on the line expect "password for your-username:" will need to match the text that gets displayed when you ssh normally to whatever server is requiring a password. This will be what expect waits for before entering in your password.

Now open the ssh-custom file and enter the following. This will be what we eventually setup an alias for that will divert the ssh command to the exp file that will handle servers that require a password.


if [ "$1" == "production" ]; then
    exp production
    # Default behavior for other SSH commands
    ssh "$@"

Now we need to setup the environment variable and alias. Assuming you use zsh, add the following to your .zshrc file.

alias ssh="ssh-custom"
export SSHPASS="yoursshpassword"


Now when you run ssh production it will automatically enter your password.

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

Reduce label clickable area to text

Reduce label clickable area to text