Skip to content

Instantly share code, notes, and snippets.

@gubatron
Last active February 17, 2020 15:17
Show Gist options
  • Save gubatron/2f457d4d7cc2b21272824a7805382cdb to your computer and use it in GitHub Desktop.
Save gubatron/2f457d4d7cc2b21272824a7805382cdb to your computer and use it in GitHub Desktop.
startSSHAgent bash function - checks for SSH_AGENT_PID in env, then for ssh-agent PID (pgrep), if not found, starts new ssh-agent, adds your keys
startSSHAgent() {
if [[ -z "$SSH_AGENT_PID" ]]; then
if [[ $(pgrep ssh-agent) ]]; then
export SSH_AGENT_PID=$(pgrep ssh-agent)
echo "Found existing ssh-agent PID, SSH_AGENT_PID=${SSH_AGENT_PID}"
else
echo "Starting fresh ssh agent"
eval `ssh-agent`
fi
fi
ssh-add ~/.ssh/my-private-key1
ssh-add ~/.ssh/my-private-key2
#...
ssh-add ~/.ssh/my-private-keyN
kill_old_ssh_agents #see https://gist.github.com/gubatron/2d97b31b0621c459f8b5ee8665c9f7b9
}
@zander
Copy link

zander commented Jan 11, 2020

Hi guba! Miss your patches at Flowee.org :)

The umask is probably not really needed, it was to make sure that the file is only readable by owner.

the limit of 48 hours is not on the life of the agent, it is on how long the agent keeps passwords. So you'd have to do a 'ssh-add' again after that. It is purely for security.

I just eval the output

That has the downside that if you logout your ssh-agent will keep running but you can't reach it anymore. Next time you login another agent will start. And you'll end up with more and more of them.
My writing file solution also means that if I login on the desktop and then later ssh to the same machine then I can reuse the already running ssh agent.

@gubatron
Copy link
Author

well I only eval if I can't find an existing ssh-agent, otherwise yes you end up with a bunch of ssh-agent processes

Ill check what's up with flowee.org and how I can help once I get a breather

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