Change the primary and secondary group of a user using a script - linux

So what I am trying to do is run a script, that can only be run from Root, and it creates new usernames and passwords. The script checks to see if that username and password already exist, and if it does, it will not create the new username. All of that works fine, but now, if a new user is created, I want to be able to add this new user to a group.
For example, lets say I want the primary group to be alpha and the secondary group to be beta. How would I be able to:
Set a user to just the primary group
Set a user to primary and secondary group
Set a user to only the secondary group
The following is my script:
#!/bin/sh
# Creating a script that creates a new user and password, runs in Root, accessible # in any shell, ADD USER TO SPECIFIC GROUPS NOW (itar and bfe already created)
ROOT_UID=0 #Root has $UID 0
SUCCESS=0
E_USEREXISTS=70
E_NOTROOT=65 #Not root
#Run as root, and this checks to see if the creater is in root. If not, will not run
if [ "$UID" -ne "$ROOT_UID" ]; then
echo "Sorry must be in root to run this script"
exit $E_NOTROOT
fi
if [ $# -eq 2 ]; then
username=$1
passwd=$2
grep -q "$username" /etc/passwd
#Checking if the username and password already exists
if [ $? -eq $SUCCESS ]; then
echo "User $username already exists"
echo "Please choose another username"
exit $E_USEREXISTS
fi
#Creating the new username and the new password:
useradd $username -d /home/$username -m ;
echo $passwd | passwd $username --stdin;
echo "The new user account is setup"
#Adding the user to group bfe or itar
echo "Which group will this user be in?"
read x more
#If the person does not give the correct number of arguments
else
echo "This program needs 2 arguments and you have given $#"
echo "You have to call the script and provide a username and password"
#if [ \"$x\" -eq "bfe" ]; then #echo "First word was \"$x\""
# usermod -g bfe $username
#if [ \"$x\" -eq "itar" ]; then
# usermod -g itar $username
fi
exit 0
Any help would be appreciated! Still learning the ropes so please take it easy on me.

Use -G option for useradd.
-G, --groups GROUP1[,GROUP2,...[,GROUPN]]]
A list of supplementary groups which the user is also a member of.Each
group is separated from the next by a comma, with no intervening
whitespace.
The groups are subject to the same restrictions
as the group given with the -g option.
The default is for the user to belong only
to the initial group.
Then rearrange part of your script, something like this
#Adding the user to group bfe or itar
echo "Which group will this user be in?"
read x
# Check if group exists
grep -q "$x" /etc/group || echo "Group doesn't exist"
#Creating the new username and the new password:
useradd "$username" -d "/home/$username" -m -G "$x" ;
echo "$passwd" | passwd "$username" --stdin;
echo "The new user account is setup"
You can use -G to assign more than one group to the user.

Related

How to use getent passwd command to see if the user exists and belongs to a particular group

I want to check if a user exists in a particular group.
getent passwd user_name &> /dev/null
The above command checks if the user is there. But I want to also see if it belongs to a group named for example support
You should run
groups username
to list the groups the user belongs.
If the user does not exist, the output is
groups: username: No such user
So the bash script can be
output=$(groups username)
if [[ $output == *"groupname"* ]]; then
echo yes
fi

How to create a bash script in Linux that checks if the user is local or not

I'm trying to create a Linux bash script that prompts for a username. For example, it asks for a username, once the username it's typed it will check if the user exists or not. I already tried to do it, but I'm not sure if I did it correctly.
I would appreciate your help.
Here is how I did it:
#!/bin/bash
echo "Enter your username:"
read username
if [ $(getent passwd $username) ] ; then
echo "The user $username is a local user."
else
echo "The user $username is not a local user."
fi
Try the following script :
user="bob"
if cut -d: -f1 /etc/passwd | grep -w "$user"; then
echo "user $user found"
else
echo "user $user not found"
fi
The file /etc/passwd contains a list of the local users along with some parameters for them. We use cut -d: -f1 to only extract the usernames, and match it with our user with grep -w $user. The if condition evaluate the exit code of the function to determine if the user is present.
if id "$username" >/dev/null 2>&1; then
echo "yes the user '$username' exists"
fi
OR
getent command is designed to gather entries for the databases that can be backed by /etc files and various remote services like LDAP, AD, NIS/Yellow Pages, DNS and the likes.
if getent passwd "$username" > /dev/null 2>&1; then
echo "yes the user '$username' exists"
fi
Will do your job, for example below
#!/bin/bash
echo "Enter your username:"
read username
if getent passwd "$username" > /dev/null 2>&1; then
echo "yes the user '$username' exists"
else
echo "No, the user '$username' does not exist"
fi
Try this.
#!/bin/sh
USER="userid"
if id $USER > /dev/null 2>&1; then
echo "user exist!"
else
echo "user deosn't exist"
fi

Linux Shell script to add a user with a password from a list

