rsync 文件同步 Posted on 2020年2月27日 | In Coding ## rsync rsync 是一个远程数据同步工具,可以快速同步多台主机间的文件。rsync使用所谓的“rsync算法”来使本地和远程两个主机之间的文件达到同步,这个算法只传送两个文件的不同部分,而不是每次都整份传送,因此速度相当快。 ### 本地文件同步 `rsync -avH /src/path /dst/path` ### 远程文件同步 - Shell方式 ```shell # 从本地传到远端,目标文件属于ssh登录的用户 rsync -avH /src/path/ www@172.18.50.125:/dst/path # 使用 ssh 加密隧道方式传输 rsync -avHe ssh /src/path/ www@172.18.50.125:/dst/path # 从远端传到本地 rsync -avH www@172.18.50.125:/src/path /dst/path # 如果远程服务器ssh端口不是默认的22 rsync -avHe "ssh -p 11222" /src/path/ www@172.18.50.125:/dst/path ``` ### 远程文件同步 - Daemon方式 #### 远程服务器配置 1. 配置文件 ``` # /etc/rsyncd/rsyncd.conf # sample rsyncd.conf configuration file # GLOBAL OPTIONS #motd file=/etc/rsyncd/rsyncd.motd #log file=/var/log/rsyncd # for pid file, do not use /var/run/rsync.pid if # you are going to run rsync out of the init.d script. # The init.d script does its own pid file handling, # so omit the "pid file" line completely in that case. # pid file=/var/run/rsyncd.pid #syslog facility=daemon #socket options= # MODULE OPTIONS [blog] comment = blog sync path = /var/www/blog read only = no use chroot = yes list = yes uid = root gid = root lock file = /var/lock/rsyncd # exclude = # exclude from = # include = # include from = auth users = username secrets file = /etc/rsyncd/rsyncd.secrets strict modes = yes # hosts allow = # hosts deny = ignore errors = yes ignore nonreadable = yes transfer logging = yes log format = %t: host %h (%a) %o %f (%l bytes). Total %b bytes. timeout = 600 refuse options = checksum dry-run dont compress = *.gz *.tgz *.zip *.z *.rpm *.deb *.iso *.bz2 *.tbz ``` 2. 配置用户名密码 ``` # /etc/rsyncd/rsyncd.secrets # 一行一个,文件权限600,或关闭 strict modes username:password ``` 3. 以 Daemon 方式启动服务端 `rsync --daemon --config=/etc/rsync/rsyncd.conf` #### 客户端命令 1. 从远程向本地同步 `rsync -avzP --delete username@172.18.50.125::module_name /local/path/` 2. 从本地向远程同步 路径末尾有 / 表示同步文件夹内部文件,无 / 表示同步文件夹 `rsync -avzP --delete /local/path/ username@172.18.50.125::module_name` 3. 排除文件 - 排除 filename 文件:`--exclude=filename` - 排除 filename 文件中列出的文件:`--exclude-file=filename` 4. 免密码 `--password-file=password.file` 密码直接写在文件中,无需用户名,注意文件权限需为 600