如何使用paramiko.ssh_exceptions

时间:2018-07-27 08:20:41

标签: python paramiko

嗨,我正在使用下面的python paramiko连接到远程主机,以使用sudo用户获取正常运行时间状态,但是它可以正常工作,但是如果sudo无法登录并抛出错误paramiko.ssh_exception.AuthenticationException: Authentication failed.

我期待着跳过错误并继续浏览该行中的其他主机

#!/usr/bin/env python
import paramiko
with open('hosts_DC_all_main', 'r') as f:
        for host in f:
                    remote_host = host.rstrip()
                    remote_pass = "pass"
                    smart_user = "user"
                    ssh = paramiko.SSHClient()
                    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                    ssh.connect(remote_host, username=smart_user, password=remote_pass)
                    transport = ssh.get_transport()
                    session = transport.open_session()
                    session.set_combine_stderr(True)
                    session.get_pty()
                    #for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
                    session.exec_command("uptime")
                    stdin = session.makefile('wb', -1)
                    stdout = session.makefile('rb', -1)
                    #you have to check if you really need to send password here
                    stdin.write(remote_pass +'\n')
                    stdin.flush()
                    print"\n"
                    print "------------------------------------------------------------------------------"
                    print "Command Execution Strated....."
                    print "------------------------------------------------------------------------------"
                    for line in stdout.read().splitlines():
                        print 'host: %s: %s' % (remote_host, line)

0 个答案:

没有答案
相关问题