这是一个老问题,但在搜索“rsync over paramiko”时仍然是 Google 中的第一个热门问题,这里唯一被投票赞成的项目是与 OP 的问题无关的评论(该评论中的链接指向使用 Paramiko 不支持的 ControlMaster)。
在其中一个 Paramiko 演示 here 中有一个如何设置本地端口转发的示例。在pull request 中还有一个更易于使用的版本。您可以通过两种方式使用本地端口转发:
- 使用 ssh 协议通过本地端口将 ad-hoc 本地端口转发到远程 ssh 服务器和
rsync。这相当于运行 ssh -L12345:localhost:22 remote-host 后跟 rsync --rsh 'ssh -p 12345' sourcedir/file localhost:/destdir/file。
- 使用 rsync 协议通过本地端口将 ad-hoc 本地端口转发到 ad-hoc 远程 rsync 守护程序和
rsync。这类似于运行ssh -L12345:localhost:12345 后跟rsync sourcedir/file rsync://localhost:12345/module/destdir/file,不同之处在于您需要设置一个在12345 上运行的临时rsync 守护进程,其模块名称指向远程主机上的destdir。
我个人更喜欢上面的第二种方法,虽然它稍微复杂一些,因为它跳过了本地 ssh 客户端,并且还使用了我认为比使用 ssh 更有效的 rsync 协议。
使用上述拉取请求中的ForwardServer,代码看起来有点像这样(取决于Fabric):
RSYNC_SPEC = """
port=12345
use chroot=false
[homedir]
log file=/tmp/rsync-ad-hoc.log
max verbosity=4
path=/home/{user}/
read only=false
"""
@task
def rsync(local_path, remote_path):
"""
local_path: Absolute path to a local source
remote_path: Relative path (from home directory) to a remote destination
"""
with ForwardServer(0, "localhost", rsync_port, connections[env.host_string].get_transport()) as serv:
local_port = serv.socket.getsockname()[1]
run("killall rsync; rm -f /tmp/rsync-ad-hoc.log /tmp/rsync-ad-hoc.conf; :")
put(local_path=StringIO(RSYNC_SPEC.format(user=env.user)), remote_path="/tmp/rsync-ad-hoc.conf", )
run("rsync --daemon --config /tmp/rsync-ad-hoc.conf")
remote_rsync_path = os.path.join("rsync://localhost:%s/homedir" % local_port, remote_path)
# Rsync expects the root of the destination to exist.
run("mkdir -p /home/{user}/{path}".format(user=env.user, path=remote_path))
logging.info("Attempting rsync from (localhost, %s, %s) to (%s, %s, %s)", local_port, local_path, env.host_string, rsync_port, remote_path)
local("rsync -avzPh --delete %s/ %s/" % (local_path, remote_rsync_path))
您还可以让函数采用远程绝对路径并为模块生成目录(而不是假设它是相对于用户的主目录)。