Skip to content

Instantly share code, notes, and snippets.

@taxilian
Last active July 19, 2021 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taxilian/49b4fd794098d310d42ca8e61fd71bfc to your computer and use it in GitHub Desktop.
Save taxilian/49b4fd794098d310d42ca8e61fd71bfc to your computer and use it in GitHub Desktop.
Easily switch between different SSH agents on mac, probably easy to adapt to any linux
function showAgent() {
echo The current SSH agent is $(readlink ~/.ssh-agent-link)
}
function updateSshAgentSock() {
NEWSOCK=$2
if [ -z "$NEWSOCK" ]; then
echo -n "No socket found for ${1}; not changing agents. "
return 1
elif [ ! -S "$NEWSOCK" ]; then
echo -n "Socket ${NEWSOCK} is not a socket; not changing agents. "
else
ln -sfv "$NEWSOCK" ~/.ssh-agent-link
fi
showAgent
}
function usegpg() {
if pgrep -x "gpg-agent" > /dev/null; then
gpgconf --reload gpg-agent
else
gpgconf --launch gpg-agent
fi
NEWSOCK=$(gpgconf --list-dirs agent-ssh-socket)
if [ -z "$NEWSOCK" ]; then
NEWSOCK=$(lsof -c gpg-agent | grep "\.ssh" | awk '{print $8}')
fi
updateSshAgentSock "gpg-agent" "$NEWSOCK"
}
function useagent() {
NEWSOCK=$(launchctl getenv SSH_AUTH_SOCK)
if [ -z "$NEWSOCK" ]; then
# Less efficient and brute force way to get agent
NEWSOCK=$(lsof -c ssh-agent | grep Listeners | awk '{print $8}')
fi
updateSshAgentSock "ssh-agent" "$NEWSOCK"
}
function usesekey() {
NEWSOCK=~/.sekey/ssh-agent.ssh
updateSshAgentSock "sekey" "$NEWSOCK"
}
export SSH_AUTH_SOCK=~/.ssh-agent-link
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment