Python script to create ‘N’ number of user IDs from CSV file

Let us write a python script to create ‘N’ number of user IDs in Linux server.

Script Input: a CSV file containing list of User IDs and Password by comma separated values as below,

[root@centos7 ~]# cat input.csv
user11,password11
user22,password22
user33,password33
user44,password44
[root@centos7 ~]#

In general, by using command line we can create the user IDs as below,

useradd -p <encrypted_password> <user_ID>

-p -> The encrypted password, as returned by crypt

We are using three different python modules to achieve it, they are
import os
import crypt
import csv

After importing, open the input.csv file as below,

with open("input.csv", 'r') as input:

read and store the input file content in a variable called ‘file’ as below,

file=csv.reader(input)

traverse the file with row by row using ‘for’ loop

for row in file:
print (row)

Encrypt the given password in each row with second column using ‘crypt’ module’s ‘crypt’ function
##crypt.crypt(word, salt=None)

salt (either a random 2 or 16 character string, possibly prefixed with $digit$ to indicate the method)

Encry_password=crypt.crypt(row[1], "39")

Now we can create user id as below using ‘OS’ module’s ‘system’ function.

os.system("useradd -p " + Encry_password + " " + row[0])

Final script:

import os
import crypt
import csv

with open("input.csv", 'r') as input:
file=csv.reader(input)
for row in file:
print (row)
print ("encrypting the password for %s" % row[0] )
Encry_password=crypt.crypt(row[1], "39")
print(Encry_password)
os.system("useradd -p " + Encry_password + " " + row[0])
print("created user id for %s" % row[
0])

Executing the script:
[root@centos7 ~]# python3 useradd_csv.py

Output:

[root@centos7 ~]# python3 useradd_csv.py
['user11', 'password11']
encrypting the password for user11
39dXUenjuGAqU
created user id for user11

['user22', 'password22']
encrypting the password for user22
39l55nHosbE1c
created user id for user22

[‘user33’, ‘password33’]
encrypting the password for user33
39ZOjCDhT2FnA
created user id for user33

[‘user44’, ‘password44’]
encrypting the password for user44
39Tnkoy6cE2Cc
created user id for user44
[root@centos7 ~]#

Hence, we have created user IDs using Python script.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: