How to verify a users password for root privledges in python

杀马特。学长 韩版系。学妹 提交于 2019-12-11 17:54:54

问题


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?

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.

Any help is much appreciated.


回答1:


Just ditch the echo.

import subprocess
subprocess.call(['sudo', '-S', 'pacman', '-Syy'])

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.

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.



来源:https://stackoverflow.com/questions/20928103/how-to-verify-a-users-password-for-root-privledges-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!