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

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

Related

For each parameters, script checks if there exists a user of such username. If exists script prints all processes run by this user

#!/bin/bash
if [ $# -ne 1 ]
then
echo "Script Should Have Atleast 1 Parameter"
exit
fi
USER=$1
echo $USER
if [ $? -eq 0 ]
then
echo " Yes the User Exists"
else
echo "No , The User Doesnt Exists"
fi
My problem here is whatever the input i give, it shows yes the user exists.
And can anyone suggest me a command to print out all the process runs by this user
Should i use awk , or grep
Well, first of all, you are not checking if user exists, but ultimately if command echo $USER didn't fail. You will need to implement proper user check.
Good way how to check if arbitrary user exists would be something like this, using command id.
if id "${1}" &> /dev/null; then
echo 'user found'
else
echo 'user not found'
fi
Next you want to list all processes belonging to this user. You will need ps. There are many ways how ps can format output. Be sure to check manual page of ps. Here is example which lists command and pid of all processes belonging to user in "$1".
ps -eo pid,comm --user $(id -u "${1}")
At last, running check using id and only then using ps for process list is inefficient at least. In your use-case, you can simply run ps and check if it was successful. If not, you can show warning that user was not found.
#!/bin/bash
if ! ps -u "$1" 2> /dev/null; then
echo 'user not exists!'
exit 1
fi

bash script to add and remove users

I am a beginner in bash scripting and I have created a bash script to add users and remove users on Linux. But since I am facing some issues with the script not really major issues but would be helpful if anyone could point me how to improve the script and the worst practice I am doing the script would be helpful
however the problem I have noticed is that the script takes -a to add a user -d to remove user and -h to get help the -a flag as 2 optional arguments -p for password and -s for shell so the command would be
./useradd.sh -a user -p password -s shell
this works as expected and the user is added to the system but the problem I am facing is that if I do not enter -a flag and specify the -s and -p flag the script is just exited I want to show a clear idea to the user why it exited and there is so many such errors I am assuming but I have not tested it out so much any help would be appreciated, so here is my script
#!/bin/bash
## checking if the user is privileged or not
if [[ $EUID != 0 ]]
then
echo "Script has to be ran as root or sudo"
echo "Aborting"
exit 101
fi
## creating help functions
function usage() {
echo "usage: ${0} -a <user> -p <password> -s <shell> | ${0} -d <user> | ${0} -h"
}
function help() {
echo "$0 - Script to add of remove users"
echo "-a - Add a new user"
echo " -p - Set password while creating user if not mentioned will not set any password by default"
echo " -s - Set a shell for the user default is /bin/bash if none specified"
echo "-a - Remove a user"
echo "-h - Print this help text"
}
if [[ "$#" -lt "1" ]]; then
echo "Argument has to be provided see $0 -h"
fi
shell=/bin/bash
password=$(openssl rand -base64 32)
while getopts :a:d:h opt; do
case $opt in
a) user=$OPTARG
while getopts :p:s: test
do
case $test in
p) password=$OPTARG;;
s) shell=$OPTARG;;
/?) echo "The provided flag is not identified see $0 -h"
exit;;
:) echo "$OPTARG requires arguments see $0 -h"
exit;;
esac
done
if [[ "$1" != "-a" ]]
then
echo "You have to specify username using -a flag see $0 -h"
fi
useradd -m $user -s $shell
echo "$user":"$password" | chpasswd
echo "The password for the $user is $password";;
d) userdel -f $OPTARG
if [[ $? == 0 ]]
then
echo "user has been removed"
else
echo "There was some error removing the user"
fi;;
h) help
exit;;
/?) echo "$OPTARG option not valid";;
:) echo "$OPTARG requires argument";;
esac
done
Please show your code! I usually process args with case ... in likes :
#!/bin/bash
while [[ $# -gt 0 ]]; do
case $1 in
"-a")
echo "-a is $2"
shift 2;;
"-d")
echo "-d is $2"
shift 2;;
esac
done

How to fix "id -u" returning 0 into my variable for if statement?

I'm trying to put the result of "id -u $1" into a variable in order to verify it with an if statement but it seems like it's returning 0 into my variable even tho I've checked it and it's supposed to be 1008.Is it because the username is taken from the argument of the script?
UID=`id -u $1`
LOCK=`usermod -L $1`
if test $UID -lt 500;then
echo "impossible to lock user"
else
$LOCK;
fi
Your problem is that you use system variable in your script and try to change it.
instead of UID try to use UID1 (for example) as variable name. And your script will be something like:
UID1=`id -u $1`
LOCK=`usermod -L $1`
if test $UID1 -lt 500;then
echo "impossible to lock user"
else
$LOCK;
fi

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 do I search for a certain piece of text inside of a variable?

I am working on a script which prompts the user for their username. Once entered, the script uses the 'rwho' command to get a list of users who are logged into the network. It should crosscheck the text they entered (their username) with the results from the rwho command.
If a match is found then it displays a message saying so, if not then it also makes the user aware of this.
Here is the script and my attempt so far:
#!/bin/sh
#
# User network checking script
#
# Using rwho command to get user list
OUTPUT="$(rwho)"
echo "${OUTPUT}"
# Prompt for username
echo "Please enter your username: "
read username
# Input validation
if [ -z "$username"]
then
echo "No username supplied"
echo "Please enter your username: "
read username
fi
# Search for user
if `echo ${OUTPUT} | grep "${username}" 1>/dev/null 2>&1'
then
echo "$username is logged in."
else
echo "$username is not present."
fi
I consistently get errors with the Search for User part. I don't have outstanding knowledge of Linux so if anyone could fix this and help me I would be greatly appreciative.
Your usage of quotes is weird.
if echo "$OUTPUT" | grep -q "$username"
should work.
-q makes grep quiet (and is shorter than your redirections).

Resources