You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本中rsync执行失败:change_dir报错无此文件或目录

问题:Python调用rsync报错但终端执行正常

我需要在Python脚本中使用rsync将某个目录及其所有内容传输到远程主机,但遇到以下错误:

building file list ... 
rsync: change_dir "/home/xxxx//xxxx/xxxx/ root@xx.xx.xx.xx:/opt/customized" failed: No such file or directory (2)
done

sent 20 bytes  received 11 bytes  62.00 bytes/sec
total size is 0  speedup is 0.00
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1183) [sender=3.1.1]

我使用的Python命令如下:

HOST_PASSWORD="xxxx"
filepath="xxxx/xxxx/"
ip="xx.xx.xx.xx"
DEPLOY_DIR="/opt/customized/"
subprocess.call(['rsync', '-Kavz', '--exclude=*.py', '--chown=root:root','--delete-after','--rsh="/usr/bin/sshpass -p {} ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -l root"'.format(HOST_PASSWORD),'{} root@{}:{}'.format(filepath, ip, DEPLOY_DIR)])

但在终端中执行以下rsync命令却完全正常:

rsync -Kavz --exclude=*.py --chown=root:root --delete-after --rsh="/usr/bin/sshpass -p xxxx ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -l root" xxxx/xxxx/ root@xx.xx.xx.xx:/opt/customized/

请问我的Python脚本哪里出了问题?谢谢!


问题原因与解决办法

错误1:--rsh参数多余的引号

在subprocess的列表式参数中,不需要给--rsh的取值加双引号。终端里的引号是用来告诉shell把整个内容当成一个参数,但subprocess直接传列表时,每个元素就是一个独立参数,加引号会被rsync当成命令的一部分,导致路径解析错误。

错误2:源路径与目标路径被合并为一个参数

你把源路径和目标路径合并成了一个字符串作为subprocess的单个参数,但实际上这两个路径需要是两个独立的参数,和终端里的写法一致。

修正后的Python代码

import subprocess

HOST_PASSWORD="xxxx"
filepath="xxxx/xxxx/"
ip="xx.xx.xx.xx"
DEPLOY_DIR="/opt/customized/"
subprocess.call([
    'rsync', 
    '-Kavz', 
    '--exclude=*.py', 
    '--chown=root:root',
    '--delete-after',
    '--rsh=/usr/bin/sshpass -p {} ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -l root'.format(HOST_PASSWORD),
    filepath, 
    'root@{}:{}'.format(ip, DEPLOY_DIR)
])

内容的提问来源于stack exchange,提问作者Henry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 04:07:06