Blitzkoder
Blitzkoder

Reputation: 1838

Automating ssh-add private keys with a common password

I have searched but the solutions I found were only focused on using a single key file. Suppose I have a set of private keys which require the same password (and that I am confortable with such a setup from a security perspective).

How could I go about making a bash script that reads a password from stdin and invokes ssh-add for each of the private keys using the same password?

I do not have -p available for ssh-add.

I am trying to avoid writing the password to a file (even if temporary). I came with this so far but I am unsure how to go or if this is possible:

#!/bin/bash

if [ $(ps ax | grep [s]sh-agent | wc -l) -gt 0 ] ; then
    printf "> 'ssh-agent' is running.\n"
else
    printf "> 'ssh-agent' needs to be running. Exiting.\n"
    exit 0
fi

unset password
prompt="> Please input your password: "
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]
    then
         break
    fi
    prompt='*'
    password+="$char"
done

printf "\n> Adding key files...\n"

## declare an array variable
declare -a arr=("key-1.ppk" "key-2.ppk" "key-3.ppk")

## now loop through the above array
for i in "${arr[@]}"
do
   #echo "$i"
   ssh-add "$i" < <(echo "$password")   

done

Also tried the following to pass into stdin:

echo $password | ssh-add "$i"

I also thought about using this in the loop:

{
/usr/bin/expect << EOF
  spawn ssh-add $HOME/.ssh/$i
  send "$password\r"
  expect eof
EOF
}

But then it would ask me to input a password for each individual key, defeating the purpose of automation. Unless there is a way for a single spawn ssh-add to receive one single password via expect (only one prompt) and add more than one key with it?

Upvotes: 2

Views: 439

Answers (2)

VDR
VDR

Reputation: 2853

If you have same password for all the keys then you can pass multiple keys to ssh-add and it prompts for password only once and adds all those keys to the ssh-agent.

eg:

$> arr=("id_ecdsa" "new_test_key")
$> ssh-add ${arr[@]}
Enter passphrase for id_ecdsa:
Identity added: id_ecdsa (test_user@host_test)
Identity added: new_test_key (test_user@host_test)

$> ssh-add -l
256 SHA256:urYhdMK9UZyLl+p8cC7ehdImYfvsmtJFtQmESWoczmM test_user@host_test (ECDSA)
256 SHA256:53obuQkRzLGW5iUJdmFPNvSK1quUSlCi4gbQkKsJinY test_user@host_test (ECDSA)

Upvotes: 3

Philippe
Philippe

Reputation: 26457

Password can be passed via environment variable :

#!/usr/bin/env bash
  
read password

ssh_askpass=$HOME/.ssh_askpass

echo 'echo "$password"' > $ssh_askpass; chmod 700 $ssh_askpass

ppk=key-1.ppk
export password
SSH_ASKPASS="$ssh_askpass" ssh-add $ppk < /dev/null

rm -f "$ssh_askpass"

Upvotes: 1

Related Questions