Skip to content

Instantly share code, notes, and snippets.

@yucer
Created September 11, 2020 09:55
Show Gist options
  • Save yucer/047aefeccd035d6ba298c3c51adc8e34 to your computer and use it in GitHub Desktop.
Save yucer/047aefeccd035d6ba298c3c51adc8e34 to your computer and use it in GitHub Desktop.
ask sudo programatically from python
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