I was asked in an exam to create a bash script that, putting a text file and a group name as parameters, would create users with the data contained in the text file.
Example of entry of the students.txt file:
juanmanuel;delrio;delafuente;77776666T
ander;errasti;basterretxea;77778888X
Two users will be created with the following information:
- juanmanuel and key: 77776666T
- ander and key: 77778888X
The following parameters will be passed to the script:
./altaalumnos.sh alumnos.txt curso2
where high-students.sh is the name of the script, students.txt is the file that contains the data separated by ";" and course2 is the name of the group to which the students will belong
Ok, I attach the code:
#!/bin/bash
if [ -z $1 ];then
echo "No ha ingresado ningun archivo de texto"
elif [ -f $1 ];then
group=$(cat /etc/group | grep "$2")
if [ "$group" ];then
lineas=$(wc -l $1 | cut -d\ -f1) #numero de lineas que tiene alumnos.txt
for (( i = 1; i <= $lineas; i++ )); do
sudo useradd -g $2 $(cat $1 | head -n $i | tail -1 | cut -d\; -f1) -p $(cat $1 | head -n $i | tail -1 | cut -d\; -f4)
done
echo "Usuarios creados con exito."
else
echo "El grupo $2 no existe."
echo "Creando el grupo $2 ..."
sudo groupadd "$2"
echo "Grupo $2 creado."
echo "Creando usuarios..."
lineas=$(wc -l $1 | cut -d\ -f1) #numero de lineas que tiene alumnos.txt
for (( i = 1; i <= $lineas; i++ )); do
sudo useradd -g $2 $(cat $1 | head -n $i | tail -1 | cut -d\; -f1) -p $(cat $1 | head -n $i | tail -1 | cut -d\; -f4)
done
fi
else
echo "No existe el archivo de texto $1 ."
fi
After executing the code with the command:
chmod +x altaalumnos.sh
./altaalumnos.sh alumnos.txt curso2
I make:
cat /etc/passwd
and I see that the users juanmanuel and ander have been created and both belong to the same group. Everything is fine there, the problem is that when I want to change the user to know if the password is the one in the .txt I do the command:
su juanmanuel
I put the password 77776666T but it tells me authentication failure and with ander the same. I have tried to put other data in the .txt like: daniel;garcia;perez;1234 and it keeps giving me the same error.