在 Python Paramiko 中的 SSH 服务器上的辅助 shell/command 中执行(子)命令

Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko

我在使用 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 调试正在填充。当我这样做时,我没有看到那些调试。

我假设 gotoshellhapi_debug=1 不是顶级命令,而是 stcli 的子命令。换句话说,stcli 有点像 shell.

在那种情况下,您需要将子shell中要执行的命令写入其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())