在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令 [英] Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko

查看:32
本文介绍了在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having a problem with a ShoreTel voice switch, and I'm trying to use Paramiko to jump into it and run a couple commands. What I believe the problem might be, is that the ShoreTel CLI gives different prompts than the standard Linux $. It would look like this:

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

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

Is Python still expecting that $, or am I missing something else?

我认为这可能是一个时间问题,所以我将那些 time.sleep(1) 放在命令之间.似乎仍然没有采取.

I thought it might be a time thing, so I put those time.sleep(1) between commands. Still doesn't seem to be taking.

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

What I would expect from the successful execution of this code, would be for the hapi_debug level to be 1. Which means that when I SSH into the thing, I would see those HAPI debugs populating. When I do, I do not see those debugs.

推荐答案

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

I assume that the gotoshell and hapi_debug=1 are not top-level commands, but subcommands of the stcli. In other words, the stcli is kind of a shell.

在这种情况下,您需要将要在子shell中执行的命令写入其stdin:

In that case, you need to write the commands that you want to execute in the subshell to its stdin:

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

<小时>

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


If you call stdout.read afterwards, it will wait until the command stcli finishes. What it never does. If you wanted to keep reading the output, you need to send a command that terminates the subshell (typically exit ).

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

这篇关于在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