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

一笑奈何 提交于 2019-12-19 10:57:47

问题


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')

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

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")

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.


回答1:


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.

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\n')
stdin.write('hapi_debug=1\n')
stdin.flush()

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\n).

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


来源:https://stackoverflow.com/questions/58452390/execute-subcommands-in-secondary-shell-command-on-ssh-server-in-python-paramik

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!