首页 > 解决方案 > 使用 Python Paramiko 通过 SSH 将输入/变量传递给命令/脚本

问题描述

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

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

主文件

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.")

/xxxxxx类中的最后一个Connect是启动的远程脚本。它将打开一个等待格式的文本响应,例如

你叫什么名字:

而且我似乎找不到一种方法来正确地将响应从我main.py的类中的文件传递给脚本Connect

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

我认为使用该read_until函数:在问题末尾查找可能会起作用。

建议?

标签: pythonlinuxbashsshparamiko

解决方案


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

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

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


推荐阅读