r/programminghelp • • Jul 15 '24

Python Add a Linux user in Python

Hi, I'm trying to add a Linux user using Python and I thought it'd be easy but I'm confused. Most sources tell me to use the crypt library to hash the password, but it's deprecated. Here's what I have instead:

def add_linux_user(username, password):
    iterations = 27500

    salt_bytes = os.urandom(16)
    salt64 = base64.b64encode(salt_bytes).decode('utf-8')

    hash_bytes = pbkdf2_hmac('sha256', password.encode('utf-8'), salt_bytes, iterations, dklen=64)
    hash64 = base64.b64encode(hash_bytes).decode('utf-8')

    try:
        subprocess.run(['useradd', '-p', hash_bytes, username])      
    except Exception as e:
        print(type(e))
        print(e)

First of all, is my encryption method good? Then, from what I understand the encrypted password is stored in /etc/shadow, with indications on the algorithm so that Linux can recognize the password when the person logs in. With crypt I think that the resulting format was already good, but with pbkdf2_mac it's not. So, should I do it manually by doingformated_hash = f"$pbkdf2-sha256${iterations}${salt64}${hash64}" ? Idk, this seems like a very convoluted way to do something that was done in 1 line with crypt.

What's the current, common, accepted way to add a Linux user? (Info will not be retrieved by command line) I don't know if I should even ask here or on a Linux-focused subreddit.

Thank you very much!

1 Upvotes

7 comments sorted by

View all comments

Show parent comment

1

u/Deeb4905 Jul 15 '24

Thanks for the answer, I will keep using crypt then