持久的SSH会话到思科路由器

8

我在这个网站和其他多个地方搜索过,但是我无法解决连接并保持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会话未被重用。非常感谢您提供的任何帮助来解决这个问题。

我对一个同时导入pexpect和paramiko的脚本深感着迷……你是在同一时间使用两者,还是先尝试一个再迁移? - Mike Pennington
4个回答

7

我使用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('exit\r')                 # Send the "exit" command
conn.close()                        # Wait for the connection to close

1

你的循环执行了那个操作

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

将初始化和设置移至循环外部。 编辑:移动close()。

1
ssh.close() 也不应该在循环中。 - Vlad H
我能够连接并成功运行第一个命令。但是我一直无法建立一个持久的连接,以便可以运行多个相关的命令。 - msudi

1

你需要在 while 循环之外创建、连接和关闭连接。


1
以上程序在需要配置模式时无法工作,因为ssh会话未被重用。
如果您将connectclose移出循环,您的ssh会话将被重用,但是每个exec_command()都在一个新的shell中(通过新通道),并且彼此无关。您需要格式化您的命令,使其不需要来自shell的任何状态。
如果我没记错的话,一些Cisco设备只允许单个exec,然后关闭连接。在这种情况下,您需要使用invoke_shell(),并使用pexpect模块进行交互式操作(您已经导入了该模块,但尚未使用)。

谢谢,我仍在努力尝试调用invoke_shell(),但还没有成功。当我解决问题时,我会在一两天内回报。 - msudi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接