2015-09-09 67 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]) 

这做到了!!!!