Auto Deploy .bashrc to Linux Servers with Bash


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
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s