1

For training reasons im trying to write a python script that creates and sets user accounts and passwords :

import subprocess
from subprocess import Popen

users = ["user1"]
default_passwd = 'password'

for user in users:
    p1 = subprocess.Popen(["useradd" ,user])
    proc = Popen(['echo' ,default_passwd ,  '|' , 'passwd', user, '--stdin'])
    proc.communicate()

While the user is created , the passwd process fails. Any help would be appreciated.

1
  • Don't use shell pipes with subprocess. Instead, try and use subprocess.PIPE for communication between processes. Commented Sep 28, 2017 at 8:09

2 Answers 2

3

Why don't you pass password along with command useradd? so that it creates a user with password without prompting!!

import os
import crypt

password ="your-password" 
crypted_password = crypt.crypt(password,"22")
os.system("useradd -p "+ crypted_password +" student")
Sign up to request clarification or add additional context in comments.

1 Comment

Nice example where os.system is much simpler than subprocess module
1

@Naren answer is neat and much more readable; but for the purpose of answering your subprocess question, it should be like this

import subprocess

users = ["user1"]
default_passwd = 'password'

for user in users:
    p1 = subprocess.Popen(['useradd', user, '-p'])
    proc = subprocess.Popen(['echo', default_passwd], stdout=subprocess.PIPE)
    p1.communicate(proc.stdout)
    proc.communicate()
  • p1 opens a subshell with useradd user1 command executed and waits for input
  • proc then executes echo default_passwd, but instead of sending output to sys.stdout, it pipes it to subprocess.PIPE
  • The communicate on p1 sends the output of proc.stdout to the stdin of p1 and waits for it completion
  • The last commands wait for proc process to finish and exit

2 Comments

Thanks Vinny for your comment. It works but it seems that does not set the password correct.
I missed the -p param; try it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.