Reading username and password from file - linux

I'm looking at a away of reading the username and password of a file and inputing those to either add user or delete user.
EG: I have a file named 'userlist' with the following content with this format:
user1 pass1
user2 pass2
user3 pass3
What I don't understand completely is how to use BASH script to add these accounts.
What I have so far is this:
if [[ whoami -ne "root" ]]
then
exit
else
echo "wish to add or delete? a/d"
read uArg
echo "enter file name"
read uFile
if [ $uArg = "a" -o $uArg = "A" ]
then
IDK WHAT TO DO HERE.
elif [ $uArg = "d" -o $uArg = "D" ]
then
IDK WHAT TO DO HERE.
fi
fi
Alright, what I don't understand is how to read each word line by line and input the username and password to add a new user or delete an existing user.
The program is ment to read the whole file and add each user with there corrosponding password. If delete is chosen then it deletes each user within the file.
I'm new to BASH so any help would be greatyl appreciated.

awk perfectly feets your needs.
See this example:
$ awk '{print "Hi! my name is " $1 ", and my pass is " $2}' ./userpass.txt
Hi! my name is user1, and my pass is pass1
Hi! my name is user2, and my pass is pass2
Hi! my name is user3, and my pass is pass3
Awk stores usernames in $1 and passwords in $2 (first and second column).
You can use pipelines to execute the strings you get from awk as commands:
$ awk '{print "echo " $1}' ./userpass.txt | /bin/bash
user1
user2
user3

something along the lines of...
if [[ whoami -ne "root" ]]
then
exit
else
echo "wish to add or delete? a/d"
read uArg
echo "enter file name"
read uFile
if [ $uArg = "a" -o $uArg = "A" ]
then
while read user passwd rest
do
if [ ! -z $rest ]; then
echo "Bad data"
else
useradd -m $user
passwd $user <<EOP
$passwd
$passwd
EOP
fi
done < $uFile
elif [ $uArg = "d" -o $uArg = "D" ]
then
while read user passwd rest
do
if [ ! -z $rest ]; then
echo "Bad data"
else
userdel $user
fi
done < $uFile
fi
fi

First comments:
learn and get used to basic commands like grep, sed, echo, and generally with file manipulation, awk is a good choice as well if you want to know bash basics, a lot you will encounter is about file manipulation
the code could use more error testing, it's just a basic skeleton
careful about string and variables, quote them whenever possible, spaces in strings can do a lot of bad
Could be something along these lines:
echo "wish to add or delete? a/d"
read uArg
echo "enter username"
read uName
grep "^$uName " password-file
RET=$?
if [ "$uArg" == "a" -o "$uArg" == "A" ]
then
[ $RET -eq 0 ] && echo "User is already in file"
if [ $RET -ne 0 ]
then
echo "enter password"
read uPass
echo "$uName $uPass" >> password-file
fi
elif [ "$uArg" == "d" -o "$uArg" == "D" ]
then
[ $RET -ne 0 ] && echo "User is not file"
if [ $RET -eq 0 ]
then
sed -i "/^$uName /d" password-file
echo "User deleted"
fi
fi

Related

Linux Bash script isnt printing out correctly

