微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python发送密码非交互式

如何解决Python发送密码非交互式

我想运行 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 等等。我该怎么做?

解决方法

使用 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

上阅读更多详细信息

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。