我在通过 SSH 将响应传递到远程服务器上的 bash 脚本时遇到问题。
我正在用 Python 3.6.5 编写一个程序,它将通过 SSH 连接到远程 Linux 服务器。 在这个远程 Linux 服务器上,我正在运行一个 bash 脚本,需要用户输入才能填写。无论出于何种原因,我无法通过 SSH 传递来自原始 python 程序的用户输入并让它填写 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.")
Connect 类中的最后一个 /xxxxxx
是启动的远程脚本。
它将打开一个文本响应,等待诸如
What is your name:
而且我似乎无法找到一种方法来正确地将响应从 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
,但我假设您知道如何做那部分)。
关于python - 使用 Python Paramiko 通过 SSH 将输入/变量传递给命令/脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57890121/