0

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 "password\npassword\npassword\n" | 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 "password\npassword" | 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 "password\npassword\npassowrd" | sudo -S passwd --stdin dave
Dave748
  • 30
  • 6
  • I executed your code `echo -e "password\npassword\npassowrd" | sudo -S passwd --stdin dave` . It throws an error : `passwd: unrecognized option '--stdin'`. Please provide the correct command. – Ratnesh Feb 25 '20 at 23:39
  • If I run the command it works: '[dave@localhost ~]$ echo -e "password\npassword\npassword" | sudo -S passwd --stdin dave [sudo] password for dave: Changing password for user dave. passwd: all authentication tokens updated successfully. [dave@localhost ~]$' – Dave748 Feb 25 '20 at 23:42
  • If you are able to run it then try with `subprocess.Popen(command, 0,None, None, shell=True)` – Ratnesh Feb 25 '20 at 23:44
  • No still not working, I'll pick it up again tomorrow. Thanks Anyway. – Dave748 Feb 25 '20 at 23:50

2 Answers2

0

Try this and see this related thread.

Option-1

username = 'dave'
sudoPassword = 'mypass'
command = 'passwd --stdin ' + username
p = os.system('echo -e "password\npassword\npassowrd" %s|sudo -S %s' % (sudoPassword, command))
CypherX
  • 7,019
  • 3
  • 25
  • 37
0

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 "password\npassword\npassword\n" | sudo -S passwd --stdin user')
print(launchCommand(command))
Ratnesh
  • 1,554
  • 3
  • 12
  • 28