Skip to content

Instantly share code, notes, and snippets.

@chuckn246
Last active February 6, 2023 22:32
Show Gist options
  • Select an option

  • Save chuckn246/a5f9e8bd538defbac1d6a8d33687f626 to your computer and use it in GitHub Desktop.

Select an option

Save chuckn246/a5f9e8bd538defbac1d6a8d33687f626 to your computer and use it in GitHub Desktop.
Add ssh keys to ssh-agent on Linux
#!/usr/bin/env bash
# Description: Load ssh keys in $keydir to ssh-agent
# Author: Chuck Nemeth
# Define variables
keys=( main work aws )
case "$1" in
"" | "${keys[0]}")
keydir="$HOME/.ssh"
sockfile="/run/user/$(id -u)/ssh/ssh-agent.socket"
;;
"${keys[1]}")
keydir="$HOME/.ssh/work"
sockfile="/run/user/$(id -u)/ssh/work-agent.socket"
;;
"${keys[2]}")
keydir="$HOME/.ssh/aws"
sockfile="/run/user/$(id -u)/ssh/aws-agent.socket"
;;
*)
printf '%s\n' "Please try again using one of the following:"
printf '%s\n' "${keys[@]}"
esac
empty="The agent has no identities."
# Define arrays
declare -A keydata
mapfile -t sshkeys < <(grep -sl 'PRIVATE KEY' "${keydir}"/*)
mapfile -t loaded < <(SSH_AUTH_SOCK="$sockfile" ssh-add -l -E sha256 2>/dev/null |
/usr/bin/mawk -v var="$empty" '$0 !~ var { print $2 }')
# Populate keydata with "fingerprint = filepath"
for key in "${sshkeys[@]}"; do
sums=$(ssh-keygen -l -E sha256 -f "$key" | cut -d' ' -f2)
keydata[$sums]=$key
done
# Populate missing variable with unloaded keys
if [[ ${#sshkeys[@]} -gt ${#loaded[@]} ]]; then
missing=()
for f in "${!keydata[@]}"; do
if [[ ! "${loaded[*]}" == *"$f"* ]]; then
missing+=("$f")
fi
done
fi
# Add unloaded keys to ssh-agent
if [[ "${missing[*]}" ]]; then
if [[ -e "${sockfile}" ]]; then
for f in "${missing[@]}"; do
SSH_AUTH_SOCK="${sockfile}" \
ssh-add "${keydata[$f]}"
done
else
printf '%s\n' "No socket found. Is the ssh-agent service running?"
exit 1
fi
fi
# vim: ft=sh ts=2 sts=2 sw=2 sr et
@chuckn246
Copy link
Author

chuckn246 commented Mar 27, 2022

I add this script to ~/.local/bin (which is in my $PATH), then call it from ~/.bashrc.

if grep -qR "PRIVATE KEY" "$HOME/.ssh/"; then
  if [ -S "${XDG_RUNTIME_DIR}/ssh-agent.socket" ] && [ -z "${SSH_AUTH_SOCK}" ]; then
    export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/ssh-agent.socket"
  fi

  # Add keys to agent
  "$HOME/.local/bin/loadkeys"
fi

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