目前工作的公司上线是通过rsync来同步代码的,前公司则是用ftp发布代码到预发布环境然后再用rsync实时同步到线上环境,今天就来看下rsync这个强大的工具
what’s rsync
rsync(remote synchronization)是*nix下一款同步软件,用于远程同步,备份文件,当然也可以本地做同步备份操作。
rsync 可以在中断之后恢复传输;它只传输源文件和目标文件之间不一致的部分;rsync 可以执行完整备份或增量备份。更棒的是,在所有风格的 UNIX 上都可以使用 rsync,包括 Mac OS X,所以很容易连接任何系统。
how to use rsync
shell模式(本地模式)
先来看下目录结构
[root@localhost tmp]# tree -L 2 . ├── rsync1 │ ├── 1.txt │ ├── a.txt │ ├── c.txt │ └── v.txt ├── rsync2 │ └── 1.txt
要将rsync1中的内容完全同步到rsync2中
[root@localhost tmp]# rsync -avz rsync1/ rsync2 sending incremental file list ./ a.txt c.txt v.txt sent 189 bytes received 72 bytes 522.00 bytes/sec total size is 0 speedup is 0.00
远程shell模式
[root@localhost tmp]# rsync -avz rsync1/ root@192.168.22.81:/tmp root@192.168.22.81's password: sending incremental file list ./ 1.txt a.txt c.txt v.txt sent 225 bytes received 91 bytes 9.16 bytes/sec total size is 0 speedup is 0.00
列表模式
[root@localhost tmp]# rsync rsync1/ drwxr-xr-x 4096 2014/02/20 13:42:21 . -rw-r--r-- 0 2014/02/18 16:41:47 1.txt -rw-r--r-- 0 2014/02/20 13:42:21 a.txt -rw-r--r-- 0 2014/02/20 13:42:21 c.txt -rw-r--r-- 0 2014/02/20 13:42:21 v.txt
这个和ll命令是一样的
服务器模式
在rsyncd下有下列rsync服务的配置
[root@localhost rsyncd]# pwd && ll /etc/rsyncd total 12 -rw-r--r-- 1 root root 808 Feb 19 16:21 rsyncd.conf -rw-r--r-- 1 root root 36 Feb 19 15:10 rsyncd.motd -rw------- 1 root root 12 Feb 19 15:10 rsyncd.secrets
rsyncd.conf
是主要配置文件,
pid file = /var/run/rsyncd.pid port = 873 #address = * uid = root gid = root use chroot = yes read only = yes #limit access to private LANs hosts allow=* #hosts deny=* max connections = 5 motd file = /etc/rsyncd/rsyncd.motd #This will give you a separate log file log file = /var/log/rsync.log #This will log every file transferred - up to 85,000+ per user, per sync #transfer logging = yes log format = %t %a %m %f %b syslog facility = local3 timeout = 300 [root_tmpTrans] path = /tmp/rsnctrans list=yes ignore errors auth users = root secrets file = /etc/rsyncd/rsyncd.secrets comment = balabala exclude = .git/ .svn/
rsyncd.secrets
是执行同步、备份的账号,格式为user:password
root:123456
rsyncd.motd
是执行时的欢迎信息(message of the day)
hi---------------------------------
现在我们启动rsync服务
rsync --daemon --config=/etc/rsyncd.conf
现在从另一台机器上看这个守护进程
root@ubuntu:/tmp# rsync 192.168.22.81:: hi--------------------------------- root_tmpTrans balabala
指定模板名称
root@ubuntu:/tmp# rsync 192.168.22.81::root_tmpTrans hi--------------------------------- Password: drwxr-xr-x 4096 2014/02/19 16:43:38 . -rw-r--r-- 0 2014/02/19 15:13:19 a.txt -rw-r--r-- 0 2014/02/19 16:43:38 c.txt -rw-r--r-- 0 2014/02/19 16:37:40 v.txt
注意上面两个例子,访问服务器模式的时候,有两个冒号
此时,直接利用rsync服务器模式,来备份,同步文件,和前面的模式类似
联系上crontab,写好需要的shell脚本,将备份和同步自动话,定时执行,这样就可以应用到更多的场景中。
题外话:1.这篇文章已经在草稿箱躺了2个月了,OMG.2.今天装了markdown插件,第一次用markdown写wordpress,有些地方不是很好用.3.最近心情不好,状态极差.