与Cisco路由器的持久ssh会话

我在这个站点和其他多个位置搜索但我无法解决在一个命令后连接和维护ssh会话的问题。以下是我目前的代码:
#!/opt/local/bin/python

import os  

import pexpect

import paramiko

import hashlib

import StringIO

while True:

      cisco_cmd = raw_input("Enter cisco router cmd:")

      ssh = paramiko.SSHClient()

      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

      ssh.connect('192.168.221.235', username='nuts', password='cisco', timeout =  30)

      stdin, stdout, stderr = ssh.exec_command(cisco_cmd)

      print stdout.read()

      ssh.close()

      if  cisco_cmd == 'exit': break
我可以运行多个命令,但是对于每个命令,都会创建一个新的ssh会话。 当我需要配置模式因为ssh session时,上面的程序不起作用 没有重复使用。非常感谢任何协助解决这个问题。     
已邀请:
我使用Exscript而不是paramiko,我现在能够在IOS设备上获得持久会话。
#!/opt/local/bin/python
import hashlib
import Exscript

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()              # Prompt the user for his name and password
conn = SSH2()                       # We choose to use SSH2
conn.connect('192.168.221.235')     # Open the SSH connection
conn.login(account)                 # Authenticate on the remote host
conn.execute('conf t')              # Execute the "uname -a" command
conn.execute('interface Serial1/0')
conn.execute('ip address 114.168.221.202 255.255.255.0')
conn.execute('no shutdown')
conn.execute('end')
conn.execute('sh run int Serial1/0')
print conn.response

conn.execute('show ip route')
print conn.response

conn.send('exitr')                 # Send the "exit" command
conn.close()                        # Wait for the connection to close
    
您需要在while循环外创建,连接和关闭连接。     
你的循环做到了
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.221.235', username='nuts', password='cisco', timeout =  30)
while True:
      cisco_cmd = raw_input("Enter cisco router cmd:")
      stdin, stdout, stderr = ssh.exec_command(cisco_cmd)
      print stdout.read()
      if  cisco_cmd == 'exit': break
ssh.close()
将初始化和设置移到循环外部。 编辑:移动关闭()     
  当我这个时,上面的程序不起作用   需要配置模式,因为ssh   会话不会被重用 一旦你在循环之外移动
connect
close
,你的ssh会话将被重用,但是每个
exec_command()
都发生在一个新的shell中(通过一个新的通道),并且是无关的。您需要格式化命令,以便它们不需要shell中的任何状态。 如果我没记错的话,某些Cisco设备只允许一个exec,然后关闭连接。在这种情况下,您将需要使用
invoke_shell()
,并使用
pexpect
模块(您已经导入但未使用)以交互方式工作。     

要回复问题请先登录注册