Created
September 11, 2020 09:55
-
-
Save yucer/047aefeccd035d6ba298c3c51adc8e34 to your computer and use it in GitHub Desktop.
ask sudo programatically from python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, subprocess | |
from getpass import getpass | |
def is_root(): | |
return os.geteuid() == 0 | |
def test_sudo(pwd=""): | |
args = "sudo -S echo OK".split() | |
kwargs = dict(stdout=subprocess.PIPE, | |
encoding="ascii") | |
if pwd: | |
kwargs.update(input=pwd) | |
cmd = subprocess.run(args, **kwargs) | |
return ("OK" in cmd.stdout) | |
def prompt_sudo(): | |
ok = is_root() or test_sudo() | |
if not ok: | |
pwd = getpass("password: ") | |
ok = test_sudo(pwd) | |
return ok | |
if prompt_sudo(): | |
print("Access granted !") | |
else: | |
print("Access denied !") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment