Ssh publikkey authentication for git within a bash script

bashgitssh

I currently have a bash script running on my Linux server that once a week goes through my repositories, performs some tasks, and backs them up remotely.

Today I started backing up some remote repositories as well. My plan was to be able within the backup bash script run something like (cd $dir && git pull origin master 2>> $LOGFILE) inside a for loop. The problem I seem to be having is that I'm trying to pull some stuff from github and that requires my private key file to be unlocked before proceeding. Is there any way that I can provide that password beforehand so that I don't get an interactive prompt for the password?

Best Answer

Use SSH agent forwarding. You will have to use an agent on your initial machine; you will also have to have agent forwarding enabled in your client and on your Linux server.

Assuming OpenSSH all around:

test -z "$SSH_AUTH_SOCK" && eval "$(ssh-agent)"
ssh-add -f /path/to/your/key-accepted-by-GitHub
ssh-add -f /path/to/your/key-accepted-by-your-user-on-the-linux-box
ssh -A userName@theLinuxBox /path/to/the/script

The sshd on your server (“yourLinuxBox”) will have to allow agent forwarding (AllowAgentForwarding in its sshd_config file; it usually defaults to “yes” if not present).

With your local agent holding the GitHub key and with agent forwarded through your SSH connection to the Linux box, any normal use of ssh on the Linux box that needs the key (e.g. git pull) will be able to use.

Or, you can use an entry in your .ssh/config to specify the bits of the “first leg” to abbreviate the last two commands as ssh backup-server /path/to/the/script (you will still have to make sure the GitHub key has been added to your local agent):

Host backup-server
    HostName     theLinuxBox # name or IP
    User         userName    # username on remote system
    IdentityFile /path/to/key-accepted-by-your-user-on-the-linux-box
    ForwardAgent yes

Note: Do not enable agent forwarding to untrusted servers (root on the server could use its local access to use keys stored in your local agent).