ssh-lastpass/ssh-copy-id.sh
2019-03-19 09:01:05 -04:00

51 lines
1.6 KiB
Bash
Executable File

#!/bin/bash
#Maintained by Linux Operations - Russ Long - <rlong@nabancard.com>
#Set variables
keyname=${1}
username=${2}
hostname=${3}
keyfile=$HOME/.ssh/${keyname}-$(date "+%s")
pubkeyfile=$HOME/.ssh/${keyname}-$(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/$keyname-datetime
lpass show $keyname --field="Private Key" > $keyfile
chmod 0600 $keyfile
#Fetch public Key and place in /home/$user/.ssh/$keyname-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