使用scp在服务器之间实现自动备份

背景:

(1)工作时的代码都在放在服务器上

(2)服务器不稳定,随时可能当机

 

所以决定写个shell脚本,自动(每天凌晨)将client服务器上指定的文件夹打包,然后复制到另外一台服务器server上的指定目录下。

话不多说,上代码:

 1 #/bin/sh
 2 
 3 #usage
 4 #(1)modify line 10 to line 14 of this script, provide necesary information
 5 #(2)./backup.11 install
 6 #(3)just enjoy it!
 7 
 8 #information you must provide
 9 #local directory that should be backup and uploaded
10 local_files=("/home/raozhengfeng/work/DEV-ICG-z.rao/ADV_PRJ/SCRC_SL/ICG_Prj/DEV/z.rao/MIS" "/home/raozhengfeng/work/NB-projects")
11 remote_host=109.119.20.11
12 remote_user=raozhengfeng
13 #directory on remote server to store bakcup files, which MUST be existed
14 remote_directory=/home/raozhengfeng/233/
15 
16 install()
17 {
18         add_cron
19         prepare_ssh
20 }
21 
22 #generate ssh-key and upload to remote host, so we can use 'scp' util without password
23 prepare_ssh()
24 {
25         if [ -e "~/.ssh/id_rsa.pub" ]; then
26                 echo "XXXXXXXXXXXXXXXXXXX"
27         else
28                 ssh-keygen -b 1024 -t rsa -N "" -f ~/.ssh/id_rsa
29         fi
30 
31         scp ~/.ssh/id_rsa.pub $remote_user@$remote_host:/home/$remote_user/.ssh/authorized_keys
32 }
33 
34 #add this script to cron
35 add_cron()
36 {
37         echo "1 10 * * * "`pwd`"/$0" > $0.cron
38         crontab $0.cron
39 }
40 
41 #tar and upload local files to remote host
42 backup()
43 {
44         for _f in ${local_files[@]}
45         do
46                 echo $_f
47                 #if necessary, we can name the archived file with date
48                 tar czf $_f.tar.gz $_f
49                 scp $_f.tar.gz $remote_user@$remote_host:$remote_directory
50         done
51 }
52 
53 if [ $# -gt 0 ]; then
54         if [ $1 = "install" ]; then
55                 echo "Installing..."
56                 install
57                 exit
58         fi
59 fi
60 
61 backup

 

使用方法见代码注释。

转载于:https://www.cnblogs.com/chutianyao/archive/2012/11/01/2750021.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值