Skip to content

Instantly share code, notes, and snippets.

@aks
Created July 7, 2021 19:42
Show Gist options
  • Save aks/17e0818c020a60e2159bbc3812341e3d to your computer and use it in GitHub Desktop.
Save aks/17e0818c020a60e2159bbc3812341e3d to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# add ssh keys
PROG=${0##*/}
KEY_DIR=~/.ssh
PUB_SFX='.pub'
# on non-MacOS systems, comment this line out
USE_KEYCHAIN_OPTION='-K'
usage() {
cat 1>&2 <<EOF
usage: $PROG [options] [KEYNAME] ..
Add one or more keys from files within $KEY_DIR with filenames containing the
string KEYNAME. If no KEYNAME given, load all keys from files that have
corresponding files with the suffix ".pub".
On MacOS, uses '-K' to cause ssh passwords to be retained in the system keychain
(which survives reboots, which is awesome).
Options:
-h show this help
-n don't do anything, but show what would have been done
-l list all available key files
-v be verbose
EOF
}
talk() { echo 1>&2 "$*" ; }
talkf() { printf 1>&2 "$@" ; }
vtalk() { (( verbose )) && talk "$*" ; }
vtalkf() { (( verbose )) && talkf "$@" ; }
all_key_files() {
local name pub_name
cd $KEY_DIR
for pub_name in `ls -1 *.pub` ; do
name=`basename $pub_name $PUB_SFX`
if [[ -f "$name" && ! -L "$name" ]]; then
echo "$name"
fi
done
}
list_keys() {
if (( $# > 0 )); then
printf 1>&2 "%d keys found:\n" $#
local keyname
for keyname in "${all_keys[@]}"; do
talk " $keyname"
done
else
talk "No keys found in $KEY_DIR"
fi
talk ''
if [[ -n "$current_ids" ]]; then
talk "SSH Agent currently knows about these keys:"
ssh-add -l
else
talk "SSH Agent knows nothing about any keys"
fi
}
norun= verbose= list_keys=
while getopts 'hnvl' opt ; do
case "$opt" in
h) usage ;;
n) norun=1 ;;
v) verbose=1 ;;
l) list_keys=1 ;;
esac
done
shift $(( OPTIND - 1 ))
all_keys=( `all_key_files` )
vtalk "Found ${#all_keys[@]} key files"
current_ids="`ssh-add -l`"
if (( verbose )); then
talk "Found $( ssh-add -l | wc -l ) keys with ssh-agent"
fi
(( list_keys )) && { list_keys "${all_keys[@]}" ; exit ; }
if (( $# > 0 )); then
all_keys=( "$@" )
fi
for keyname in "${all_keys[@]}" ; do
vtalkf "Checking key: $keyname : "
if [[ ! "$current_ids" =~ $keyname ]] ; then
keyfile="$KEY_DIR/$keyname"
if [[ -e "$keyfile" ]]; then
vtalk " found"
( set -x ; ssh-add $USE_KEYCHAIN_OPTION $keyfile )
else
talk "no such file"
fi
elif (( verbose )) ; then
talk " already installed"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment