OS X / LINUX使用RSYNC拷贝远程服务器文件到本地 译注本文翻译自 biodegradablegeek.com 的 Linux 专栏。2026 编者注文章写于 2015 年命令本身到今天依然有效补充两点现代环境的变化见文末。一、Rsync 是什么下边部分的代码使用 Rsync 从远程服务器拷贝文件到本地机器从而使本地和远程服务器的文件保持同步。这是一个备份 web 服务器重要目录到外部硬盘或者其他什么地方的有用技巧。The following is used to copy files from a remote server to your local machine using Rsync to keep both synchronized. This is useful for things like backing up important directories on your web server to your external hard drive or elsewhere.Rsync 可以在本地和远程服务器之间文件增量备份也就是说只同步你的远程服务器上更新了的文件到本地服务器。Rsync can incrementally synchronize files between two locations whether local or remote. This means only the updated files on your remote server are updated on your local machine.二、同步脚本从接下来的部分我假设你和我一样也是使用 OS X但是这个脚本应该也能在 Linux 工作。首先需要打开一个控制台就是那个令人讨厌的黑框框在命令行的提示符下输入以下的代码From here on in I assume youre using OS X but this should work on Linux as well. Press CMDSpace to open a Terminal. At the command prompt, just use the following:#!/bin/sh rsync -a -e ssh --rsync-pathsudo rsync -vau remoteusernameremote.host.com:/home . rsync -a -e ssh --rsync-pathsudo rsync -vau remoteusernameremote.host.com:/var . rsync -a -e ssh --rsync-pathsudo rsync -vau remoteusernameremote.host.com:/etc .这个脚本执行的结果是拷贝你远程服务器的/home、/var、/etc目录到当前目录。This will copy /home, /var, and /etc from your remote machine to the current directory.命令拆解参数作用-a归档模式保留权限、时间戳、软链接等-e ssh走 SSH 通道传输加密--rsync-pathsudo rsync -vau 远端用 sudo 执行 rsync读取需要 root 权限的目录remoteusernameremote.host.com:/home源远端的 /home.目标本地当前目录三、放进脚本执行可以把上述的代码拷贝到一个文件命名成rsyncRemote.sh并使用下述的命令执行# should under same directory with rsyncRemote.sh chmod ax rsyncRemote.sh ./rsyncRemote.sh四、2026 补充macOS 自带的 rsync 已过时2.6.92006 年的版本。建议brew install rsync新版支持--infoprogress2等实用参数增量算法也更快SSH 默认禁用了密码交互的趋势现在更推荐配 SSH key 免密登录rsync会自动走密钥认证不用每次输密码。远端 sudo 也可以改用/etc/sudoers.d/里限定命令的 NOPASSWD 规则比全局 sudo 更安全。命令逻辑没变这篇 2015 年的小技巧今天依然能直接用。相关本站的 C 系统编程与网络系列在专栏持续更新。