我遇到了通过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.")
类/xxxxxx
中的最终Connect
是启动的远程脚本。
它将打开一个文本响应,等待
你叫什么名字:
我似乎无法找到一种方法,可以从类main.py
中的Connect
文件中将响应正确传递给脚本。
我尝试传递name
作为参数或变量的每一种方式答案似乎都消失了(可能因为它试图在Linux提示符下打印它而不是在bash脚本中)
我认为使用read_until
函数在问题末尾查找:
可能会有效。
建议?
答案 0 :(得分:0)
将您的命令所需的输入写入stdin
:
stdin, stdout, stderr = self.client.exec_command(command)
stdin.write(name + '\n')
stdin.flush()
(您当然需要将name
变量从module
传播到sendCommand
,但我认为您知道该如何做到这一点。