skip to Main Content

I’m currently working on a Python Script on a CentOs 8 VM, I’m trying to write part of my python script that will set a users password for them without user interaction. I’ve not found a way to do this yet and tried various methods like:

subprocess.run(str('echo -e "passwordnpasswordnpasswordn" | sudo -S passwd --stdin user'), shell=True, universal_newlines=True, check=True)

But to no avail.

I know this is insecure (even if it worked) but in this case, that really doesn’t matter, so, security aside I just need to make it work. The passwords are just examples to show the code as I know they would be rejected if used as the actual passwords.

Is there a way to make the script run as the root user maybe, instead of the logged-in user?

Doing a similar thing as root user works like this:

subprocess.run(str('echo -e "passwordnpassword" | passwd --stdin ' + userName), shell=True, universal_newlines=True, check=True)

it’s only when I add the sudo part I can’t auto put in the sudo password

If I do this straight from the terminal it works:

echo -e "passwordnpasswordnpassowrd" | sudo -S passwd --stdin dave

2

Answers


  1. Try this and see this related thread.

    Option-1

    username = 'dave'
    sudoPassword = 'mypass'
    command = 'passwd --stdin ' + username
    p = os.system('echo -e "passwordnpasswordnpassowrd" %s|sudo -S %s' % (sudoPassword, command))
    
    Login or Signup to reply.
  2. Try using subprocess.Popen(command, 0, None, None, shell=True) like below:

    def launchCommand(command):
        proc = subprocess.Popen(command,0,None,None, shell=True)
        proc.poll()
        proc.wait()
        ret = proc.returncode
        return ret
    
    command = str('echo -e "passwordnpasswordnpasswordn" | sudo -S passwd --stdin user')
    print(launchCommand(command))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search