2011-03-08 52 views
7

我有這個網站和多個其他地點的搜索,但我一直無法解決我的連接和維護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會話 未被重用。在解決此問題方面的任何幫助將不勝感激。

+0

我迷上了導入pexpect和paramiko的腳本......您是同時使用兩者還是嘗試一個並遷移? – 2011-04-17 02:28:32

回答

6

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

您需要在while循環之外創建,連接和關閉連接。

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

移動初始化和設置外循環。 編輯:移近()

+1

'ssh.close()'不應該在循環中。 – 2011-03-08 20:40:24

+0

好點我錯過了它 – 2011-03-08 20:46:53

+0

我能夠連接併成功運行第一個命令。我一直無法建立一個持續的連接,以便可以運行多個相關的命令。 – msudi 2011-03-09 19:06:38

1

當我 需要配置模式,因爲SSH 會話不重用

上述程序不工作,你SSH一旦你移動會話將被重用循環外部的connectclose,但是每個exec_command()發生在新的shell中(通過新的通道),並且是不相關的。您需要格式化命令,以便它們不需要shell中的任何狀態。

如果我沒有記錯,某些思科設備只允許一個exec,然後關閉連接。在這種情況下,您將需要使用invoke_shell(),並使用pexpect模塊(您已經導入但尚未使用)交互工作。

+0

謝謝,仍然試圖invoke_shell()無濟於事。當我解決我的問題時,我會在一兩天內回覆。 – msudi 2011-03-09 19:09:00