python - 使用 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
函数:
在问题末尾查找可能会起作用。
建议?
解决方案
将您的命令需要的输入写入stdin
:
stdin, stdout, stderr = self.client.exec_command(command)
stdin.write(name + '\n')
stdin.flush()
(您当然需要将name
变量从module
to传播sendCommand
,但我假设您知道如何执行该部分)。
推荐阅读
- swift - 带有数组的 SwiftUI 动画形状
- python - 如何修复搜索路径上的放大错误?
- maven - 如何配置 Android Studio 以在项目中包含包含 pom.xml 的配置文件夹?
- function - 如何将字符串数组传递给函数并在 SQL 的“IN”语句中使用它
- python - 数据框唯一项目和 xy 位置到室友(共享位置)项目网格
- angular - Angular 9 ngx-image-cropper 使用滑块调整裁剪器大小
- java - 将字符串转换为键值对并在java中将其转换为一行
- python - 如何为误差线分配颜色?[Matplotlib]
- laravel - 如何使用 Laravel 进行多用户进程?
- css - 为什么我的 Angular 应用程序没有拿起可动手做的 CSS?