0

I would like to automate a script that regularly runs rsync, and rsync prompts for my ssh key password each time I run it.

I don't mind typing the password once at the beginning of the script. I can't be prompted each time it runs an rsync command in a loop.

Is there a clean, safe way to prompt for the password once and continue using it?

My assumed solution would be to prompt for the password somehow (not sure how to do that off the top of my head) and store it in an environment variable, then use expect to make use of it. But I feel like there might be an easier approach that I'm not aware of.

David Parks
  • 1,140
  • 1
    Is there any particular reason you don't want to use certificate based authentication (which needn't require a password)? – Chris Davies Sep 30 '17 at 00:02
  • I'm using an ssh key, but the key itself is what requires a password, and it's generally insecure to leave an unencrypted ssh key laying around. – David Parks Sep 30 '17 at 21:47

1 Answers1

3

Set up an authentication agent. Namely ssh-agent. This runs in the background and intercepts requests that require authentication. When you start the agent it will ask you for your passphrase one time. It keeps it in memory and each time authentication is required (e.g. using SSH you log into a remote host on which your key has been installed) it automatically inserts it.

Here's one way to get up and running. Create a script and put it somewhere convenient (e.g. ~/bin) like so:

start_agent ()
{
    echo "Initialising new SSH agent...";
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > ${SSH_ENV};
    echo succeeded;
    chmod 600 "${SSH_ENV}";
    . "${SSH_ENV}" > /dev/null;
    /usr/bin/ssh-add
}

# Source SSH settings, if applicable
SSH_ENV=$HOME/.ssh/environment
if [ -f ${SSH_ENV} ]; then
     . "${SSH_ENV}" > /dev/null
     # ps flags are not always portable so check here if agent doesn't start
     ps -p "${SSH_AGENT_PID}" || start_agent;
else
     start_agent;
fi

Then simply source this script: . ~/bin/ssh-agent-init.sh. You will be prompted for your passphrase at this point so enter it and then you're good to go.

You can source it from your .bashrc if you want it to run all the time.

B Layer
  • 5,171