gpt4 book ai didi

python - rsync over ssh - 使用 Paramiko 在 Python 中创建的 channel

转载 作者:太空狗 更新时间:2023-10-29 23:59:39 25 4
gpt4 key购买 nike

我想使用 rsync 和 SSH(在 Python 程序中)从远程机器获取文件。

如何启动一个本地的rsync实例并将其引入我用Paramiko打开的SSH channel ?

最佳答案

这是一个老问题,但在搜索“rsync over paramiko”时仍然是谷歌的第一个热门问题,这里唯一被投票的项目是与 OP 的问题无关的评论(该评论中的链接指向使用 Paramiko 不支持的 ControlMaster。

在 Paramiko 演示之一中有一个如何设置本地端口转发的示例 here .在 pull request 中还有一个更易于使用的版本.您可以通过两种方式使用本地端口转发:

  1. 使用 ssh 协议(protocol)通过本地端口将一个临时本地端口转发到远程 ssh 服务器和 rsync。这相当于运行 ssh -L12345:localhost:22 remote-host 后跟 rsync --rsh 'ssh -p 12345' sourcedir/file localhost:/destdir/file .
  2. 使用 rsync 协议(protocol)将 ad-hoc 本地端口转发到 ad-hoc 远程 rsync 守护程序和 rsync。这类似于运行 ssh -L12345:localhost:12345 然后运行 ​​rsync sourcedir/file rsync://localhost:12345/module/destdir/file,除了你需要设置一个在 12345 上运行的临时 rsync 守护进程,其模块名称指向远程主机上的 destdir

我个人更喜欢上面的第二种方法,虽然它稍微复杂一些,因为它跳过了本地 ssh 客户端并且还使用了 rsync 协议(protocol),我认为这比使用 ssh.

使用上述拉取请求中的 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))

您还可以让该函数采用远程绝对路径并为模块生成目录(而不是假设它是相对于用户主目录的)。

关于python - rsync over ssh - 使用 Paramiko 在 Python 中创建的 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16497166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com