问题描述
我正在尝试编写一个需要用户密码才能使用 subprocess
库运行一些外部命令的 Python 程序.代码大致如下所示.
I'm attempting to write a python program that requires a the users password to run some external commands using the subprocess
libraries. The code is going to look roughly like this.
import subprocess
passwordInput = raw_input("What is your password: ")
subprocess.call('echo ' + passwordInput + ' | sudo -S pacman -Syy', shell=True)
此程序运行良好,但如果您输入错误的密码,程序将失败.我将如何添加某种防错功能来检测密码是否输入错误?
This program works fine, however if you enter the incorrect password, the program fails. How would I go about adding some kind of error proofing to detect if the password is entered incorrectly?
我想也许将这段代码包装在 while
循环中,然后使用 try-except
来测试密码,但是我不确定是哪种 except
可以做到这一点.
I was thinking perhaps wrapping this code in a while
loop and then using a try-except
to test the password, however I'm not sure what kind of except
could do this.
非常感谢任何帮助.
推荐答案
放弃 echo
.
import subprocess
subprocess.call(['sudo', '-S', 'pacman', '-Syy'])
sudo
程序会询问用户一定次数.您的 Python 程序无需知道用户的密码.曾经.
The sudo
program will ask the user a certain number of times. There's no need for your Python program to know the user's password. Ever.
另一个问题是你使用的是 shell=True
,这意味着如果我的密码是 $nakel0ver
因为我喜欢蛇,你的程序会传递一个空密码给sudo
.
Another concern is that you are using shell=True
, which means that if my password is $nakel0ver
because I love snakes, your program will pass an empty password to sudo
.
这篇关于如何在python中验证root权限的用户密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!