You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Paramiko处理多轮连续提示的键盘交互式多因素认证

Paramiko多轮键盘交互式MFA认证实现

针对包含多轮连续提示的键盘交互式多因素认证场景,可通过自定义Paramiko认证回调实现全流程自动应答,认证交互流程如下:

Using username "XXXXXX".
Keyboard-interactive authentication prompts from server:
| Password: xxxxxxxxx
| * Two Factor Auth *
| [Available mechanisms]
|  1 - Email... @company.com
|  2 - Security Question
| Please select a mechanism [1]: 2
| Answer security question 'my village of birth': xxxxxxx
End of keyboard-interactive prompts from server
Last login: Wed May 25 13:43:04 2022 from 10.xxx.xx.xx

核心逻辑

Paramiko连接时支持传入自定义的键盘交互认证回调函数,服务端每返回一组认证提示,回调就会被自动调用,只需按提示内容匹配返回对应应答值即可完成全流程认证,无需额外控制交互时序。

可用代码片段

import paramiko

def interactive_auth_handler(title, instructions, prompt_list):
    """
    键盘交互式认证回调,按提示内容返回对应应答
    参数说明:
    title: 服务端返回的认证标题
    instructions: 服务端返回的认证说明文本
    prompt_list: 本轮需要应答的提示列表,格式为[(提示文本, 是否回显输入), ...]
    """
    responses = []
    for prompt, is_echo in prompt_list:
        prompt = prompt.strip()
        # 匹配登录密码提示
        if prompt.startswith("Password:"):
            responses.append("你的登录密码")
        # 匹配MFA机制选择提示
        elif "Please select a mechanism" in prompt:
            responses.append("2")  # 选择安全问题验证,选邮箱则填"1"
        # 匹配安全问题答案提示
        elif "Answer security question" in prompt:
            responses.append("你的密保问题答案")
        # 其他未覆盖的提示可按需扩展匹配规则
        else:
            raise ValueError(f"未识别的认证提示: {prompt}")
    return responses

# 初始化SSH客户端
client = paramiko.SSHClient()
# 测试用自动接受未知主机密钥
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    client.connect(
        hostname="你的服务器IP地址",
        port=22,
        username="你的登录用户名",
        # Paramiko 3.0+版本使用以下认证策略配置
        auth_strategy=paramiko.auth_strategy.AuthStrategy(
            allowed_methods=["keyboard-interactive"],
            interactive_handler=interactive_auth_handler
        ),
        # Paramiko 2.x旧版本请注释上面的auth_strategy,启用以下3行配置
        # look_for_keys=False,
        # allow_agent=False,
        # auth_interactive=interactive_auth_handler
    )
    print("认证成功,已连接到服务器")
    # 连接成功后可执行shell命令、SFTP文件传输等操作
    stdin, stdout, stderr = client.exec_command("whoami")
    print("当前登录用户:", stdout.read().decode().strip())
finally:
    client.close()

注意事项

  • 若使用邮箱验证机制,只需修改机制选择的返回值为"1",再新增对应验证码提示的匹配规则,返回收到的邮箱验证码即可
  • 提示匹配优先使用关键字匹配,不要硬编码应答顺序,避免服务端微调提示文本顺序后认证失效
  • 测试环境可使用AutoAddPolicy自动接受主机密钥,生产环境建议配置已知主机密钥校验,防范中间人攻击
  • 若运行时提示找不到auth_strategy相关属性,说明当前Paramiko版本较低,切换为注释内的旧版配置即可正常使用

内容的提问来源于stack exchange,提问作者Partha Kaushik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 21:57:23