Un ejemplo de clase sencillo para estudiar los pasos realizados al momento de crear un nuevo usuario en nuestro sistema:
root
#!/bin/bash useradd $1 passwd $1 addgroup $1 usermod -G$1 -a $1 cp -r /etc/skel /home/$1 chown -R $1:$1 /home/$1 chmod -R g+rx /home/$1 chmod -R g-w /home/$1 chmod -R o-rwx /home/$1
Un paso interesante sería agregar a éste script controles para los parámetros recibidos, por ejemplo:
Para esto, deberemos agregar las siguientes preguntas:
Control de cantidad parámetros:
if [ $# -lt 1 ]; then echo "Faltan parámetros!" exit 1 fi
Control de existencia de usuario/grupo:
cat /etc/passwd | cut -f1 -d":" | grep "^$1$" if [ $? -eq 0 ]; then echo "Atención, el usuario '$1' ya existe!" exit 2 fi cat /etc/group | cut -f1 -d":" | grep "^$1$" if [ $? -eq 1 ]; then addgroup $1 fi
El resultado quedaría de la siguiente forma:
#!/bin/bash if [ $# -lt 1 ]; then echo "Faltan parámetros!" exit 1 fi cat /etc/passwd | cut -f1 -d":" | grep "^$1$" if [ $? -eq 0 ]; then echo "Atención, el usuario '$1' ya existe!" exit 2 fi useradd $1 passwd $1 cat /etc/group | cut -f1 -d":" | grep "^$1$" if [ $? -eq 1 ]; then addgroup $1 fi usermod -G$1 -a $1 cp -r /etc/skel /home/$1 chown -R $1:$1 /home/$1 chmod -R g+rx /home/$1 chmod -R g-w /home/$1 chmod -R o-rwx /home/$1 exit 0
Esta variación permite crear múltiples usuarios en un mismo paso:
#!/bin/bash if [ $# -lt 1 ]; then echo "Faltan parámetros!" exit 1 fi for usuario in $@; do cat /etc/passwd | cut -f1 -d":" | grep "^$usuario$" if [ $? -eq 0 ]; then echo "Atención, el usuario '$usuario' ya existe!" exit 2 fi useradd $usuario passwd $usuario cat /etc/group | cut -f1 -d":" | grep "^$usuario$" if [ $? -eq 1 ]; then addgroup $usuario fi usermod -G $usuario -a $usuario cp -r /etc/skel /home/$usuario chown -R $usuario:$usuario /home/$usuario chmod -R g+rx /home/$usuario chmod -R g-w /home/$usuario chmod -R o-rwx /home/$usuario done exit 0