GOAL: My goal in this assignment is to create a script that will take in a student id as an input and will output a matching student's name OR an error message saying there is none by that name in this class. Im fairly new to Linux and it is kinda tough for me but I would love all the help I can get. Thanks!
Screenshot Page 1 of assignment
Screenshot Page 2 of assignment
My script is printing off everyones name in the file rather than just the one I am searching for.
#!/bin/bash
# findName.sh
searchFile="/acct/common/CSCE215-Fall17"
if [[ $1 = "" ]] ; then
echo "Sorry that person is not in CSCE215 this semester"
exit 2
fi
while read LINE
do
firstNameIndex=0
middleNameIndex=1
lastNameIndex=2
userIDIndex=3
IFS=', ' read -r -a lineArray <<< "$LINE"
if [[ $1 -eq ${lineArray[$userIDIndex]} ]] ; then
echo ${lineArray[$firstNameIndex]} ${lineArray[$middleNameIndex]} ${lineArray[$lastNameIndex]}
fi
done < "$searchFile"
VERSION 3:
Here is how I would do it with grep. This prevents you from looping through the input file.
#!/bin/bash
searchFile="sample.txt"
function notincourse()
{
echo "Sorry that person is not in CSCE215 this semester"
exit 2
}
# Verify arguments, 1 argument, name to search for
if [ $# -ne 1 ]
then
echo "findName.sh <NAME>"
exit 1
else
searchfor=$1
fi
# Verify if the name is in the file
nameline=$(grep $searchfor $searchFile)
#if [ $(echo $nameline | wc -l) -eq 0 ]
if [ $? -eq 1 ]
then
notincourse
else
idvalue=$(echo $nameline | cut -d',' -f1)
if [ "$idvalue" == "$searchfor" ]
then
IFS=', ' read -r -a lineArray <<< "$nameline"
echo ${lineArray[1]} ${lineArray[2]} ${lineArray[3]}
else
notincourse
fi
fi
I tried if with the following test input file:
111, firstname1, middlename1, lastname1
222, firstname2, middlename2, lastname2
333, firstname3, middlename3, lastname3
VERSION 3: it now verifies that the id is indeed the first word in the line. I realized that if the student id is someown included in his name (ya, but better safe than sorry!) my grep would return true!
One line of code to change:
if [[ "$1" == "${lineArray[$userIDIndex]}" ]] ; then

Can anyone help correct my bash script: Custom user creation in bash?

I've got basic knowledge of bash scripting, and need to create a function to create a user with custom settings:
1.User name and password
2.Group and user ID
3.Comment
4.Home directory
`function user_custom {
if [ $(id -u) -eq 0 ] ; then
read -p "Enter name here: " username
read -s -p "Enter password: " password
grep "^$username" /etc/passwd > /dev/null
if [ $? -eq 0]; then
echo -e "${LIGHTGREEN}This user already exists! Try another name
please.${RESET}" ; break
else
pass=$(perl -e 'print crypt(($AVG[0], "password")' $password)
read -p "Enter group for user: "GID
egrep "^$GID" /etc/passwd > /dev/null
if [ $? -eq 0] ; then
$GID=$?
else
echo "No such group"
fi
read -p "Enter custom comment for $username: "comment
read -p "Enter unique user ID" Uid
getent passwd `grep "^Uid" /proc/$3/status |awk '{printf "%4s",$2}'` | if
[$? -eq $Uid ] ; then
echo "Select diferent ID"
fi
useradd -m -p -u -c -g $username $pass $Uid $comment $GID
fi
}`
I have a function ready, but I'm sure there are a lot of obvious mistakes.
Its like a patched skirt, I've gathered a lot of data from different sources.
I would be thankful if someone could help with fixing it.
Ill provide a screenshot of the whole function.
I'm from Ukraine, but i am good at english\russian.
PS: btw the 'if' in the end is included, all ifs are closeTd
Thanks ahead! <3
I correct it for you, I hope this will suit your need. You had lot of typo like if [ anything ]; then there is always needed space after [ and before ].
Brake only working for loops, you need to use exit 1 to terminate function with error code 1.
Instead of encrypt password in the script I prefer let passwd do the job, it will also enforce password rules.
The following way you can pass almost everything to command, like you typed it in from console:
(echo $password ; echo $password ) | passwd $username
I would add a lot of other check to make this script to enforce followings:
Uid should be number, and less/equal than UID_MAX in /etc/login.def
Gid should be a number, and less than the GID_MAY in /etc/login.def
And some feature as well like:
The script cannot handle if you like to make a GID for the user insted of using a existing one.
Asking if it should create home folder or not (currently -m do it in useradd)
If passwd fail because of password rule enforcing on the host, there is no retrying so you need to type it manually.
This is just the ones came into my mind now but there could be more.
#!/bin/bash
function user_custom {
if [ $(id -u) -eq 0 ] ; then
read -p "Enter name here: " username ;
read -s -p "Enter password: " password ; echo
grep "^$username" /etc/passwd > /dev/null
if [ $? -eq 0 ] ; then
echo -e "\nThis user already exists! Try another name please.\n" ; exit 1
else
read -p "Enter group for user: " GID
egrep "^"$GID":" /etc/group > /dev/null
if [ $? -gt 0 ] ; then
echo "No such group ( "$GID" )"; exit 1
fi
read -p "Enter custom comment for $username: " comment
read -p "Enter unique user ID: " Uid ; echo
if [ $(getent passwd | awk -F ":" '{print $3}' | egrep -c "^"$Uid"$" ) -gt 0 ];then
echo " ID already exist! " ; exit 1
fi
fi
useradd -m -u $Uid -c $comment -g $GID $username &&
(echo $password ; echo $password ) | passwd $username
fi
}
user_custom

IF statement for LINUX

Modify your program so that if no matching name is found, a message is displayed: "Name 'xyz' not in directory". You could use an 'if' statement to check the value of $? to see if the grep command was successful (remember that '0' indicates success). If the grep is NOT successful, then echo the message (which includes the value of $name).
The original code was:
#!/bin/bash
name=$1
if [ "$name" = "" ]
then echo -n "Enter a name to search for: "
read name
fi
grep -I $name ~uli101/2017a/phonebook
I basically have to insert and IF statement into the program using the instructions above. I've tried many different things such as:
if [ $? = 1 ]
then echo -n "Name 'xyz' not in directory"
fi
but it is not accepting the answer. Pls help me out with this. Any help is appreciated.
This is working for me, try:
#!/bin/bash
name=$1
if [ "$name" = "" ]; then
echo -n "Enter a name to search for: "
read name
fi
grep -I $name phonebook
if [ $? = 1 ]; then
echo "Name '${name}' not in directory"
fi
Or you can change the last IF into:
grep -I $name phonebook && echo -n "Name not in directory"
Try this, it works for me.
#!/bin/bash
#
NAME=$1
if [ -z "${NAME}" ]; then
echo -n "Enter a name to search for: "
read NAME
fi
grep -I $NAME~uli101/2017a/phonebook

Extraction of usernames from the text file in a script

I am a newbie to linux scripting and I am getting an unexpected error. I have made a script which takes into account two options 1 and 2. I am having issues with option 2 I want to extract the usernames from a text file and add all of the users except the EOF to the home directory like this:
Try this for parsing your input file:
if [ -e $Path ]
then
while read user
do
[[ $user = \#* ]] && continue
Username=`echo $user | cut -f2 -d:`
if [ "$Username" != "EOF" ]
then
echo $Username
fi
done < $Path
fi

how do I save a password on a file using UNIX/LINUX?

I only know how to read a password. But I'm having a problem on how to set a password inputted by the user for a file. I've only gone this far. Please help:
if [ -d "$1" ]
then
#reads password
read -s -p "Enter Password: " password
stty -echo
stty echo
echo ""
echo ""
#checks whether the password is valid or not
echo $mypassword" == "$PASS" ] && echo "Password accepted" || echo "Access denied"
else
echo "Directory not found."
fi
If I don't get you wrong, try something like this:
#!/bin/bash
EXPECTED_PASS="FooBar"
if [ -d "$1" ]
then
read -s -p "Enter Password: " password
stty -echo
stty echo
echo ""
echo ""
#Save password to a temporary file
echo "${password}" > /tmp/password.txt
#Load password from file
password=`cat /tmp/password.txt`
if [ "${password}" == "${EXPECTED_PASS}" ]
then
echo "Access granted"
else
echo "Access denied"
fi
else
echo "Directory not found."
fi
Usually it's not a good idea to store passwords as plain text. It's better to encrypt them or at least perform a hash operation over them:
EXPECTED_PASS=`echo "FooBar" | md5sum | cut -f1 -d" "`
...
#Save password to a temporary file
echo "${password}" | md5sum | cut -f1 -d" " > /tmp/password.txt
#Load password from file
password=`cat /tmp/password.txt`
Hope it helps.
Regards.

Resources