SCP 通过 Python 子进程 Popen:“身份文件无法访问”

Mr.*_*ris 2 python subprocess scp popen python-3.x

从 subprocess.popen 执行 SCP 时,我收到错误:Warning: Identity File ./id_rsa.key not accessible: no such file or directory. 问题解释如下。

我想使用 python 脚本将文件从本地计算机 SCP 到远程计算机,并且我想指定执行 SCP 时使用的密钥(使用 -i 选项)。

我的本地计算机是 Windows 10 企业版。我的“远程”机器目前是一个在我的本地主机上运行 Alpine linux 的 Docker 容器。

当我在提升的 shell 中运行该命令时,它可以工作:

scp -i ./id_rsa.key -P 2222 ./test.plan root@127.0.0.1:/go/
Run Code Online (Sandbox Code Playgroud)

当我通过 Python 3.6 subprocess.popen 执行命令时:

SSH = subprocess.Popen(['scp', '-i ./id_rsa.key', '-P 2222', './test.plan', 'root@127.0.0.1:/go/'],
    cwd = r'C:\ThePathToThisStuff',
    shell = False,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)
Run Code Online (Sandbox Code Playgroud)

它提示我输入密码,root@127.0.0.1's password:当我输入密码时,它会抛出以下错误,表明它无法找到 RSA 密钥:

<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'> ERROR: [b'Warning: Identity file  ./id_rsa.key not accessible: No such file or directory.\n']
Run Code Online (Sandbox Code Playgroud)

我尝试提供键的绝对路径,将参数列表中的每个命令分为选项和值、不同的分组等。

Bar*_*mar 5

您不应将选项及其参数组合在同一参数中,它们需要是单独的列表元素。

SSH = subprocess.Popen(['scp', '-i', './id_rsa.key', '-P', '2222', './test.plan', 'root@127.0.0.1:/go/'],
Run Code Online (Sandbox Code Playgroud)