如何通过ssh使用paramiko登录网络设备?

时间:2015-11-25 16:04:54

标签: python ssh paramiko

我试图通过ssh登录网络设备。我执行第一个命令后输出正确,但执行第二个命令时出现奇怪的错误。

import paramiko

paramiko.common.logging.basicConfig(level=paramiko.common.INFO)
paramiko.util.log_to_file('demo_router_simple.log')
try:
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    hostname='192.168.1.1'
    username='test'
    password='test'
    client.connect(hostname,username=username,password=password,look_for_keys = False,allow_agent = False)
    stdin, stdout, stderr = client.exec_command('show ip inter b')
    print stdout.read()
    # error occurs after I execute the second command
    stdin, stdout, stderr = client.exec_command('show ip inter b')
    print stdout.read()
finally:
    client.close()

奇怪的错误显示在下面

DEB [20151125-09:26:42.841] thr=1   paramiko.transport: userauth is OK
INF [20151125-09:26:42.852] thr=1   paramiko.transport: Authentication (password) successful!
DEB [20151125-09:26:42.876] thr=2   paramiko.transport: [chan 0] Max packet in: 32768 bytes
DEB [20151125-09:26:42.883] thr=1   paramiko.transport: [chan 0] Max packet out: 4096 bytes
DEB [20151125-09:26:42.883] thr=1   paramiko.transport: Secsh channel 0 opened.
DEB [20151125-09:26:42.901] thr=1   paramiko.transport: [chan 0] Sesch channel 0 request ok
DEB [20151125-09:26:42.925] thr=2   paramiko.transport: [chan 1] Max packet in: 32768 bytes
DEB [20151125-09:26:42.925] thr=1   paramiko.transport: [chan 0] EOF received (0)
DEB [20151125-09:26:42.927] thr=1   paramiko.transport: [chan 0] EOF sent (0)
DEB [20151125-09:26:42.928] thr=1   paramiko.transport: Ignoring message for dead channel 0
DEB [20151125-09:26:42.928] thr=1   paramiko.transport: EOF in transport thread

我还在路由器上打开调试并捕获调试信息

*Mar  1 00:17:09.639: SSH2 0: done calc MAC out #11
*Mar  1 00:17:09.639: SSH0: Session terminated normally
 R1#

根据这个名为exec_command的方法的解释,此方法将在服务器上执行命令。如果服务器允许,则通道将直接连接到正在执行的命令的stdin,stdout和stderr。当命令完成执行时,通道将关闭,不能重复使用。如果要执行另一个命令,则必须打开一个新通道。

让我困惑的是,为什么exec_command关闭这个ssh连接而不是通道?是否有其他人像我一样运行同样的问题?任何帮助将不胜感激。

0 个答案:

没有答案