Skip to content

Instantly share code, notes, and snippets.

@sergii-bond
Created June 20, 2017 20:19
Show Gist options
  • Save sergii-bond/f3f3c095d2f6d52759e1bd6520eef678 to your computer and use it in GitHub Desktop.
Save sergii-bond/f3f3c095d2f6d52759e1bd6520eef678 to your computer and use it in GitHub Desktop.
Start SSH agent only once and add identity information without password prompt
SSH_ENV="$HOME/.ssh/environment"
KEY="$HOME/.ssh/id_rsa"
function start_agent {
# Starts the ssh-agent
# and adds its env vars into $SSH_ENV file.
echo "Initializing new SSH agent..."
# spawn ssh-agent
ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
echo succeeded
chmod 600 "$SSH_ENV"
. "$SSH_ENV" > /dev/null
}
function add_identities {
# Adds $KEY identities to the agent,
# if the agent has no identities associated
ssh-add -l | grep "The agent has no identities" > /dev/null
if [ $? -eq 0 ]; then ssh-add $KEY; fi
}
function is_ssh_agent_pid_valid () {
# Accepts ssh agent's pid as the first argument.
# Returns 0 if ssh-agent process is running,
# otherwise returns non-zero.
ps -ef | grep $1 | grep -v grep | grep ssh-agent > /dev/null
}
# check for running ssh-agent with proper $SSH_AGENT_PID
if [ -n "$SSH_AGENT_PID" ] && is_ssh_agent_pid_valid $SSH_AGENT_PID; then
add_identities;
else
# if $SSH_AGENT_PID is not properly set, we might be able to load one from $SSH_ENV
if [ -f "$SSH_ENV" ]; then . "$SSH_ENV" > /dev/null; fi
if ! is_ssh_agent_pid_valid $SSH_AGENT_PID; then start_agent; fi
add_identities
fi
@sergii-bond
Copy link
Author

I had an annoying problem. Whenever I wanted to do some git operations with a remote repository, such as git pull, it asked me to input a password, which I had set when creating ~/.ssh/id_rsa for security reasons. The first solution I found was to create a file ak with the following contents and source it:

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

It asks for a password, I input it and then git doesn't ask me for a password anymore. True, only if you invoke git in the same terminal session. But I use multiple sessions via tmux terminal multiplexer. Thus in every new window where I wanted to use git I had to type source ~/bin/ak and type a password. Still annoying. Also behind the scenes it would have as many ssh-agent processes running as the number of times I sourced that file.

Then after a year of struggling, I browsed the web again and found how to solve this problem once and for all. The original solution can be found here. I fixed one issue there and slightly improved it, the result is the script above. Copy it into your '.bashrc' and I hope it will make your life easier too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment