2015-09-09 76 views
-1

多重身份驗證憑據,我有以下代碼:的paramiko SSH - 與Python

import paramiko 
import time 
import re 
import sys 
import random 
import fileinput 

ip_address = raw_input("Enter a valid WAP IP: ") 

#Open SSHv2 connection to devices 
def open_ssh_conn(ip): 

try: 
    #Logging into device 
    session = paramiko.SSHClient() 

    #AutoAddPolicy 
    session.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 

    #Passing the necessary 
    session.connect(ip, username = 'myUsername', password = 'myPassword') 

    #Start an interactive shell session on the switch 
    connection = session.invoke_shell() 

    #Commands 
    connection.send("enable\n") 
    time.sleep(1) 
    connection.send("show version\n") 
    time.sleep(1) 

    #Checking command output for IOS syntax errors 
    output = connection.recv(65535) 

    #Checking command output for IOS Syntax errors 
    if re.search(r"% Invalid input detected at", output): 
     print "* There was at least one IOS syntax error on device %s" % ip 
    else: 
     print "\nDONE for device %s" % ip 

    #Test for reading command output 
    print output + "\n" 

    #Closing the connection 
    session.close() 

except paramiko.AuthenticationException: 
    print "* Invalid username or password. \n* Please check 
    the username/password file or the device configuration!" 
    print "* Closing program...\n" 

#Calling the SSH function 
open_ssh_conn(ip_address) 

如何測試沒有得到踢出程序的多個證書時捕獲異常?

例如,嘗試這種新的憑據:

session.connect(IP,用戶名= 'myNewUsername',密碼= 'myNewPassword')

+1

使用try /除了循環。沒有什麼說除了你的程序塊外唯一允許的就是程序暫停。 –

+0

你可以說明在我的代碼中...? – elyoe011

回答

0

我想通了!我創建了一個嵌套列表與證書:

list = [['username1', 'password1'], ['username2', 'password2'], \ 
     ['username3', 'password3']] 

然後,創建一個for循環,把我的代碼中:

for elem in list: 
      my code... 
      # this is the connect line: 
      session.connect(ip, username = elem[0], password = elem[1]) 

這做到了!!!!