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

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

Leave a Comment