I'm trying to modify a script that read usernames/password from a file which is like this:
user1 pass1
user2 pass2
user3 pass3
I can't get the script to read the space between the users and pass.
What can I use to delimit this space?
This is my code:
for row in `cat $1`
do
if [ $(id -u) -eq 0 ]; then
username=${row%:*}
password=${row#*:}
#echo $username
#echo $password
I know I have to change the stuff in ${row%:} and ${row%:}
What do I have to put so it sees the space between user1 pass1 ?
It would be easier to split the two fields as you read each line. You can do that with read. It's also better to use a while loop here (a for loop requires to play with $IFS and it would also load the entire file in memory):
#!/bin/bash
if [ "$EUID" -ne 0 ]; then
echo >&2 "You are not root"
exit 1
fi
while read -r username password; do
# do the useradd stuff here
done < "$1"
Notice that I also changed $(id -u) to $UID which should be faster since it does not invoke an external program.

How to check if a group exists and add if it doesn't in Linux Shell Script

this is a summary of what i want my code to do:
if (group exists)
then
(add user to group)
else
(create group)
(add user to group)
fi
I am using the Ubuntu virtual machine but all of the results i have found on similar sites do not work.
The grep statement in the solution of rups has some flaws:
E.g. grepping for a group admin may return true ("group exists") when there is a group lpadmin.
Either fix the grep-query
grep -q -E "^admin:" /etc/group
or use
if [ $(getent group admin) ]; then
echo "group exists."
else
echo "group does not exist."
fi
This script may help you:
read -p "enter group name: " group
if grep -q $group /etc/group
then
echo "group exists"
else
echo "group does not exist"
fi
Grepping /etc/group works, but only on a machine where /etc/nsswitch.conf has:
group: files
meaning that only /etc/group is consulted when determining available groups. Use either of these (by name or by gid):
getent group <groupname>
getent group <groupid>
for a more generic solution, checking the exit status: 0 means "exists", non-zero means "does not exist". For example, to check to see if group 'postgres' exists, and create it if it does not (assuming bash shell, running as a user able to create new groups) run:
/usr/bin/getent group postgres 2>&1 > /dev/null || /usr/sbin/groupadd postgres
I've found it more useful, to compose andiba's solution into a proper function:
function grpexists {
if [ $(getent group $1) ]; then
echo "group $1 exists."
else
echo "group $1 does not exist."
fi
}
This can for e.g be invoked into your environment by including this function in your /etc/bash.bashrc*, such that you can then check for the existence of a group, using the following spell:
grpexists group_name
Which should then return one of:
group group_name exists.
or
group group_name does not exist.
Single line:
$getent group <-groupname-> || groupadd <-groupname->
Here are 3 commands which should work:
group=sudo
grep -qw ^$group /etc/group || groupadd $group
usermod -aG $group $USER
Or one, when you use -f/--force (exit successfully if the group already exists):
groupadd -f mygroup && usermod -aG mygroup $USER
$ groupadd --help
Usage: groupadd [options] GROUP
Options:
-f, --force exit successfully if the group already exists,
and cancel -g if the GID is already used
So you can do simply:
groupadd -f some_new_grp
Geeks great solutions and guidance, thanks for sharing here are my 2 cents to make our lives simpler or lazier :-) I could use to complement an useradd script I have to add several users at once. I'm wondering how it would look like inside a for
in loop for several groups: group1, group2, group3...group6
Then useradd to the system something like this?
for g in $( cat fewgroups.txt ); do
groupadd $g
echo "Group:" $g "Exist not added moving on"
else
echo "Group:" $g "added successfully!"
# Then create the users
for u in $( cat 100sofusers.txt ); do
useradd -m -g group1 -G group2,wheel -d /home/$u -c "Just anothe SiFiGeek" -s /bin/bash $u
echo "userID:" $u "added successfully!"
echo $u:$randompw | chpasswd
echo "Password for userID:" $u "changed successfully"
done

String Bash scripting if then statement fails

I am currently writing a script that will allow me to add groups via user input. I am on the portion of my script where the user types the group name in and it compares it against /etc/group and lets the user know if it needs to be added or not. I have tested this against a group that I know for a fact is not on my system and it only reads the first statement in my loop. Could someone tell me where I am going wrong?
#!/bin/bash
echo "This script will allow you to enter Groups and Users needed for new builds"
echo
echo
echo
echo
# Setting Variables for Group Section
Group=`cat /etc/group |grep "$group"`
echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: " # Request User input to obtain group name
read group
echo "Searching /etc/group to see if the group "$group" exists." # Checking to see if the group exists
if [ "$group" != "$Group" ]; then
echo "The group already exist. Nothing more to do buddy."
else
echo "We gotta add this one fella..carry on."
If you're on Linux, and thus have getent available:
printf "Group to search for: "
read -r group
if getent group "$group" >/dev/null 2>&1; then
echo "$group exists"
else
echo "$group does not exist"
fi
Using getent uses the standard C library for directory lookups. Thus, it's good for not only /etc/passwd, /etc/group, etc., but also directory services such as Active Directory, LDAP, NIS, YP and the like.
Here's what you do:
Search for a group name
Input the group name to search for
Sadly, you can't search for the group name before you input it, as this would violate causality and the laws of spacetime as we know them. Try searching after you know what you search for instead:
echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: " # Request User input to obtain group name
read group
if cat /etc/group | grep -q "^$group:"
then
echo "The group already exist. Nothing more to do buddy."
fi

Resources