【问题标题】:Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令
【发布时间】:2020-02-15 12:59:57
【问题描述】:

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

【问题讨论】:

    标签: python ssh paramiko shoretel


    【解决方案1】:

    我假设gotoshellhapi_debug=1 不是顶级命令,而是stcli 的子命令。换句话说,stcli 是一种外壳。

    在这种情况下,您需要将要在子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())
    

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2021-05-17
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多