Skip to content

Instantly share code, notes, and snippets.

@isaaclw
Last active November 27, 2022 21:38
Show Gist options
  • Save isaaclw/670f3e5421eccf5955fde38de9b8b3d8 to your computer and use it in GitHub Desktop.
Save isaaclw/670f3e5421eccf5955fde38de9b8b3d8 to your computer and use it in GitHub Desktop.
Load the ssh key #function #bash #ssh
load_ssh_key() {
key=~/.ssh/id_ed25519
force=0
if [ -n "$1" ]; then
if [ -e "$1" ]; then
key=$(readlink -f $1)
elif [ "$1" == "reset-all" ]; then
echo "resetting"
pkill --signal 9 -f ssh-agent
force=1
fi
fi
SOCKET="$HOME/.ssh/ssh_auth_sock"
#SOCKET="$(ls -t /run/user/$(id -ur)/keyring*/ssh | head -1)" # this should find the most recently created ubuntu socket
# if the socket doesn't already exists and there isn't any agent running:
if [ $force -eq 1 ] || ! pgrep -u $USER ssh-agent > /dev/null || [ ! -e "$SOCKET" ]; then
echo "deleting socket"
rm -f "$SOCKET" # socket exists, pid doesn't
eval $(ssh-agent -s -a $SOCKET)
fi
export SSH_AUTH_SOCK=$SOCKET
if ! env | grep -q SSH_AGENT_PID; then
export SSH_AGENT_PID=$(pgrep -u $USER ssh-agent | tail -1)
fi
# Only load the ssh keys if we need them
fingerprint="$(ssh-keygen -lf "$key" | cut -d' ' -f2)"
if ! ssh-add -l | grep -q "$fingerprint"; then
ssh-add $key > /dev/null && echo "Loaded $key"
[ $? -gt 0 ] && load_ssh_key reset-all
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment