【问题标题】:How to detect expired password using Python Fabric?如何使用 Python Fabric 检测过期密码?
【发布时间】:2016-06-08 19:20:54
【问题描述】:

使用以下代码,我无法让 Fabric 在登录时检测到密码过期提示。会话没有超时,并且 abort_on_prompts 参数似乎没有被触发。如何配置 Fabric 来检测这种状态?

from fabric.api import env, run, execute
from fabric import network
from fabric.context_managers import settings

def host_type():
    with settings(abort_on_prompts=True):
        print ("Using abort mode %(abort_on_prompts)s" % env)
        result = run('uname -s')
return result

if __name__ == '__main__':
    print ("Fabric v%(version)s" % env)
    env.user = 'myuser'
    env.password = 'user67user'
    env.hosts = ['10.254.254.143']
    host_types = execute(host_type)

执行此脚本会导致脚本挂起,如下所示:

Fabric v1.11.1.post1 [10.254.254.143] 执行任务'host_type' 使用中止模式 True [10.254.254.143] 运行:uname -s [10.254.254.143] 出:警告:您的密码已过期。 [10.254.254.143] out:您必须立即更改密码并重新登录! [10.254.254.143] out:更改 myuser 的密码。 [10.254.254.143] 出:(当前)UNIX 密码:

【问题讨论】:

    标签: python ssh fabric


    【解决方案1】:

    Fabric 包含一种回答提示问题的方法。

    您可以在with settings 上使用prompts 字典。在字典中,每个键都是您想要回答的标准输出中的问题,而值就是您的答案。

    所以在你的例子中:

    from fabric.api import env, run, execute
    from fabric import network
    from fabric.context_managers import settings
    
    def host_type():
        with settings(prompts={"(current) UNIX password": "new_password"}):
            result = run('uname -s')
    return result
    
    if __name__ == '__main__':
        print ("Fabric v%(version)s" % env)
        env.user = 'myuser'
        env.password = 'user67user'
        env.hosts = ['10.254.254.143']
        host_types = execute(host_type)
    

    【讨论】:

    • 谢谢,这是朝着正确方向的良好开端。随后,我了解了我正在构建的另一项更改密码的任务的提示。仅供参考,该示例在我测试过的 2 个 Linux 变体中无法正常工作。 Fabric 代码使用 _endwith 函数进行匹配,因此您需要在尾部包含一个空格,例如“UNIX 密码:” 因为我不知道新密码,也绝对不想意外设置一个,所以我正在使用提示发送错误密码,导致操作失败,退出代码为 10。
    • 续:with settings(prompts={'UNIX password: ': 'BOGUS'}): host_types = execute(host_type)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 2010-10-10
    • 2012-09-16
    • 2014-02-11
    • 2011-03-06
    相关资源
    最近更新 更多