ssh-lastpass/ssh-copy-id.sh

52 lines
1.7 KiB
Bash
Raw Permalink Normal View History

2019-02-07 14:51:01 -05:00
#!/bin/bash
#Maintained by Linux Operations - Russ Long - <rlong@nabancard.com>
#Set variables
2019-03-19 11:06:07 -04:00
keyname="${1}"
2019-03-19 09:01:05 -04:00
username=${2}
hostname=${3}
2019-03-19 11:06:07 -04:00
keysavename=$(echo -e ${keyname} | tr -d '[:space:]' | awk -F"/" '{print $NF}')
keyfile=$HOME/.ssh/${keysavename}-$(date "+%s")
pubkeyfile=$HOME/.ssh/${keysavename}-$(date "+%s").pub
2019-02-07 14:51:01 -05:00
#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
2019-03-19 11:06:07 -04:00
#Fetch private key and place in /home/$user/.ssh/$keysavename-datetime
lpass show "$keyname" --field="Private Key" > $keyfile
2019-02-07 14:51:01 -05:00
chmod 0600 $keyfile
2019-03-19 11:06:07 -04:00
#Fetch public Key and place in /home/$user/.ssh/$keysavename-datetime.pub
lpass show "$keyname" --field="Public Key" > $pubkeyfile
2019-02-07 14:51:01 -05:00
#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."
2019-03-19 09:01:05 -04:00
ssh-copy-id -i $pubkeyfile $username@$hostname
2019-02-07 14:51:01 -05:00
#Remove keyfiles
rm -f $keyfile
rm -f $pubkeyfile