python - 在交互式 ssh 模式下调用进程内的多个命令
问题描述
我开始使用 paramiko 从计算机上的 python 脚本调用服务器上的命令。
我写了以下代码:
from paramiko import client
class ssh:
client = None
def __init__(self, address, port, username="user", password="password"):
# Let the user know we're connecting to the server
print("Connecting to server.")
# Create a new SSH client
self.client = client.SSHClient()
# The following line is required if you want the script to be able to access a server that's not yet in the known_hosts file
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
# Make the connection
self.client.connect(address, port, username=username, password=password, look_for_keys=False)
def sendcommand(self, command):
# Check if connection is made previously
if self.client is not None:
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
_data = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
_data += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(_data, "utf8"))
else:
print("Connection not opened.")
def closeconnection(self):
if self.client is not None:
self.client.close()
def main():
connection = ssh('10.40.2.222', 2022 , "user" , "password")
connection.sendcommand("cd /opt/process/bin/; ./process_cli; scm")
print("here")
#connection.sendcommand("yes")
#connection.sendcommand("nsgadmin")
#connection.sendcommand("ls")
connection.closeconnection()
if __name__ == '__main__':
main()
现在,我发送到服务器 (scm) 的命令中的最后一个命令是一个命令,它应该发送到我在服务器中运行的进程“process_cli”,并且应该打印出进程的输出(进程从服务器外壳的标准输入获取输入并将输出打印到服务器外壳的标准输出)。
当我在交互模式下运行时一切正常,但是当我运行脚本时,我成功连接到我的服务器并在该服务器上运行所有基本 shell 命令(例如:ls、pwd 等),但我无法运行任何命令在此服务器内部运行的进程上。
我该如何解决这个问题?
解决方案
SSH“exec”通道(由 使用SSHClient.exec_command
)在单独的 shell 中执行每个命令。作为结果:
cd /opt/process/bin/
对 完全没有影响./process_cli
。scm
将作为 shell 命令执行,而不是作为process_cli
.
你需要:
执行
cd
和process_cli
作为一个命令(在同一个 shell 中):stdin, stdout, stderr = client.exec_command('cd /opt/process/bin/ && ./process_cli')
或者
stdin, stdout, stderr = client.exec_command('/opt/process/bin/process_cli')
将 的(子)命令馈送
process_cli
到其标准输入:stdin.write('scm\n') stdin.flush()
类似的问题:
推荐阅读
- css - 为什么这个 css 值无效?
- sql - Azure devops 中的预览工作项附件可以不是图像吗?
- sql-server - Cloud Run 完全托管连接到 Cloud SQL:这是否支持 SQL Server?
- javascript - Grunt 将许多 v= 添加到文件名
- entity-framework - 由多个项目组成的 MVC 解决方案的 TFS 分支和合并
- html - 当我将鼠标悬停在图像上时,图像与导航栏重叠
- php - 按两个字段排序对象数组,日期和顺序
- python - 将列表中的变量放入字符串(url代码)
- mysql - 是否可以获得日期时间字段的时区?
- javascript - 用于更改请求对象的单元测试 Express 中间件