Thursday, January 5, 2012

Create bunch of users from text file

This tutorial is about a bash script to add users from text file
Scenario. one of my client provide me list of proxy users with password . its around 600 users. i was exited with this new challenge. I tried to create users from text file.while struggling with that i found "newusers" command to add users from text file.
example.
# echo "user1:password:1001:513:Student Account:/home/user1:/bin/false" > users.txt ; newusers users.txt 

for 600 users it would be a difficult task to create like this.
then i got an idea from this command . i have prepare a bash script which takes users,passwords and gcos(comments) from text file and create users.


1. Log in to the Linux box as root and create  usersadd.sh and paste following lines from "Start-Of-Script" to "END-OF-SCRIPT"


########Start-Of-Script##########
#!/bin/bash
# Build on Mon Jan  2 20:21:50 IST 2012
# Purpose add users/passwd from text file
# Author Rahul Patil



# To set variable from arguments

THE_SCRIPT=`readlink -f $0`
THE_USER=`readlink -f $2 2>/dev/null`
THE_PASS=`readlink -f $4 2>/dev/null`
THE_GC=`readlink -f $6 2>/dev/null`
NEWUSER=`which newusers`
MV=`which mv`


SHOW_HELP ()
{
cat <<_EOF
This Script help you to add users from text file
Usage: 
        $THE_SCRIPT -u users.txt -l passwd.txt -g gcos.txt # gcos means users comments
_EOF
}

ADD_U ()
{
cat $THE_PASS | paste -d":"  $THE_USER  - | sed -e 's/$/::/' - | paste -d":" - $THE_GC | sed -e 's/$/::\/bin\/false/'  >> /tmp/adduser.txt

$NEWUSER /tmp/adduser.txt
$MV /tmp/adduser.txt /tmp/adduser-`date +%F`.txt

}


MAIN ()
{
case $1 in

    -u)
      ADD_U
    ;;
    -l)
      SHOW_HELP
    ;;
        --help|-h)
      SHOW_HELP
    ;;
    *)
    SHOW_HELP
    ;;
esac
}
MAIN $* 2>/dev/null


##################END-OF-SCRIPT############


2. set execute permission to script "chmod +x usersadd.sh"


3. create users.txt, passwd.txt and gcos.txt


example of above file.

[root@localhost ~]# cat users.txt
user1
user2
user3
user4



[root@localhost ~]# cat passwd.txt
passwd123
passwd123
passwd123
passwd123

[root@localhost ~]# cat gcos.txt
Xyz user from sales
abc admin user
user3 test user
user4 test user



let me show you 1st user is exist or not 



[root@localhost ~]# id user1
id: user1: No such user
 

now lets run the script
[root@localhost ~]# ./usersadd.sh -u users.txt -l passwd.txt -g gcos.txt

[root@localhost ~]# id user1
uid=528(user1) gid=527() groups=527()


[root@localhost ~]# finger user4
Login: user4                            Name: user4 test user
Directory:                              Shell: /bin/false
Never logged in.
No mail.
No Plan.




Note: above example only use for proxy users for authentication.

 














0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.