#!/bin/bash #Maintained by Linux Operations - Russ Long - #Set variables keyname="${1}" username=${2} hostname=${3} keysavename=$(echo -e ${keyname} | tr -d '[:space:]' | awk -F"/" '{print $NF}') keyfile=$HOME/.ssh/${keysavename}-$(date "+%s") pubkeyfile=$HOME/.ssh/${keysavename}-$(date "+%s").pub #Check to see if user is logged in to lastpass cli if lpass status | grep -q "Logged in as"; then echo "Logged in to Lastpass, continuing..." else echo "Please login with 'lpass login email@address.com'" exit 1 fi #Fetch private key and place in /home/$user/.ssh/$keysavename-datetime lpass show "$keyname" --field="Private Key" > $keyfile chmod 0600 $keyfile #Fetch public Key and place in /home/$user/.ssh/$keysavename-datetime.pub lpass show "$keyname" --field="Public Key" > $pubkeyfile #Ask user if they wish to remove old keys read -r -p "Do you wish to remove ALL other ssh keys for your user on $hostname? [Y/n]" removeresponse removeresponse=${removeresponse,,} #tolower if [ -z $removeresponse ]; then removeresponse="y" fi if [ $removeresponse = "y" ] || [ $removeresponse = "yes" ]; then echo "ALL Old keys being removed for your user, authorized_keys file on $hostname being backed up first." ssh $hostname "cp .ssh/authorized_keys{,.bak} && cat /dev/null > .ssh/authorized_keys" else echo "Something other than Yes was entered..." echo "" echo "Old keys will remain in place, please audit your authorized_keys file frequently!" echo "" echo "You may be prompted for your key passphrase for the key to be copied." echo "" fi #Add the key to ssh-agent echo "Copying id to $hostname, you may be asked to authenticate to SSH." ssh-copy-id -i $pubkeyfile $username@$hostname #Remove keyfiles rm -f $keyfile rm -f $pubkeyfile