0

I have this script running as root:

import subprocess
proc = subprocess.Popen(['chpasswd'], stdin=subprocess.PIPE)
proc.stdin.write("username:password")
print("Password updated")

While the script is run as a root user, it works as expected.

However, when I try running it under flask, it prints "Password updated", but it does not actually update the password. What could be the reason, and how to make it work?

...
@app.route('/')
def some_path():
    if condition:
        proc = subprocess.Popen(['chpasswd'], stdin=subprocess.PIPE)
        proc.stdin.write("username:password")
        print("Password updated")
...
acagastya
  • 323
  • 2
  • 14
  • Why do you expect `chpasswd` to work in unprivileged mode at all? Run it with `sudo`, or have Flask talk to a privileged helper. (Also, probably use `subprocess.run()` if your Python is new enough, or `subprocess.check_call()` if you need to support dead versions.) – tripleee Sep 06 '20 at 13:41
  • I am running the script as root, @tripleee – acagastya Sep 06 '20 at 13:48

1 Answers1

0

Referring to this answer, replacing proc.stdin.write("username:password") with proc.communicate(b"username:password") solves the problem.

acagastya
  • 323
  • 2
  • 14