Bash: Using Temporary SSH Keys Within A Script

August 10th, 2011 | Tags: , , ,

Every once and a while you will have the need to make multiple ssh calls to remote systems within a bash script.  Normally you would simply have the user enter their password multiple times, or have a requirement for SSH keys to be configured prior to running the keys.  This is widely accepted as the way to do it, however if that were the best way to do it, then I would not be writing this article.  Now the better way to do it would be to create ssh keys, and upload them as authorized keys to the remote host(s) then upon completion of the work we can then clean up the changes that we made.

tempkey="1"
uniqueoption="option"
remotehost="machine.allanglesit.net"
user="root"

if [ "$tempkey" -eq "1" ]
then
key="/root/.ssh/tempsshkey_id_${uniqueoption}"
publickey="/root/.ssh/tempsshkey_id_${uniqueoption}.pub"
authkeys="/root/.ssh/authorized_keys"
ssh-keygen -t rsa -q -f ${key} -N ''
chmod 600 ${key}
chmod 600 ${publickey}
pubkeystring=`cat ${publickey} | sed -e 's/\//.*/g'`
ssh-copy-id -i ${publickey} root@${remotehost} 2>&1 1>/dev/null
sshstring="ssh -i ${key} ${user}@${remotehost}"
else
sshstring="ssh ${user}@${remotehost}"
fi

${sshstring} "uptime"

if [[ -n "$tempkey" ]]
then
echo "Cleaning up temporary ssh keys..."
${sshstring} "cat ${authkeys} | sed -e '/$pubkeystring/d' > ${authkeys}"
rm ${key} ${publickey}
fi

The above code will require tempkey, uniqueoption, remotehost, and user variables to be set.  Now in my scripts I set these as parameters, and you will probably want to as well.  The uniqueoption should really be renamed to something that makes sense to you.  Basically this bit is so that if you are running your script multiple times on the same machine, you will be able to differentiate which key is for which process, so for example on my vmmigrate.sh script this variable was vmname, which meant that I would have an ssh key for every VM which was being migrated.  So if I wanted to move more than one VM then it would work without destroying the other key.

Basically what we are doing in the first part (line 6-19) is setting up the keys locally in a unique file (this prevents us from destroying any previously defined keys) and the set the permissions appropriately and copy them out to the remote machine.  The second part (line 21) is where we would invoke the script.  Notice we have captured the ssh command in a variable, this allows us to allow our script to either use temporary ssh keys or not, with a minimal amount of code.  Finally in part three (line 23-28) we clean up the the changes we made.  This is done by stripping only the key we added out of the authorized_keys file on the remote host and deleting the local copies of the private and public key.

Comments are closed.