Shell Script para agregar un usuario en Linux
En este tutorial, le mostraremos cómo escribir un script de shell para agregar un usuario en Linux. En el script, usaremos el comando useradd para agregar un usuario y el comando groupadd para agregar un usuario al grupo.
Agregar un nuevo usuario usando un script de shell
El siguiente script de shell agrega un nuevo usuario que puede crear un nombre de usuario, un grupo principal, un directorio de inicio y un shell. Estamos usando el comando useradd para crear un usuario.
#!/bin/bash while [ x$username = "x" ]; do read -p "Please enter the username you wish to create : " username if id -u $username >/dev/null 2>&1; then echo "User already exists" username="" fi done while [ x$group = "x" ]; do read -p "Please enter the primary group. If group not exist, it will be created : " group if id -g $group >/dev/null 2>&1; then echo "Group exist" else groupadd $group fi done read -p "Please enter bash [/bin/bash] : " bash if [ x"$bash" = "x" ]; then bash="/bin/bash" fi read -p "Please enter homedir [/home/$username] : " homedir if [ x"$homedir" = "x" ]; then homedir="/home/$username" fi read -p "Please confirm [y/n]" confirm if [ "$confirm" = "y" ]; then useradd -g $group -s $bash -d $homedir -m $username fi
Resultado de la muestra
sudo ./linux_user.sh Please enter the username you wish to create : test Please enter the primary group. If group not exist, it will be created : test Please enter bash [/bin/bash] : Please enter homedir [/home/test] : Please confirm [y/n]y 22:12:58 [test@Desktop] :~ id test uid=1003(test) gid=1003(test) groups=1003(test)
Más información sobre el guión línea por línea
#Escribir en la consola pide ingresar al grupo y guardar la entrada en la variable de grupo
read -p «Introduzca el grupo principal. Si el grupo no existe, se creará:» grupo
# comprobar si el grupo ya existe
si id -g $ grupo> / dev / null 2> & 1; entonces
# solo advierte que el grupo ya existe
echo «El grupo existe»
demás
#si el grupo no existe, cree uno más
groupadd $ grupo
fi
# fin del ciclo while
hecho
# solicitar ingresar al bash preferido
read -p «Por favor ingrese bash [/bin/bash] : «bash
# comprobar si no hay entrada
si [ x»$bash» = «x» ]; entonces
# si no hay entrada, use bash predeterminado
bash = «/ bin / bash»
fi
# solicitar ingresar al hogar preferido
read -p «Por favor ingrese homedir [/home/$username] : «homedir
# comprobar si no hay entrada
si [ x»$homedir» = «x» ]; entonces
# si no hay entrada, use homedir predeterminado
homedir = «/ home / $ nombre de usuario»
fi
# solicitar confirmar todas las entradas
read -p «Confirma [y/n]»confirmar
#if entrada y
si [ «$confirm» = «y» ]; entonces
#comando para agregar un usuario con toda la información ingresada
useradd -g $ grupo -s $ bash -d $ homedir -m $ nombre de usuario
fi