Thursday, 8 March 2012

Read file in linux, check if the group exists,Check if the user exists,Add the group if it does not exists

You have a file named users. Each line in the file contains two words (space separated): a user
name and a group name. Write a (Perl or Bash) script to: 25 Marks
a. read one by one each line in the file
b. check if the group exists, add the group if it does not exists
c. check if the user exists, check the user belongs to the same group, if not change the
group. Add user to the group if user does not exists
d. Set the password of the user same as the username.
e. On each step, display appropriate prompts (e.g., user added, user already exists etc.)

while read user group #Reading user and group from the file
echo CHECKING FOR USER $user and GROUP $group #Display message before checking for
each user or group
tmp_u=$(grep -w ^$user /etc/passwd) #Check if user exists.
tmp_g=$(grep -w ^$group /etc/group) #Check if group exists
pass=$(mkpasswd $user)
if [ -z $tmp_g ] #If group does not exist
echo Group $group does not exist, it is being added #Display message
sudo groupadd $group #Adding group
else #If Group exists
echo Group $group exists #Display message
if [ -z $tmp_u ] #If user does not exists
echo User $user does not exist, it is being added #Display message
sudo useradd -g $group $user #Adding user to the group
else #If user exists
echo User $user exists #Display message
org_grp=$(id -gn $user) #Extract group of the user
if [ $group == $org_grp ] #If user's current group is same as desired
echo User $user already belongs to group $group #Display message
echo User $user belongs to $org_grp and being changed to $group
#Display message
sudo usermod -g $group $user #Change the user group
sudo usermod -p $pass $user #Changing password to the user name
echo "Password for $user changed to $user" #Display message
echo '**********************************************************'
done < user #Input file (user) for the while loop
Contents of file user are:
omer omer
check grp
ent nust
cse seecs


Post a Comment

Free Host | lasik surgery new york