Dec 18, 2013

Simple Script To Backup Files From a Linux Server Via SCP and SSH

Tux, the Linux penguin
 (Photo credit: Wikipedia)
I mentioned a little while back that I had replaced all of my Windows machines at home with Ubuntu. Well, one of the machines that I replaced was running a weekly backup job using WinSCP to go out and pull backup files from my personal email server so I would have a copy off site from my cloud hosting provider.

Since that machine is now running Ubuntu, I had to do the same thing, but use a shell script with SCP and SSH instead. SCP pulls the files from the email server, and I then use SSH to clean up the files once I have them copied. The problem is that when you use SSH or SCP you are normally prompted with a password right?

Well to remedy this all you have to do is generate a key pair to use for authentication instead. To do that do the following from a terminal as root (sudo su):
  • ssh-keygen -t rsa
  • ssh-copy-id -i ~/.ssh/id_rsa.pub user@remotehost
If your remote server uses an alternative port for SSH like mine does, you can add the -p option after ssh-copy-id like this:
  • ssh-copy-id -p PORTNUMBER -i ~/.ssh/id_rsa.pub user@remotehost
Please note that when you run ssh-keygen -r rsa just hit enter after all the prompts so no password is necessary. YOU NEED TO MAKE SURE THIS KEY IS SECURED THOUGH. I for one use full disk encryption at home, so this key should be pretty well secured.

Once that is done you can now run SCP or SSH without being prompted for a password. Here are the commands I added to my shell script  to first pull the backup files I wanted, then once I had them downloaded SSH deletes them from the server:
scp -P PORTNUMBER user@remotehost:/bak/*.cpt .
ssh -p PORTNUMBER user@remotehost rm /bak/*.cpt
If you are wondering what the *.cpt extension is, I explained that I first encrypt my backups in a previous post. Also the '.' at the end of the first command assumes you want the files downloaded to you current directory. You need to change that if you want it downloaded somewhere else.

Anyway, now I have my script being run as root weekly via cron on my home computer, and once again I have some peace of mind!



Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | stopping spam