We’ve all been there, we have a bunch of linux boxes with user accounts set up and no SSH keys. If you are like most linux users out there you have probably read more than a few guides on setting up simplified access using SSH keys, but one thing that seems to be missing is a guide on how to efficiently deploy your SSH keys so that you don’t have to login to dozens or hundreds of machines. Enter the script below.
Any one who has been sysadmin with more than about 10 servers under their control knows how big a pain it can be to set up your environment on each box. I wrote this shell script to deploy my .bashrc file to some servers that I have an account on. Everything is pretty simple. My favorite feature is the versioning. This script can be used to deploy or set up pretty much anything because you can run any commands you wish with ssh.
The first thing we do is check to see if ssh key authentication has been set up. If key authentication is good we check to see if a scratch directory exists and creates it if it does not. After that we copy the existing .bashrc to the scratch directory and append the date to the filename. Once all that is complete we copy the new file in place. Pretty simple, but incredibly useful(at least to me).
#!/bin/bash #Deploy some useful files to a new server you have access to. #Loop through the server hostname/ips in the serverlist file for server in `cat ./serverlist`; do # Quick check to make sure the ssh key has been deployed to the server if `ssh -o BatchMode=yes $server 'uptime 2>&1' | grep -q average`; then #check to see if there is a scratch directory and create one if it does not scratch_result=`ssh $server 'if [ -d ~/scratch ]; then echo 0; else echo 1; fi'` if [ $scratch_result == 1 ]; then #create the directory ssh $server 'mkdir ~/scratch' if [ $? != 0 ]; then echo "Directory Creation Failed on $server" exit 0 fi elif [ $scratch_result != 0 ]; then echo "Directory Check Failed on $server" exit 0 fi #copy the bashrc file to the server echo -n "Copying bashrc to backup on $server..." ssh $server 'cp .bashrc ~/scratch/.bashrc`date +%F`.bak' if [ $? == 0 ]; then echo " Success" echo "Copying new bashrc to $server..." scp ./.bashrc $server: else echo " Fail" fi fi done