skip to Main Content

I have been asked to create a user and password from two files in ubuntu. Below is what i did in python.

import os

with open("users.txt",'r') as file, open("passwords.txt", 'r') as password:
    for line in file:
        pass
        for passw in password:
            os.system('useradd ' +line)
            os.system('echo +line +passw | chpasswd')

Contents of users.txt

avinash
ananthram

Contents of passwords.txt

lifeisbeautiful
lifeisbeautifulagain

It gives me an error in the last line saying chpasswd: line 1: missing new password. I have tried using os.system("echo +line +passw | chpasswd") but still it gives me the error. Can someone help me through this? Thanks in advance

I am expecting to create users with the password from two files.

2

Answers


  1. Try this

    os.system(f'echo -e "{line}n{passw}" | chpasswd')
    

    Explanation – The echo command is used to write a string to the standard output, but you are using it to construct the command that you want to pass to chpasswd.
    Instead of using echo, you can use the -e option of echo to include a new line in the string being passed to chpasswd.

    Login or Signup to reply.
    1. You have to loop through the lines in both files simultaneously. Code you provided reads the first line from user file, then loops through all the passwords trying to set those passwords for the first user. By the time you reach read second line in users file you have already reached EOF in password file.
    2. Substitute line and passw in last command with those variables’ values.
    3. chpasswd expects user and password delimited by colon, not space
    4. add -n to echo to suppress adding newline character at the end
    import os
    
    with open("users.txt",'r') as file, open("passwords.txt", 'r') as password:
        for line, passw in zip(file, password):
            os.system('useradd ' +line)
            os.system(f'echo -n "{line}:{passw}" | chpasswd')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search