Last active
February 6, 2023 22:32
-
-
Save chuckn246/a5f9e8bd538defbac1d6a8d33687f626 to your computer and use it in GitHub Desktop.
Add ssh keys to ssh-agent on Linux
This file contains hidden or 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
| #!/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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I add this script to
~/.local/bin(which is in my $PATH), then call it from~/.bashrc.