使用Python用于身份验证的两个密码之一登录到多个服务器

2024-04-19 23:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手。 我正在使用Paramiko模块登录Linux服务器。但是,我有两个不同的身份验证密码,我希望使用其中任何一个登录服务器。如果两者都失败了,我将为其提出一个例外。 当我不得不使用第二个密码时,我面临着问题。这是同样的样品。 server.txt包含服务器列表

file1 = 'D:\Linux\server.txt'
with open(file1) as f:
    switch_ip = f.readlines()
switch_ip = [x.strip() for x in switch_ip]

username = "user1"

password1 = "abcd2"
password2 = "efcdrf2"

def simple_out(cmd):
    try:
            ssh=paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            x=[]

            ssh.connect(IP,port =22,username = username, password = password1 or password2)
            pass
            time.sleep(2)
            stdin, stdout, stderr = ssh.exec_command(cmd)
            line1 = stdout.readline()               #read line by line
            while line1:
                split_words = line1.split()         #List
                #      split_words.insert(0,IP)
                print split_words       
                str1 = ' '.join(split_words)        #String
                x.append(str1)
                line1=stdout.readline()
            return [x]
    except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error) as e:
        time.sleep(2)
        buf = StringIO.StringIO(e)
        line3 = buf.read()
        y=[line3]
        return [y]

for IP in switch_ip:
        output = simple_out("df -h")                                            # will call function and execute command
        out1 = output[0]                                                                #t     
        for items in out1:
            book = xlrd.open_workbook('D:\\Linux\\xlwt example.xls')
            sheet2 = book.sheet_by_index(0)
            row_count = sheet2.nrows
            column_count = 1
            sheet1.write(row_count, 0, IP)
            sheet1.write(row_count, column_count, items)
            wb.save('D:\\Linux\\xlwt example.xls')

time.sleep(2)   

我想使用这两个密码中的任何一个登录到服务器


Tags: inip服务器paramiko密码forlinuxcount
1条回答
网友
1楼 · 发布于 2024-04-19 23:27:30

您可以对每个密码使用try-catch块并在程序中继续,请参见以下示例:

try:
  ssh.connect(IP,port =22,username = username, password = password1)
except paramiko.AuthenticationException as e: #catch other exceptions as well
  ssh.connect(IP,port =22,username = username, password = password2)

相关问题 更多 >