簡體   English   中英

與Cisco路由器的持久ssh會話

[英]Persistent ssh session to Cisco router

我在這個站點和其他多個位置搜索但我無法解決在一個命令后連接和維護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會話不被重用。非常感謝解決此問題的任何幫助。

我使用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

您需要在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模塊(您已經導入但未使用)以交互方式工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM