The following script is supposed to create a user and generate a random password on an Ubuntu machine:
#!/bin/bash
#Script should execute with sudo/root access
if [[ "${UID}" -ne 0 ]]
then
echo "Please run with sudo or root"
exit 1
fi
#User should provide atleast one argument as username else guide him
if [[ "${#}" -lt 1 ]]
then
echo "Usage: ${0} USER_NAME [COMMENT]..."
echo "Create a user with name USER_NAME and comments field of COMMENT"
exit 1
fi
#Store 1st argument as user name
USER_NAME="${1}"
#In case of more than one argument, store it as account comments
shift
COMMENT="${@}"
#Create a password
PASSWORD=$(date +%s%N)
#Create the user
useradd -c "$COMMENT" -m $USER_NAME
#Check if user is successfully created or not
if [[ $? -ne 0 ]]
then
echo "The Account could not be created"
exit 1
fi
#Set the password for the user
echo $PASSWORD | passwd --stdin $USER_NAME
#Check if password is successfully set or not
if [[ $? -ne 0 ]]
then
echo "The password could not be set"
exit 1
fi
#Force password change on first login
passwd -e $USER_NAME
#Display username, password and the host where the user was created
echo
echo "Username: $USER_NAME"
echo
echo "Password: $PASSWORD"
echo
echo "Hostname: $(hostname)"
Output:
root@Sengh:/home/sengh/scripts# bash user_create.sh singh this is a
passwd: unrecognized option '--stdin'
Usage: passwd [options] [LOGIN]
Options:
-a, --all report password status on all accounts
-d, --delete delete the password for the named account
-e, --expire force expire the password for the named account
-h, --help display this help message and exit
-k, --keep-tokens change password only if expired
-i, --inactive INACTIVE set password inactive after expiration
to INACTIVE
-l, --lock lock the password of the named account
-n, --mindays MIN_DAYS set minimum number of days before password
change to MIN_DAYS
-q, --quiet quiet mode
-r, --repository REPOSITORY change password in REPOSITORY repository
-R, --root CHROOT_DIR directory to chroot into
-P, --prefix PREFIX_DIR directory prefix
-S, --status report password status on the named account
-u, --unlock unlock the password of the named account
-w, --warndays WARN_DAYS set expiration warning days to WARN_DAYS
-x, --maxdays MAX_DAYS set maximum number of days before password
change to MAX_DAYS
The password could not be set
--stdinisn't a valid option forpasswd.passwdmight have that option. But if yours doesn't, then it doesn't.passwd: unrecognized option '--stdin'message.blahand a chicken salad magically appeared on his desk. But if I write in the shellblah, I get the messageblah: Command not found. How to resolve it?