How to create a user in linux using python

后端 未结 6 708
南旧
南旧 2020-12-08 16:48

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 th

相关标签:
6条回答
  • 2020-12-08 17:00

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

    0 讨论(0)
  • 2020-12-08 17:00

    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.

    0 讨论(0)
  • 2020-12-08 17:05

    This is a solution where shell is false.

    #!/bin/env/python
    
    import subprocess
    import traceback
    import sys
    
    
    def user_add(username, user_dir=None):
        if user_dir:
            cmd = ["sudo", "useradd", "-d", user_dir, "-m", username]
        else:
            cmd = ["sudo", "useradd", username]
    
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, error = p.communicate()
        output = output.strip().decode("utf-8")
        error = error.decode("utf-8")
        if p.returncode != 0:
            print(f"E: {error}")
            raise
        return output
    
    
    try:
        username = "user"
        output = user_add(username)
        print(F"Success. {username} is added")
    except:
        traceback.print_exc()
        sys.exit(1)
    
    
    
    0 讨论(0)
  • 2020-12-08 17:06
    import os
    import crypt
    
    password ="p@ssw0rd" 
    encPass = crypt.crypt(password,"22")
    os.system("useradd -p "+encPass+" johnsmith")
    
    0 讨论(0)
  • 2020-12-08 17:18
    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)
    
    0 讨论(0)
  • 2020-12-08 17:24

    On Ubuntu, you could use the python-libuser package

    0 讨论(0)
提交回复
热议问题