For convenience, the optimal method is a combination of the answers of jmtd and Faheem.
Using ssh-agent
alone means that a new instance of ssh-agent
needs to be created for every new terminal you open. keychain
when initialized will ask for the passphrase for the private key(s) and store it. That way your private key is password protected but you won't have to enter your password over and over again.
The Arch wiki recommends initializing keychain from /etc/profile.d/
or your shell profile, such as .bash_profile
or .bashrc
. This has a disadvantage in that it intializes your keychain as soon as you open a terminal.
A more flexible approach is to combine keychain
with a specific tmux
session. So, in .bash_profile
:
tsess=$(tmux ls 2>&1)
if [[ "${tsess%%:*}" = "secured" ]] &&
[[ -f $HOME/.keychain/$HOSTNAME-sh ]]; then
# start keychain
/usr/bin/keychain -Q -q --nogui ~/.ssh/id_rsa
. $HOME/.keychain/$HOSTNAME-sh
fi
...and then it is just a case of starting the secured tmux
session as and when required (launched from a keybind):
#!/bin/bash
PID=$(pgrep tmux)
new="tmux -f $HOME/.tmux/conf new -s secured"
old="tmux attach -t secured -d"
if [[ -z "$SSH_AUTH_SOCK" ]]; then
eval `ssh-agent`
trap "kill $SSH_AGENT_PID" 0
fi
if [[ -z "$PID" ]]; then
urxvtc -title "SSH" -e sh -c "${new}"
else
urxvtc -title "SSH" -e sh -c "${old}"
fi
ssh-add
Now, your keychain will only be initialized once when you start that specific tmux
session. As long as that session persists, you will be able to access those ssh
keys and push to your remote repositories.