2

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

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
bfan
  • 55
  • 1
  • 7
  • 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 Jun 05 '18 at 22:16
  • If the latter, then this is probably a job for `pexpect`. See [`paramiko-expect`](https://github.com/fgimian/paramiko-expect) for some glue that may make this easier. – Charles Duffy Jun 05 '18 at 22:16
  • Could you please elaborate? I read some documents on paramiko-expect and am not sure how it would be of much use. – bfan Jun 05 '18 at 23:00
  • 1
    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 Jun 05 '18 at 23:15

1 Answers1

0

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

stdin.write('command\n')
stdin.flush()
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992