0

I'm working on a script (python 2.7) that is wotking with a remote device running Cisco IOS, so I need to execute a lot of commands through ssh. Few commands have no output and some of them have, and I want to recieve the output. It goes something like this:

import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self._ip, port=22, username=username, password=password
stdin, stdout, stderr = ssh.exec_command('command with no output')
stdin, stdout, stderr = ssh.exec_command('command with no output')
stdin, stdout, stderr = ssh.exec_command('command with output')
sh_ver = stdout.readlines()

The thing is exec_command is causes the channel to close and it can’t be reused, but it's not possible for me to open a new channel in order to execute another command, because this is a session of commands that in the end I need to get the output.

I've tried to execute the commands this way as well:

stdin, stdout, stderr = ssh.exec_command('''
command
command
command
''')
output = stdout.readlines()

but this way, output is empty. And even if it would'nt, I need to perform a few checks on the output and then continue the session where I stopped.

So what do I need? A way to manage this ssh connection without closing it or starting a new one, and to easily recieve the output from the command.

Thanks in advance, Miri. :)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Miri Adj
  • 21
  • 4

2 Answers2

0

You need to properly chain the commands together, as in a shell script:

stdin, stdout, stderr = ssh.exec_command('''
command1
&& command2
&& command3
''')
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • oh, okay.. but as i said, is it possible to check the output and then continue in the same session this way? – Miri Adj Dec 16 '16 at 12:56
  • @MiriAdj: I know you said `exec_command()` can only be used once per session, but I don't think that's true. Is your point that you want to "continue" the same chain of commands? It would really help if you were more specific about what the commands are. – John Zwinck Dec 16 '16 at 12:57
  • yes, it's a chain of commands.. the commands are for a cisco device, so these are some settings and then i get an output.. – Miri Adj Dec 16 '16 at 18:44
0

I think what you need is invoke_shell(). For example:

ssh = paramiko.SSHClient()
... ...
chan = ssh.invoke_shell() # starts an interactive session

chan.send('command 1\r')
output = chan.recv()

chan.send('command 2\r')
output = chan.recv()
... ...

The Channel has many other methods. You can refer to the document for more details.

pynexj
  • 19,215
  • 5
  • 38
  • 56