How to verify a users password for root privledges

2019-09-16 16:39发布

问题:

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.