如何使用 python 在远程服务器中执行命令?

How to execute commands in a remote server using python?

这个问题与另一个问题相关:

我想连接到开发板以执行脚本。我想将该脚本的所有输出发送到 Elasticsearch 机器。

我可以使用恰好安装了 Elasticsearch 的笔记本电脑连接到开发板(参见下图)。但是,当我想将数据发送到开发板时,脚本什么也没显示。 我正在做的是:

我做错了什么?

import paramiko
import os

#Server's data
IP = '172.16.2.47'
PORT = 22
USER = 'mendel'
PASSWORD = 'mendel'


ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = IP, port=PORT, username = USER, password = PASSWORD)

channel = ssh.invoke_shell() #to get a dedicated channel

channel_data = str()
host = str()

while True:
    if channel.recv_ready(): #is there data to be read?
       channel_data += channel.recv(9999).decode("utf-8")
       os.system('clear')
       print(channel_data)

#ONLY WORKS UNTIL HERE!!!

    else:
        continue

    if channel_data.endswith('mendel@undefined-eft:~$'):
        channel.send('cd coral/tflite/python/examples/classification/Auto_benchmark\n')
        channel_data += channel.recv(9999).decode("utf-8")
        print(channel_data)

图像

编辑

channel = ssh.invoke_shell() #to get a dedicated channel

channel_data = str()
host = str()

while True:
    if channel.recv_ready(): #is there data to be read?
       channel_data += channel.recv(9999).decode("utf-8")
       os.system('clear')
       print(channel_data)

    else:
        continue

    if channel_data.endswith('mendel@undefined-eft:~$ '):#it is good to send commands
       channel.send('cd coral/tflite/python/examples/classification/Auto_benchmark\n')
       #channel_data += channel.recv(9999).decode("utf-8")
       #print(channel_data)
    elif channel_data.endswith('mendel@undefined-eft:~/coral/tflite/python/examples/classification/Auto_benchmark$ '):
         channel.send('ls -l\n') #python3 auto_benchmark.py')
         channel_data += channel.recv(9999).decode("utf-8")
         print(channel_data)

我想你必须改变

if channel_data.endswith('mendel@undefined-eft:~$'):

if channel_data.endswith('mendel@undefined-eft:~$ '):

根据您的提示。请注意:~$

后的space