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

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

Related

Useradd script in linux without using passwd

I have to write a useradd script which adds a new user and sets for him a home directory.
#!/bin/bash
echo "Name:"
read name
echo "Password:"
read password
echo "Group:"
read group
useradd -m -G $group -s /bin/bash -p $password $name
Everything works as intended but I have problems with the password in the following line -
useradd -m -G $group -s /bin/bash -p $password $name
It does not work so I need to use later in terminal passwd command.
How can I rebuild my script so I won't need to use passwd to setup password correctly? I have read that you can use stdin but I was not able to do this correctly.
If you prefer to pipe the user's password from STDIN, use chpasswd utility which is quick and simple.
as suggested by #Ardit.
This script should work for your purpose, assuming you meet the following conditions-
You are interacting as the root user
You have an existing group created for the purpose of your new user
#!/bin/bash
echo "Name:"
read name
echo "Password:"
read password
echo "Group:" # group must exist
read group
# add new user, set group, create new home directory
useradd -G $group -m $name
# update new user password by piping from STDIN
echo ""$name":"$password"" | chpasswd
# change the default user shell to bash
chsh -s /bin/bash $name
First we execute useradd command to create the new user and assign it to an existing group.
Then we pipe the name and password into chpasswd. If you're wondering why wrap those variable expansions with double quotes, check this answer out .
Finally chsh utility is used to update the user shell.
Why not execute everything in a single statement?
I prefer subdividing a problem into smaller tasks for easier understanding.

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

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.

How can I get all information about specific user in ubuntu using bash ?

Right now I have this code, that gives me only name, but I want to get name and other information from file /etc/passwd,
#!/bin/bash
user=$1;
grep home /etc/passwd | grep $user | cut -d: -f1;
I would like to get the full line, Not only my name.
Here is all the info on the current user. Note that because $USER is just a variable, it can be changed whereas the id command gives the actual user.
myuser#PC:~$ getent passwd $(id -u)
myuser:x:1000:1000:"",,,:/home/myuser:/bin/bash
myuser#PC:~$ export USER=root
myuser#PC:~$ getent passwd $USER
root:x:0:0:root:/root:/bin/bash
Try the finger command. You may need to install it.

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