使用SCP和Cron进行数据备份

服务器间的数据同步,rsync的确是个好方式,不过它只能被动同步而不能主动分发。

本想使用SVN+rsync的方案进行代码的管理,可是因为上面说到的原因,无法达到代码的即时分发。

遂想起SCP这个东西,但SCP每次执行必须要在控制台输入手动输入密码,于是就Google到了下面这个文章。

人家说的是用SCP进行数据备份,我是用来跟SVN的hook功能一起达到即时分发代码的目的,原理是一样的。

实在懒的翻译了,文章来自:http://www.spaceprogram.com/knowledge/cron_scp.html

Introduction

This document will explain the steps required to use scp in cron. This is generally useful to do automated backups on Linux and other nix variations.

Instructions

These instructions will walk you through what it takes.

1. Generate a private/public key pair

Simple command to do this:

ssh-keygen -t rsa

Leave the passphrase empty so that cron can use it passwordless. Just be sure nobody gets your private key.

2. Copy the public key to the remote server

scp ~/.ssh/id_rsa.pub remote_host:

3. Add local key to remote servers trusted key

Log on to the remote server and if there has never been a key created for this user on the remote machine, run the ssh-keygen -t rsa just to get the key directory and stuff set up.

Then concatenate the new key to your authorized_keys file:

cat ~/id_rsa.pub >> ~/.ssh/authorized_keys

Now for some reason, you may have to do this to the keys file:

chmod 644 ~/.ssh/authorized_keys

4. Now try logging into the remote machine again from local

ssh REMOTE_USERNAME@remote_host

This should log you in without asking for a password. If it doesn’t, then something must be wrong at this point and you should go through the steps above again.

This should also mean that scp will work the same way and you might want to test that scp works by copying a file from local to remote using scp. If no password, then we’re all good.

5. Now lets test out cron script

My cron script for this example is simply going to copy a directory of files using scp to the remote server.

scp -r /PATH_TO_FILES/ REMOTE_USER@remote_host:BACKUPS/

And that’s about all she wrote. Save that in a file called backup.sh (or whatever you want to call it), chmod 755 i it and then try running it. ./backup.sh to run it. If it works, then next stop is to cron it.

6. Add script to cron jobs

Easiest way is to simply copy the backup.sh file into /etc/cron.daily/ . This will make it run every day. Choose another cron.SOMETIME to make it run more or less often. If you want more control on when it’s run, read up on adding it to the crontab.

发表评论

邮箱地址不会被公开。 必填项已用*标注