Paramiko会话超时,但我需要执行很多命令

Paramiko session times out, but i need to execute a lot of commands

我正在编写一个与远程设备 运行 Cisco IOS 一起工作的脚本 (python 2.7),因此我需要通过 ssh 执行很多命令. 很少有命令没有输出,其中一些有,我想接收输出。它是这样的:

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

问题是 exec_command 导致通道关闭并且无法重复使用,但我不可能打开一个新通道来执行另一个命令,因为这是一个会话最终我需要得到输出的命令。

我也试过用这种方式执行命令:

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

但是这样一来,output就空了。即使它不会,我也需要对 output 执行一些检查,然后继续我停止的会话。

那我需要什么?一种无需关闭或启动新连接即可管理此 ssh 连接并轻松接收命令输出的方法。

提前致谢,美里。 :)

您需要正确地将命令链接在一起,就像在 shell 脚本中一样:

stdin, stdout, stderr = ssh.exec_command('''
command1
&& command2
&& command3
''')

我想你需要的是invoke_shell()。例如:

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

Channel还有很多其他的方法。详情可参考document