对linux 来说,要实现自动备份数据并不难,但要实现远程数据安全地自动备份就有点麻烦了.

这次,我用了Linux的SSH和Crond进行远程数据备份.

要考虑到安全因素,那么就得有验证.在程序自动运行过程中,不可能向人一样输入用户名,等待提示后再输入密码,但是不输入密码又无法确保安全,ssh有另一种用密钥对来验证的方式,这次,我们就用这个办法来实现验证.

1.生成密匙对

[user1@rh user1]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user1/.ssh/id_rsa):
Created directory '/home/user1/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user1/.ssh/id_rsa.
Your public key has been saved in /home/user1/.ssh/id_rsa.pub.
The key fingerprint is:
e0:f0:3b:d3:0a:3d:da:42:01:6a:61:2f:6c:a0:c6:e7 user1@rh.test.com

生成的公共密匙为:~/.ssh/id_rsa.pub
私有密钥为 ~/.ssh/id_rsa

2.把公共密匙拷到目标机器上去,保存为:
~/.ssh/authorized_keys(默认是整个文件名,可以在/etc/sshd/sshd_config里修改)

3.用SSH登陆测试,是否不输入密码就可以登陆

ssh -i ~/.ssh/id_rsa <用户名>@<目标IP>

第一次需要键入yes ,以后就不需要在键入任何东西就可以登陆了.

4.下面是简单的自动备份SHELL脚本
源数据服务器:

  1. #!/bin/sh
  2. date=$(/bin/date +"%Y%m%d")
  3. backupdir="<directory>"
  4. scp $backupdir/<directory>/"$date"_sql.tar.gz <user>@<IP>:<directory>/"$date"_sql.tar.gz
  5. ssh <user>@<IP> "touch <directory>/finished.test"

备份服务器:

#!/bin/sh
cd <dir>
date=$(/bin/date --date '1 days ago' +"%Y%m%d")
del_date=$(/bin/date --date '5 days ago'  +"%Y%m%d")
if [ -f ./finished.test ]&&[ -f ./"$date"_sql.tar.gz ]
then
 
tar xvzf <dir>/"$date"_sql.tar.gz -C <dir>/
 
mv ./finished.test ./finished_$date
 
rm "$del_date"_sql.tar.gz -f
 
rm finished_"$del_date" -f
 
rm nofinsh_$date -f
else
 
rm ./finished_$date -f
 
rm ./finished.test -f
 
touch nofinsh_$date
fi

5.最后在crontab上设置好自动运行时间就可以了.