使用 Python Paramiko 通过 SSH 将 input/variables 传递给 command/script

Pass input/variables to command/script over SSH using Python Paramiko

我在通过 SSH 向远程服务器上的 bash 脚本传递响应时遇到问题。

我正在 Python 3.6.5 中编写一个程序,它将通过 SSH 连接到远程 Linux 服务器。 在这个远程 Linux 服务器上有一个 bash 脚本,我是 运行,它需要用户输入来填写。无论出于何种原因,我无法传递来自原始 [=44= 的用户输入] 通过 SSH 编程并让它填写 bash 脚本用户输入问题。

main.py

from tkinter import *
import SSH

hostname = 'xxx'
username = 'xxx'
password = 'xxx'

class Connect:
    def module(self):
        name = input()
        connection = SSH.SSH(hostname, username, password)
        connection.sendCommand(
            'cd xx/{}/xxxxx/ && source .cshrc && ./xxx/xxxx/xxxx/xxxxx'.format(path))

SSH.py

from paramiko import client

class SSH:

    client = None

    def __init__(self, address, username, password):
        print("Login info sent.")
        print("Connecting to server.")
        self.client = client.SSHClient()    # Create a new SSH client
        self.client.set_missing_host_key_policy(client.AutoAddPolicy())
        self.client.connect(
            address, username=username, password=password, look_for_keys=False) # connect

    def sendCommand(self, command):
        print("Sending your command")
        # Check if connection is made previously
        if (self.client):
            stdin, stdout, stderr = self.client.exec_command(command)
            while not stdout.channel.exit_status_ready():
                # Print stdout data when available
                if stdout.channel.recv_ready():
                    # Retrieve the first 1024 bytes
                    alldata = stdout.channel.recv(1024)
                    while stdout.channel.recv_ready():
                        # Retrieve the next 1024 bytes
                        alldata += stdout.channel.recv(1024)


                    # Print as string with utf8 encoding
                    print(str(alldata, "utf8"))
        else:
            print("Connection not opened.")

class中最后的/xxxxxxConnect是启动的远程脚本。 它将打开一个文本响应,等待

等格式

What is your name:

而且我似乎无法找到一种方法将响应从 class Connect.

中的 main.py 文件正确传递给脚本

我尝试将 name 作为参数或变量传递的每一种方式,答案似乎都消失了(可能是因为它试图在 Linux 提示符下而不是在bash 脚本)

我认为使用 read_until 函数查找问题末尾的 : 可能有效。

建议?

将您的命令需要的输入写入 stdin:

stdin, stdout, stderr = self.client.exec_command(command)
stdin.write(name + '\n')
stdin.flush()

(您当然需要将 name 变量从 module 传播到 sendCommand,但我假设您知道如何执行该部分)。