Python 子进程,将 rsync 与 ssh 密钥文件一起使用,方法调用出错

Python Subprocess, using rsync with ssh key file, error with method Call

我得到了从远程服务器同步数据文件的命令,我正在使用 ssh 密钥文件作为身份验证方法。我在 bash 中的原始命令是:

rsync -az -e 'ssh -i my_key.pem' admin@192.168.0.10:/export/home/admin/monitor_dir/monitor_srv1.dat .

这很好用,它传输了文件,但是当我尝试使用 Python 子进程库方法调用时,从这个 python bash 命令到 运行 ] 脚本。

#!/usr/bin/python 
import subprocess

server = ['192.168.0.10', '/export/home/admin/monitor_dir/', 'srv1']

subprocess.call(['rsync', '-az', '-e', '\'ssh', '-i', 'my_key.pem\'', 'admin@{0}:{1}monitor_{2}.dat'.format(server[0],server[1],server[2]), '.'])

这是显示的错误:

rsync: link_stat "/Users/works/LUIS/scripts_py/my_key.pem'" failed: No such file or directory (2)

rsync: link_stat "/Users/works/LUIS/scripts_py/admin@192.168.0.10:/export/home/admin/monitor_dir/monitor_srv1.dat" failed: No such file or directory (2)

rsync error: some files could not be transferred (code 23) at /BuildRoot/Library/Caches/com.apple.xbs/Sources/rsync/rsync-51/rsync/main.c(996) [sender=2.6.9]

我尝试了方法 运行 也调用了,但我不知道我做错了什么,或者即使有另一种方法可以使用 python 执行 rsync 命令?

我正在使用:

-Python 3.5.0
-GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)
-rsync  version 2.6.9  protocol version 29
rsync -az -e 'ssh -i my_key.pem' ...

当您从 shell 进行 运行 rsync 时,单引号是 shell 将字符串 ssh -i my_key.pem 视为单个命令行参数的语法,而不是由空格分隔的三个参数。当您的 shell 调用 rsync 程序时,rsync 将具有以下命令行参数列表:

rsync
-az
-e
ssh -i my_key.pem
...

在python版本中:

subprocess.call(['rsync', '-az', '-e', '\'ssh', '-i', 'my_key.pem\'', ...

您正在将这些命令行参数传递给 rsync:

rsync
-az
-e
'ssh
-i
my_key.pem'

这里不需要转义引号——原文中的引号是 shell 语法,你没有使用 shell 在此处调用 rsync。你想像这样调用 rsync:

subprocess.call(['rsync', '-az', '-e', 'ssh -i my_key.pem', ...

至于这个错误:

rsync: link_stat "/Users/works/LUIS/scripts_py/admin@...

这可能是另一个错误的副作用。 Rsync 已决定尝试执行本地-> 远程复制而不是远程-> 本地复制,并且它尝试将 "admin@..." 参数解释为本地文件名。