python3子流程popen将密码发送到sudo并获取流程的结果

发布于 2025-02-06 08:59:12 字数 665 浏览 2 评论 0原文

我有一个PYQT5程序,其中使用QinputDialog窗口获取某些PCI操作的用户密码。我看不到弄清楚如何获得由sudo运行的命令的输出。

john@d10shop:~/bin$ python3
Python 3.7.3 (default, Jan 22 2021, 20:04:44) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen, PIPE
>>> password = 'xyz'
>>> p = Popen(['sudo', '-S', 'ls'], stdin=PIPE, stderr=PIPE, text=True)
>>> prompt = p.communicate(password + '\n')
camera  imap-1.py  pass.py
>>> prompt
(None, '[sudo] password for john: ')
>>> 

我可以看到命令已执行,但我获得了约翰的[sudo]密码:但是我需要在此示例中从LS输出。

OS Debian 10

谢谢 JT

I have a PyQt5 program where I get the users password for some PCI operations with a QInputDialog window. I can't seen to figure out how to get the output of the command that is ran by sudo.

john@d10shop:~/bin$ python3
Python 3.7.3 (default, Jan 22 2021, 20:04:44) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen, PIPE
>>> password = 'xyz'
>>> p = Popen(['sudo', '-S', 'ls'], stdin=PIPE, stderr=PIPE, text=True)
>>> prompt = p.communicate(password + '\n')
camera  imap-1.py  pass.py
>>> prompt
(None, '[sudo] password for john: ')
>>> 

I can see the command is executed but I get the [sudo] password for john: but I need the output from ls in this example.

OS Debian 10

Thanks
JT

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尾戒 2025-02-13 08:59:12

来自 python docs

请注意,如果要将数据发送到该过程的stdin,则需要使用stdin = pipe创建Popen对象。同样,要在结果元组中获得以外的任何东西,您需要给出stdout = pipe 和/或stderr = stderr = pipe。 /p>

您缺少stdout =管道零件以获取输出。
这对我有用:

p = Popen(['sudo', '-S', 'ls'], stdin=PIPE, stderr=PIPE, stdout=PIPE, text=True)
prompt = p.communicate(password + '\n')
output = prompt[0]

From the python docs:

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

You are missing the stdout=PIPE part to get the output.
This works for me:

p = Popen(['sudo', '-S', 'ls'], stdin=PIPE, stderr=PIPE, stdout=PIPE, text=True)
prompt = p.communicate(password + '\n')
output = prompt[0]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文