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)