Temporarily remove the password from the ssh private key in a shell script


I am required to deploy some files from server A to server B. I connect to server A via SSH and from there, connect via ssh to server B, using a private key stored on server A, the public key of which resides in server B's authorized_keys file. The connection from A to B happens within a Bash shell script that resides on server A.

This all works fine, nice and simple, until a security-conscious admin pointed out that my SSH private key stored on server A is not passphrase protected, so that anyone who might conceivably hack into my account on server A would also have access to server B, as well as C, D, E, F, and G. He has a point, I guess.

He suggests a complicated scenario under which I would add a passphrase, then modify my shell script to add a a line at the beginning in which I would call

ssh-keygen -p -f {private key file}

answer the prompt for my old passphrase with the passphrase and the (two) prompts for my new passphrasw with just return which gets rid of the passphrase, and then at the end, after my scp command calling

ssh-keygen -p -f {private key file}

again, to put the passphrase back

To which I say "Yecch!".

Well I can improve that a little by first reading the passphrase ONCE in the script with


then supplying it as needed using the -N and -P parameters of ssh-keygen.

It's almost usable, but I hate interactive prompts in shell scripts. I'd like to get this down to one interactive prompt, but the part that's killing me is the part where I have to press enter twice to get rid of the passphrase

This works from the command line:

ssh-keygen -p -f {private key file} -P {pass phrase} -N ''

but not from the shell script. There, it seems I must remove the -N parameter and accept the need to type two returns.

That is the best I am able to do. Can anyone improve this? Or is there a better way to handle this? I can't believe there isn't.

Best would be some way of handling this securely without ever having to type in the passphrase but that may be asking too much. I would settle for once per script invocation.

Here is a simplified version the whole script in skeleton form

#! /bin/sh

unset_passphrase() {
        # params
        # oldpassword keyfile
        echo "unset_key_password()"
        cmd="ssh-keygen -p -P $1 -N '' -f $2"
        echo "$cmd"

reset_passphrase() {
        # params
        # oldpassword keyfile
        echo "reset_key_password()"
        cmd="ssh-keygen -p -N '$1' -f $2"
        echo "$cmd"

echo "Enter passphrase:"
unset_passphrase $PASSPHRASE $KEYFILE
# do something with ssh
reset_passphrase $PASSPHRASE $KEYFILE

Check out ssh-agent. It caches the passphrase so you can use the keyfile during a certain period regardless of how many sessions you have.

Here are more details about ssh-agent.