使用Paramiko在Python中使用2FA进行SSH

时间:2018-12-13 11:47:10

标签: python paramiko multi-factor

我正在尝试编写一个Python 3脚本,该脚本将通过ssh连接到远程服务器并使用paramiko模块运行命令。

远程服务器使用Duo 2因子身份验证,并在使用ssh连接时提示您选择身份验证模式:

$ ssh myuser@remoteserver.com
Duo two-factor login for myuser

Enter a passcode or select one of the following options:

 1. Duo Push to +XXX XX-XXX-1111
 2. Phone call to +XXX XX-XXX-1111
 3. SMS passcodes to +XXX XX-XXX-1111

Passcode or option (1-3): 1
Success. Logging you in...

当我在终端中使用ssh时,只需按1,然后按Enter,将推入我的手机以确认连接,然后登录。

不幸的是,我无法在Python中做到这一点。这是我尝试使用的代码:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('remoteserver.com', port=22, username='myuser', password='mypassword')
stdin, stdout, stderr = ssh.exec_command('ls -l')
output = stdout.readlines()
print(output)

如果我在没有2FA的远程服务器上尝试相同的代码,则它可以按预期运行,但是在此服务器上,我收到一个Authenticatino错误:

paramiko.ssh_exception.AuthenticationException: Authentication failed.

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

在我自己的一个项目中,终于自己解决了这个问题,剩下的就是我使用的允许进行这项工作的代码。

主要结论是paramiko确实允许在传输和提示列表中完成此操作,在我的情况下,我在我的two_factor_types中缺少publickey方法

def _auth(self, username, password, pkey, *args):
    self.password = password
    saved_exception = None
    two_factor = False
    allowed_types = set()
    two_factor_types = {'keyboard-interactive', 'password', 'publickey'}

参考文献:
Paramiko/Python: Keyboard interactive authentication
https://github.com/paramiko/paramiko/pull/467
https://github.com/paramiko/paramiko/pull/467/commits/dae916f7bd6723cee95891778baff51ef45532ee
http://docs.paramiko.org/en/stable/api/transport.html

我建议尝试一些类似的方法 auth_interactive_dumb

auth_interactive_dumb(username, handler=None, submethods='')

以交互方式但不可靠地对服务器进行身份验证。只需打印提示和/或说明以输出并发送回响应即可。这适用于通过密钥实现部分身份验证然后用户必须输入2fac令牌的情况。


有关完整示例,请参见下面的摘录和链接

Full SSH CLient Class for reference

class SSHClient(paramiko.SSHClient):
    duo_auth = False

    def handler(self, title, instructions, prompt_list):
        answers = []
        global duo_auth

        if title.startswith('Duo two-factor login'):
            duo_auth = True
            raise SSHException("Expecting one field only.")

        for prompt_, _ in prompt_list:
            prompt = prompt_.strip().lower()
            if prompt.startswith('password'):
                answers.append(self.password)
            elif prompt.startswith('verification'):
                answers.append(self.totp)
            elif prompt.startswith('passcode'):
                answers.append(self.totp)
            else:
                raise ValueError('Unknown prompt: {}'.format(prompt_))
        return answers

    def auth_interactive(self, username, handler):
        if not self.totp:
            raise ValueError('Need a verification code for 2fa.')
        self._transport.auth_interactive(username, handler)

    def _auth(self, username, password, pkey, *args):
        self.password = password
        saved_exception = None
        two_factor = False
        allowed_types = set()
        two_factor_types = {'keyboard-interactive', 'password', 'publickey'}

        agent = paramiko.Agent()
        try:
            agent_keys = agent.get_keys()
            # if len(agent_keys) == 0:
            # return
        except:
            pass

        for key in agent_keys:
            logging.info("Trying ssh-agent key %s" % hexlify(key.get_fingerprint()))
            try:
                self._transport.auth_publickey(username, key)
                logging.info("... success!")
                return
            except paramiko.SSHException as e:
                logging.info("... nope.")
                saved_exception = e

        if pkey is not None:
            logging.info('Trying publickey authentication')
            try:
                allowed_types = set(
                    self._transport.auth_publickey(username, pkey)
                )
                two_factor = allowed_types & two_factor_types
                if not two_factor:
                    return
            except paramiko.SSHException as e:
                saved_exception = e

        if duo_auth or two_factor:
            logging.info('Trying 2fa interactive auth')
            return self.auth_interactive(username, self.handler)

        if password is not None:
            logging.info('Trying password authentication')
            try:
                self._transport.auth_password(username, password)
                return
            except paramiko.SSHException as e:
                saved_exception = e
                allowed_types = set(getattr(e, 'allowed_types', []))
                two_factor = allowed_types & two_factor_types

        assert saved_exception is not None
        raise saved_exception