How to create a user in linux using python

2020-02-05 03:26发布

问题:

How do I create a user in Linux using Python? I mean, I know about the subprocess module and thought about calling 'adduser' and passing all the parameters at once, but the 'adduser' command asks some questions like password, full name, phone and stuff. How would I answer this questions using subprocess? I've seen module called pexpect in this question: Can I use Python as a Bash replacement?. Is there any other standard module?

回答1:

Use useradd, it doesn't ask any questions but accepts many command line options.



回答2:

On Ubuntu, you could use the python-libuser package



回答3:

import os
import crypt

password ="p@ssw0rd" 
encPass = crypt.crypt(password,"22")
os.system("useradd -p "+encPass+" johnsmith")


回答4:

You could just use the built-in binaries so just call useradd or something through the subprocess module, However I don't know if there's any other modules that hook into Linux to provide such functionality.



回答5:

def createUser(name,username,password):
    encPass = crypt.crypt(password,"22")   
    return  os.system("useradd -p "+encPass+ " -s "+ "/bin/bash "+ "-d "+ "/home/" + username+ " -m "+ " -c \""+ name+"\" " + username)