【问题标题】:Python send password non-interactivePython发送密码非交互式
【发布时间】:2021-02-02 11:47:27
【问题描述】:

我想运行 shell 命令 'su - testuser -c "id"' 并获取输出。之后在控制台中询问密码。我的意图是在 python 脚本中运行它,它登录到另一个用户(源用户和目标用户都没有 root 权限)。问题是,密码应该以非交互方式输入,这样我就可以在不输入密码的情况下启动脚本并查看输出。所以我可以启动 python 脚本,它会自动运行命令而无需等待密码并给我输出。

我用 pexpect 包试过了:

child = pexpect.spawn('su - testuser -c "id"') 
child.expect_exact('Password:')
child.sendline('mypassword')
print(child.before) # Prints the output of the "id" command to the console

问题是代码不起作用。输出就像一个随机字符串,而不是 id 等等。我该怎么做?

【问题讨论】:

    标签: python linux shell authentication process


    【解决方案1】:

    使用child.read 而不是print(child.before) 可以解决这个问题。

    >>> child = pexpect.spawn('su - testuser -c "id"') 
    >>> child.expect_exact('Password:')
    0
    >>> child.sendline('1234')
    5
    >>> print(child.before)
    b''
    >>> child.read()
    b' \r\nuid=1002(testuser) gid=1003(testuser) groups=1003(testuser)\r\n'
    

    您可以在here阅读更多详细信息

    【讨论】:

    • 谢谢,现在可以了。但是如何打印逐步创建输出的命令?例如。对于安装,完整的输出文本不会立即出现。我尝试使用“startsap”来启动 sap 系统,但 child.read() 失败了。它仅适用于写入立即获得输出的命令,如“I'd”、“pwd”、“ls”、“whoami”等。
    • 你能添加一个你正在尝试做什么的例子吗?
    • 现在可以了。 pexpect 的默认超时太小了。我通过添加“child.timeout=300”(默认为 30)来更改它。
    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2011-09-18
    • 2012-11-18
    • 1970-01-01
    相关资源
    最近更新 更多