added lssh to its own repo

This commit is contained in:
James Tomasino 2019-04-18 15:51:42 -04:00
commit 3efe562c6d
1 changed files with 140 additions and 0 deletions

140
lssh Executable file
View File

@ -0,0 +1,140 @@
#!/bin/sh
# ENV Variables Used:
# SSH_KEY_LOCATIONS
# LASTPASS_USER
version="2019.04.18"
arg_options="hv"
key=""
# Required: lpass (lastpass cli)
if ! command -v lpass > /dev/null; then
printf "LastPass CLI is required.\n"
exit 2
fi
# Required: expect
if ! command -v expect > /dev/null; then
printf "'expect' is required.\n"
exit 2
fi
show_help () {
cat > /dev/stdout << END
lssh [options] [ssh-key]
OPTIONAL FLAGS:
-h Show this help
-v Show current version info
END
}
parse_input () {
if ! parsed=$(getopt $arg_options "$@"); then
printf "Invalid input\\n"
exit 2
fi
eval set -- "$parsed"
while true; do
case "$1" in
-h)
show_help
shift
;;
-v)
printf "%s\\n" "$version"
shift
;;
--)
shift
break
;;
*)
printf "Internal error."
exit 3
;;
esac
done
if [ $# -gt 0 ]; then
key="$1"
fi
}
main () {
parse_input "$@"
key_locations="${SSH_KEY_LOCATIONS:-$HOME/.ssh/}"
if [ -z "${key}" ]; then
printf "You need to specify a key name.\n"
exit 2
fi
# Try to find the passed key path / name from possible key locations.
# Add space-separated path locations for your keys to $SSH_KEY_LOCATIONS
# env variable.
for path in $key_locations; do
if [ -f "${path}${key}" ]; then
printf "Found key at: %s\\n" "${path}${key}"
KEY_ID="${path}${key}"
break;
fi
if [ -d "${path}${key}" ]; then
if [ -f "${path}${key}/id_rsa" ]; then
printf "Found key at: %s\\n" "${path}${key}/id_rsa"
KEY_ID="${path}${key}/id_rsa"
break;
fi
fi
done
# If no key is found there's nothing to activate. End script
if [ -z "$KEY_ID" ]; then
printf "Could not find key file.\n"
exit 1
fi
# If this key is already in the agent we don't need to do anything
if ssh-add -l | grep -q "${KEY_ID}"; then
printf "Key already present.\n"
exit 0
fi
# If not logged into lastpass, do so now
if ! lpass status -q; then
lpass login "${LASTPASS_USER}"
fi
# Retrieve key from LastPass. If logged in but not recently authenticated
# lastpass will prompt with pinentry. If no entry found, suppress error.
password=$(lpass show --password "SSH: ${key}" 2> /dev/null)
# If we found a password, apply it to the key
if [ -n "$password" ]; then
# awkward tabbing due to EOF structure
expect <<EOF >/dev/null
spawn ssh-add -t 3600 ${KEY_ID}
expect "Enter passphrase"
send "$password\n"
expect eof
EOF
else
printf "Unable to get password. Activating key without password.\n"
ssh-add -t 3600 "${KEY_ID}"
fi
# Double-check whether the key was added to the agent
if ssh-add -l | grep -q "${KEY_ID}"; then
printf "Key successfully activated.\n"
exit 0
else
printf "Found passphrase but could not activate key.\n"
exit 1
fi
}
main "$@"