2
votes

My goal is to be able to SSH into a device, execute CLI command which will take me to another Shell where I can enter in my commands. Currently, I am able to successfully SSH into a device, but cannot figure out how to get to that secondary shell with the CLI. My code below

import datetime, logging, os, paramiko, re, scp, sys, time, socket, logging

SSH = paramiko.SSHClient()
SSH.set_missing_host_key_policy(paramiko.AutoAddPolicy())
SSH.connect(server, username=usr, password=password, port=22, timeout=2)
print('successful ssh')
stdin, stdout, stderr = SSH.exec_command('cli console',bufsize=2)
# inBuf = stdout.readlines()
# for line in inBuf:
    # print(line.strip('\n'))

SSH.close()

My initial assumption is that after executing the cli to get into the shell console, I would be able to just simply execute whatever command I want but that is not the case. Any help would be appreciated

1
This really depends on the device, or rather, its SSH server implementation. It may not support exec_command() at all; does ssh your-device 'cli console' work, or do you need to run ssh your-device and then run cli console after? - Charles Duffy
If the latter, then this is probably a job for pexpect. See paramiko-expect for some glue that may make this easier. - Charles Duffy
Could you please elaborate? I read some documents on paramiko-expect and am not sure how it would be of much use. - bfan
The key difference is whether exec_command() or invoke_shell() is in use. Usually, when someone is having trouble interacting with a minimal embedded SSH server the issue is that that server doesn't support (the protocol-level functionality behind) exec_command() at all, but only supports invoke_shell(), so you need to send multiple commands over a single session -- hence needing an expect-style pattern-matching mechanism, rather than being able to get a channel per remote command. - Charles Duffy

1 Answers

0
votes

Write the commands that you want to execute in the subshell to the stdin:

stdin.write('command\n')
stdin.flush()