I have a bash script called AddUsers.sh. The script should take a line like this:
john.mccarthy#caltech.edu;1927/09/04;sudo,visitor;/visitorData
and return variables like this:
name=john
surname=mccarthy
bdate=1927/09/04
uname=mccjoh
pass=1927
groups(array)=sudo, visitor
folder=/visitorData
When I run the script and give it the required text file, it is tellilng me that 'groupadd' 'chgrp' 'chmod' and 'chage' are all errors. Is anyone able to tell me why / give me any feedback?
Thanks in advance for any help.
#!/bin/bash
#check for file
while [ ! -f $file ]
do
#ask user for filename
echo What is the filename?
#reading input as file name
read file
if [ ! -f $file ]
then
echo "File not found!"
else
echo "File found!"
fi
done
#process each line and make a user from the data
cat "$file" | while read line
do
name=`echo $line | sed 's/^\(.*\)\..*\#.*$/\1/g'`
surname=`echo $line | sed 's/^.*\.\(.*\)\#.*$/\1/g'`
bdate=`echo $line | sed 's/^.*;\(.*\);.*;.*$/\1/g'`
#set groups to tokenize
groups=`echo $line`
folder=`echo $line`
temp2=`echo $name | sed 's/^\(...\).*$/\1/g'`
temp1=`echo $surname | sed 's/^\(...\).*$/\1/g'`
user="${temp1}${temp2}"
#pass must be first 4 numbers of birthdate
pass= ${bdate:0:4}
#tokenise group + add to array
declare -a groupArray
IFS=" "
groupArray=(`echo $groups | tr "," " "`)
#create groups if not existing.
for i in ${groupArray[#]}
do
if [ getent group $i ]
then
echo "group exists"
else
groupadd $i
fi
done
#Create shared folders if not existing.
if [ ! -d $folder ];
then
mkdir -p $folder
fi
#Create groups for shared folders
gname=`echo "${folder:1}"`
groupadd $gname
#Set group as owner of directory and change permissions
chgrp -R $gname $folder
chmod -R 770 $folder
#create user and add to groups
if [ grep "^${user}:" /etc/passwd ]
then
echo "user exists already!"
else
#Create user
useradd -m -d /home/$user -p $pass $user
#Add user to groups
for i in ${groupArray[#]}
do
usermod -a -G $i $user
done
#Add user to shared group
usermod -a -G $gname $user
fi
#force password change
chage -d 0 $user
done
you could use commands in scripts with full path address. and you can extract their full path address by "which" command.
for example instead of using "chmod" you could use "/bin/chmod"
type this to find full path:
$which chmod
Related
I am writing a bash script to add users but I am stuck when adding users to groups.
What I have:
#--------------------------------------------------
#This First reads the users.csv file splits up the data
#Checks if the users exists and if not makes them and gives them a password.
#it will then
file="users.csv.1"
Count=0
while IFS=";"; read email birthDate group sharedFolder
do
echo -e "Email: $email"
firstCharacter=${email:0:1}
echo $firstCharacter
local_part="${email%%#*}"
last_Name="${local_part##*.}"
echo "$last_Name"
UserName="$firstCharacter$last_Name"
USERID="$UserName"
egrep -i "^${USERID}:" /etc/passwd
if [[ $? -eq 0 ]]; then
echo "User $USERID exists in etc/passwd"
else
echo "User $USERID does not exists in etc/passwd"
fi
sudo useradd $UserName
echo -e "UserName: $UserName"
echo -e "Password: $birthDate" | tr -d '/'
echo "$UserName:$birthDate" | sudo chpasswd
echo -e "Birth Date: $birthDate"
if [[ "$group" == "staff" ]]; then
usermod -a -G "$UserName" staff
elif [[ "$group" == "visitor" ]]; then
usermod -a -G "$UserName" visitor
elif [[ "$group" == "sudo" ]]; then
usermod -a -G "$UserName" sudo
else
echo -e "no group to add to"
fi
echo -e "Group: $group"
echo -e "shared Folder: $sharedFolder\n"
done < "$file"
My problem is that it will keep coming back and saying usermod: user 'staff' does not exist
I do make the groups at the start of the script.
Shown here:
if [ $(getent group staff) ]; then
echo "group staff exists."
echo $'\n'
else
echo "group staff does NOT exsit."
echo "one will be created now"
sudo groupadd staff
echo "staff group has been created"
echo $'\n'
fi
if [ $(getent group visitor) ]; then
echo "group visitor exist."
echo $'\n'
else
echo "group visitor does Not exist."
echo "One will be created now"
sudo groupadd visitor
echo "visitor group has been created"
echo $'\n'
fi
I am not sure what I am doing wrong because I get the checks back at the start of the scripts saying that the groups exist.
The usermod command had its variables around the wrong way.
instead of
usermod -a -G "$UserName" visitor
it should be
sudo usermod -a -G visitor "$UserName"
Also should have sudo at the start of the command to run it.
I have a file which contains name of Users I want to create and assign them random password.I'm using this code but only first user from file is created and given random password.Here's the shell script.
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
arr=($line)
sudo adduser --force-badname ${arr[0]} --quiet --disabled-password
var2=$(openssl rand -base64 2)
echo "${arr[0]}:$var2" | sudo chpasswd
echo "User ${arr[0]} Created "
echo "Password for ${arr[0]} is $var2"
done < "$1"
text in file I'm giving input is as
Tyr3
Try2
but only user Tyr3 is created. Here's the output:
I am trying to output which accounts have been successfully created from a text file and which haven't. I would also like to output the number of successfully created accounts. I currently the get the following error: grep: 3: No such file or directory. The script and text file and saved in the same folder. I have use the following commands in my script.
file=users.txt
verify =grep "verify" $file |cut -f2 -d:`
cat /etc/passwd | grep $verify
echo -e "\nYou have Currently"
cat /etc/passwd | grep $verify |wc -l;
echo "users added from your Text File"
Edit:
#!/bin/bash
ROOT_UID=0 #The root user has a UID of 0
if [ "$UID" -ne "$ROOT_UID" ]; then
echo "**** You must be the root user to run this script!****"
exit
fi
clear
echo
echo "######################################################"
echo "##### Batch script to automate creation of users #####"
echo -e "######################################################\n"
while true;
do
file=notvalid
while [ $file == "notvalid" ]
do
#echo "repeat $repeat"
#echo -e "\n"
echo -n "Please enter import filename:"
read filename
echo -e "\r"
exists=0
if [ -e $filename ]; then
file=valid
while IFS=":" read firstname lastname userid password group
do
egrep -i "^$userid:" /etc/passwd &>/dev/null
if [ $? -eq 0 ]; then
exists=$((exists+1))
#echo -e "${firstname} ${lastname} already exists on the system"
#grep ${userid} /etc/passwd
aname=$( getent passwd "$userid" | cut -d: -f3)
echo "Account Exists: $aname"
euserid=$( getent passwd "$userid" | cut -d: -f1)
echo "User ID: $userid"
homedir=$( getent passwd "$userid" | cut -d: -f6)
echo "Home Directory: $homedir"
usershell=$( getent passwd "$userid" | cut -d: -f7)
echo "User Shell: $usershell"
g=$( id -Gn "$userid")
echo "Groups: $g"
echo -e "\r"
else
egrep -i "^$group:" /etc/group &>/dev/null
if [ $? -eq 1 ]; then
/usr/sbin/addgroup ${group} &>/dev/null
fi
useradd -d /home/"${userid}" -m -s /bin/bash -c \
"${firstname}${lastname}" -g "${group}" "${userid}"
echo "Creating Account: ${firstname} ${lastname}"
nuserid=$( getent passwd "$userid" | cut -d: -f1)
echo "Creating User ID: ${nuserid}"
{ echo ${password}; echo ${password}; } | sudo passwd ${userid} > /dev/null 2>&1
echo "Creating Password: ${password}"
echo "Creating Home Directory: /home/${userid}"
echo "Creating User Shell: /bin/bash"
echo -e "Assigning Group: ${group}\n"
fi
done < $filename
else
echo -e "##### CANNOT FIND OR LOCATE FILE #####"
fi
verify=`grep "verify" /home/pi/$filename | cut -f3 -d:`
echo "$verify"
count=0
for id in $verify
do grep -wo ^$id /etc/passwd && count=$((count+1))
done
echo $count users added from your text file
echo these are not added:
for id in $verify
do grep -wq ^$id /etc/passwd || echo $id
done
while true
do
echo -n "Create additional accounts [y/n]: "
read opt
if [[ $opt == "n" || $opt == "y" ]];then
break
else
echo "Invalid Input"
fi
done
if [ $opt = "n" ]; then
clear
break
else
clear
fi
done
You were almost there.
The main issue with your approach is that you try to search for multiple accounts at once with grep. The variable verify has multiple userids so you need to process it one by one.
file=users.txt
verify=`grep "verify" $file | cut -f2 -d:`
count=0
for id in $verify
do grep -wo ^$id /etc/passwd && count=$((count+1))
done
echo $count users added from your text file
echo these are not added:
for id in $verify
do grep -wq ^$id /etc/passwd || echo $id
done
The for loop will take each element in your verify variable into id and search with grep (-w matches only whole words, not fragments, ^ matches the beginning of line and -o outputs only the matching word not the whole line).
We count the number of matches in the count variable. Alternative approach to run the for loop twice and pipe the second one to wc -l as you did.
&& operator means it will increase count if the previous command found a match (the return code of grep was 0).
The next loop will not print matching ids (-q), and will echo id if grep did not found a match (the return code was not 0). This is achieved with the || operator.
One last note on iteration of a list: if the members can contain spaces (unlike userids), you should use ${verify[#]} (this is a bash-ism) instead of $verify .
And forget this: cat /etc/passwd | grep pattern, use grep pattern /etc/passwd instead.
I want to pass my n number csv data into command "esusers useradd username -r role -p password". How can i perform this in linux machine. i Have done this window but unable to do in linux machine can anyone help me out of this. My input will contain header also.
csv file user.csv:
user1,role1,pass1
user2,role2,pass2
user3,role3,pass3
The bash script (scripts.sh) to iterate over the csv file:
#!/bin/bash
# Check parameters
if [ "$#" -ne 1 ]; then
>&2 echo "Illegal number of parameters"
exit 1
fi
# Check file
if [ ! -f "${1}" ]; then
>&2 echo "File ${1} not found"
exit 1
fi
FILE="${1}"
while read line; do
USER=`echo ${line} | cut -d"," -f1`
ROLE=`echo ${line} | cut -d"," -f2`
PASS=`echo ${line} | cut -d"," -f3`
echo "adding user ${USER} (role: ${ROLE}) with password: ${PASS}"
esusers useradd "${USER}" -r "${ROLE}" -p "${PASS}"
done < ${FILE}
Then, add execution mode to the script with chmod +x script.sh
and run the script with the csv file as parameter ./script.sh user.csv
$ ./script.sh user.csv
adding user user1 (role: role1) with password: pass1
adding user user2 (role: role2) with password: pass2
adding user user3 (role: role3) with password: pass3
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