Created
June 20, 2017 20:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 fileak
with the following contents and source it: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 typesource ~/bin/ak
and type a password. Still annoying. Also behind the scenes it would have as manyssh-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.