Thursday, March 08, 2012

mcp -- copying a file to multiple machines via scp

I have a series of 6 machines that I need to occasionally deploy the same file to in exactly the same place.  I got tired of it being such a pain so I wrote this little script I call mcp.sh  It's certainly easy enough for a shell script master to do this, but for me?  I struggled for 30 mins to get this right -- hopefully this saves you some pain.

I assume you have already passed your ssh key to the machines you want to connect to so you can scp without a password.  If not please read  http://www.thegeekstuff.com/2008/11/3-steps-to-perform-ssh-login-without-password-using-ssh-keygen-ssh-copy-id/

You call mcp.sh with the absolute path to the file you want to copy, and it will copy it to exactly the same location on the target machine.

Put names of the machines (one per line) you want to update in the file hosts.txt

#mcp.sh

firstChar=`expr substr $1 1 1`
if [ -z $1 ]; then
        echo "usage mcp </absolute/path/to/file.txt>"
        exit 1
fi
if [ $firstChar  != / ]; then
        echo "Must use absolute path"
        exit 1
fi
for line in `cat hosts.txt`
do
 `scp $1 root@$line:$1`
done


improvement comments welcome

No comments: