Skip to content

Instantly share code, notes, and snippets.

@lyashevska
Created September 25, 2018 15:24
Show Gist options
  • Save lyashevska/72e39263f1bc326d727d50029a48c7e3 to your computer and use it in GitHub Desktop.
Save lyashevska/72e39263f1bc326d727d50029a48c7e3 to your computer and use it in GitHub Desktop.
add-new-local-user
#!/bin/bash
# Make sure the script is being executed with superuser privileges.
if [[ "${EUID}" -ne 0 ]]; then
echo 'The script requires root priveledges'
exit 1
fi
# supply at least one argument otherwise return an exit status of 1
if [[ "${#}" -lt 1 ]]
then
echo "Usage: ${0} USER_NAME [COMMENT]..."
echo "Create an account name USER_NAME with a comment field of COMMENT"
exit 1
fi
# The first parameter is the user name.
USER_NAME = "${1}"
echo "${USER_NAME}"
# The rest of the parameters are for the account comments.
shift
COMMENT="${@}"
# Generate password.
PASSWORD=$(date +%s%N | sha256sum | head -c48)
# Create the user with the password.
useradd -c "${COMMENT}" -m ${USER_NAME}
# Check to see if the useradd command succeeded.
if [[ "${?}" -ne 0 ]]
then
echo 'The account could not be created.'
exit 1
fi
# Set the password.
echo ${PASSWORD} | passwd --stdin ${USER_NAME}
# Check to see if the passwd command succeeded.
if [[ "${?}" -ne 0 ]]
then
echo 'The password for the account could not be set.'
exit 1
fi
# Force password change on first login.
passwd -e ${USER_NAME}
# Display the username, password, and the host where the user was created.
echo 'username:'
echo "${USER_NAME}"
echo 'password:'
echo "${PASSWORD}"
echo 'host:'
echo "${HOSTNAME}"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment