为什么无法从Python调用SSH终端命令?

问题描述 投票:1回答:1

我正在尝试通过SSH将文件复制到我的Raspberry pi,我想从python执行Windows终端命令,因此以后可以将其自动化。但是,每次尝试执行它都会收到错误。当我手动将SSH命令放入控制台时,它会按预期工作,但从此脚本中调用它时,它将无法工作。我以前从未在python中调用过控制台命令,因此我正在尝试使用发现的其他一些线程。我可能做错了什么?我还尝试过运行os.system,该操作未返回错误,但是也没有执行应有的命令。我正在使用Python 3.8.1。这是我的脚本和错误,感谢您的帮助。

代码:

import subprocess

subprocess.run(['scp <text file path> pi@<IP>:here/'])
print ("done")

错误

Traceback (most recent call last):
  File "<script file path>.py", line 3, in <module>
    subprocess.run(['scp <text file path>.txt pi@<IP>:here/'])
  File "<python file path>\Python38-32\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File <python file path>\Python38-32\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File <python file path>\Python38-32\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

编辑:这是我按如下所示拆分一系列命令时遇到的错误:

代码:

import subprocess

subprocess.run(['scp', '<text file path>.txt', 'pi@<IP>:here/'])
print ("done")

错误:

Traceback (most recent call last):
  File "<script file path>.py", line 3, in <module>
    subprocess.run(['scp', '<text file path>.txt', 'pi@<IP>:here/'])
  File "<python file path>\Python38-32\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "<python file path>\Python38-32\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File <Python file path>\Python38-32\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

当然,我放入<>的所有内容都是为了保护我的信息。

编辑:运行方法:enter image description here

python shell ssh command-line subprocess
1个回答
0
投票

要么删除列表,然后让shell解析字符串

import subprocess

subprocess.run('scp <text file path> pi@<IP>:here/', shell=True)
print ("done")

或您自己将命令拆分为其组成部分

import subprocess

subprocess.run(['scp', <text file path>, 'pi@<IP>:here/'])
print ("done")

关于您的错误,<text file path>是相对错误的相对路径(鉴于当前工作目录),或者scp不在您的PATH中。从错误消息中看不到找不到哪个文件。

© www.soinside.com 2019 - 2024. All rights reserved.