Passing csv file data into command using .sh file in linux - linux

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

Related

Trying to create user from text file but keep getting invalid user name error in Ubuntu

I am now trying to create users in Ubuntu from a text file and it looks like this:
student1
student2
student3
student4
student5
However, I keep getting invalid user name error. For instance
'seradd: invalid user name 'student5
Here is my code. The first argument is input file and the second input is output file. Can anyone help?
#!/bin/bash
if test ${#} -lt 1
then
echo "Please provide the input file"
exit 1
else
cat ${1} | while read user
do
randompw=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
useradd -m -s /bin/bash ${user}
echo ${newuser}:${randompw} | chpasswd
if test $# -lt 2
then
echo ${newuser}:${randompw} >> pwlist.txt
else
echo ${newuser}:${randompw} >> ${2}
fi
if id -u ${user}
then
echo "User account ${user} created successfully"
else
echo "User account ${user} created unsuccessfully"
fi
done
fi
The variable newuser is not defined. I think you meant $user instead.
Suggestion:
Enclose variable references and computations within double quotes. I fixed that.
#!/bin/bash
if test ${#} -lt 1
then
echo "Please provide the input file"
exit 1
else
cat "${1}" | while read user
do
randompw="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)"
useradd -m -s /bin/bash "${user}"
echo "${user}:${randompw}" | chpasswd
if test $# -lt 2
then
echo "${user}:${randompw}" >> pwlist.txt
else
echo "${user}:${randompw}" >> ${2}
fi
if id -u "${user}"
then
echo "User account ${user} created successfully"
else
echo "User account ${user} created unsuccessfully"
fi
done
fi

create user from file and random password

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:

My script does not work properly

Problem: I need to create a file where users and passwords are stored. But my script only saves the password of user1.
Example: I explain myself better with an example. When the two users are created with random password, my script assigns the same password on both users.
user1:Eehei5oo8ohz:/home/user1:/bin/bash
user2:Eehei5oo8ohz:/home/user2:/bin/bash
When the result of my script should be something like this:
user1:Eehei5oo8ohz:/home/user1:/bin/bash
user2:Kln2149sdpja:/home/user2:/bin/bash
My script: This is the script I have used:
#!/bin/bash
##Checking if you are root.##
if [ `id -u` -ne 0 ]
then
echo "you dont are a root user."
exit 1
fi
x=`pwgen 12 1`
for i in {1..2}
do
echo "user$i:#:/home/user$i:/bin/bash" >> users.txt
done
for j in $x
do
sed -i "s/#/$j/" users.txt
done
newusers users.txt
users=`cat users.txt`
login=`echo $i | cut -d: -f1` #username
pass=`cat pass.txt | tr " " _`
password1=`echo $i | cut -d: -f2` #password
for in $users
do
echo "$login:$password1" | chpasswd -m
done
rm users.txt
rm pass.txt
I hope I have explained correctly and appreciate all the help.
You could simplify your script and adapt it as follows (I'm referring to the first part only):
#!/bin/bash
# checking if you are root.##
if [ `id -u` -ne 0 ]
then
echo "you are not the root user!"
exit 1
fi
for i in {1..2}
do
x=`pwgen 12 1`
echo "user$i:$x:/home/user$i:/bin/bash" >> users.txt
done
This will create a file users.txt like the one bellow:
user1:ohng3uxohYi9:/home/user1:/bin/bash
user2:Gah5kiehaemi:/home/user2:/bin/bash
I see no point in creating a file with users and then replacing the # sign with a generated password since you can do that from the start!
You can simplify this script by getting rid of sed editing, eg change:
for i in {1..2}
do
echo "user$i:#:/home/user$i:/bin/bash" >> users.txt
done
for j in $x
do
sed -i "s/#/$j/" users.txt
done
to
pass=`cat pass.txt`
i=1
for pw in $pass
do
echo "user$i:$pw:/home/user$i:/bin/bash" >> users.txt
((i++))
done
This way you can get user numbers and passwords in one go and you are guaranteed to get as many usernames as passwords.

Linux commands not working in bash

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

Verify account creation from text file in bash script

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.

Resources