Automate Updating SSH Keys

by J. Edward Durrett

Regularly changing ssh keys is a good practice that often gets pushed to
the back burner. This is especially true if the system using the keys
is an automated process or is embedded like a router or other appliance.
Also, in an organization, the varying technical skills of staff might be
a hindrance. This script solves that problem:

bits= #Enter number of bits, assuming RSA key
fpath='' #Put path to private key here
comment_string='' #put comment string here, needed to delete old keys
ssh_user='' #User Name on Server
sshd_server='' #Server Name
sshd_port='' #Port sshd is running on server
srm $fpath'.old'#Replace srm with rm on systems that can't secure delete
mv $fpath $fpath'.old'
ssh-keygen -t rsa -b $bits -C $comment_string -P '' -f $fpath
scp -i $fpath'.old' -P $sshd_port
sed "/\$comment_string/d" $fpath'.authorized_keys' > $fpath'.authorized_keys.tmp
mv $fpath'.authorized_keys.tmp' $fpath'.authorized_keys'
cat $fpath'.pub' >> $fpath'.authorized_keys'
scp -i $fpath'.old' -P $sshd_port $fpath'.authorized_keys'
$ssh_user'@'$sshd_ser ver':~/.ssh/authorized_keys'

To use the above script, change the variables at the top for your setup.
If you already have keys set up, it will run, create a new key, and put
the public key on the remote machine.

When used on a regular basis, it will create a new key pair, put the
public key on a remote machine and also delete the old public key from
the remote server.

It can be put in a crontab to run on a regular basis, or can be called
from another script whenever that script is run. For example,
integrated with a backup script it will change the keys every time the
backup is run.

For users, it can be put in their crontab and they will always have new
keys without even having to bother with thinking about it.

Copyright (c) 2019, Jason Edward Durrett - All content on this site, unless otherwise noted, is subject to this license.

Please contact me if any errors, such as erroneous / misleading content or missing / incomplete attribution, are found.