用Python Parami在secondary shell中执行(sub)命令/SSH服务器上的command

2024-06-13 09:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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调试被填充。当我这样做时,我看不到那些调试。你知道吗


Tags: debug命令paramikoclitimestderrstdinstdout
1条回答
网友
1楼 · 发布于 2024-06-13 09:41:08

我假设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())

相关问题 更多 >