首页 > 解决方案 > 在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令

问题描述

我在使用 ShoreTel 语音开关时遇到问题,我正在尝试使用 Paramiko 跳进去并运行几个命令。我认为问题可能在于 ShoreTel CLI 提供的提示与标准 Linux 不同$。它看起来像这样:

server1$:stcli
Mitel>gotoshell
CLI>  (This is where I need to enter 'hapi_debug=1')

Python 还在期待$,还是我错过了其他东西?

我认为这可能是一个时间问题,所以我把它们放在time.sleep(1)命令之间。好像还是不接。

import paramiko
import time

keyfile = "****"
User = "***"
ip = "****"

command1 = "stcli"
command2 = "gotoshell"
command4 = "hapi_debug=1"

ssh = paramiko.SSHClient()
print('paramikoing...')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname = ip, username = User, key_filename = keyfile)
print('giving er a go...')
ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(command1)
time.sleep(1)
stdin, stdout, stderr = ssh.exec_command(command2)
time.sleep(1)
stdin, stdout, stderr = ssh.exec_command(command4)
time.sleep(1)
print(stdout.read())

ssh.close()

print("complete")

我对成功执行此代码的期望是hapi_debug级别为 1。这意味着当我 SSH 进入该事物时,我会看到那些 HAPI 调试正在填充。当我这样做时,我看不到那些调试。

标签: pythonsshparamikoshoretel

解决方案


我假设gotoshellandhapi_debug=1不是顶级命令,而是stcli. 换句话说,它stcli是一种外壳。

在这种情况下,您需要将要在 subshel​​l 中执行的命令写入其stdin

stdin, stdout, stderr = ssh.exec_command('stcli')
stdin.write('gotoshell\n')
stdin.write('hapi_debug=1\n')
stdin.flush()

如果您stdout.read之后调用,它将等到命令stcli完成。它从不做什么。如果您想继续阅读输出,您需要发送一个终止子 shell 的命令(通常是exit\n)。

stdin.write('exit\n')
stdin.flush()
print(stdout.read())

推荐阅读