背景:
(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
使用方法见代码注释。