0
votes

Through a lot of searching and playing with snippets found on stackoverflow, I was able to create the following code that allows me to, using a Python GUI, launch a shell script as sudo with a password input through the GUI, and then not wait for the shell to return, allowing a progress bar to update as the shell script runs.

    build_script = ["Sudo -S sh dummyfile.sh"]
    sudo_password = 'password'
    sp = subprocess.Popen(build_script, shell=True, stdin=subprocess.PIPE, universal_newlines=True)
    sp.stdin.write(sudo_password+'\n')
    sp.stdin.flush()

If, the password is entered properly the first time, the tool runs fine. However, if the password is entered incorrectly, then entered correctly it fails and the GUI needs to be closed then reopened.

How can I go about validating if the password was accepted by:

    sp.stdin.write(sudo_password+'\n')

So that I can return an error back to the user.

I do understand that there are security risks associated with what I am attempting. I am open to suggestions that will allow me to:

  1. Validate the password is correct
  2. Launch a sh file as Sudo with a user input password
  3. Continue running the python (don't wait) while the sh script runs

It needs to be compatible with Python 2.7, but I am also trying to keep it working in Python 3 for the future.

Thank you for your help!

1

1 Answers

0
votes

So I wasn't able to check within the run block of code, so I created a new one to evaluate the password before running the script.

Sudo -S cd elevates and then runs cd which does nothing. Error will return "Password:" no matter what, but if the password is wrong it returns more info about being incorrect and number of wrong attempt.

    # Check password
    sudo_password = 'password'
    var = subprocess.Popen(["Sudo -S cd"], shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    out, error = var.communicate(input=sudo_password+'\n')

    if error == "Password:":
        pass
    else:
        self.label_return['text'] = "Local Admin Password Incorrect"
        return

    # Launch bash script
    sp = subprocess.Popen(dummyscript.sh, shell=True, stdin=subprocess.PIPE, universal_newlines=True)
    sp.stdin.write(sudo_password+'\n')
    sp.stdin.flush()

The if error == "Password:" is a little janky, but so far is consistent.