Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Usage: create-user username [any other words for the GECOS field]
- # Usually this would be used as 'create-user smithj John Smith - Accounts
- # Function for hashing the password to SHA512
- hash-passwd() {
- pwdSalt=$(tr -dc '[:alnum:]' < /dev/urandom | tr -d ' ' | fold -w 8 | head -n 1) 2> /dev/null
- pwdSalt="${pwdSalt,,}"
- python -c "import crypt; print crypt.crypt('${1}', '\$6\$${pwdSalt}')"
- }
- # Set our base variables
- newUser="${1:?No Username Supplied}"
- [[ "${2}" ]] && newGecos="${*:2}"
- # Get the new password interactively
- while true; do
- printf '%s\n' "================================"
- echo -ne "Please enter the new password and press [Enter]: "
- read -s newpwdin1
- echo -ne "\nPlease confirm the new password and press [Enter]: "
- read -s newpwdin2
- # Compare the two, if they don't match, try again
- if [[ "${newpwdin1}" != "${newpwdin2}" ]]; then
- echo ""
- read -p "The passwords entered do not match. Press [Enter] to start again."
- true
- else
- # If the passwords match, hash it to a variable
- hashedPass=$(hash-passwd "${newpwdin1}")
- # And give the condition to exit the while loop
- false
- fi
- done
- # Add the user, creating homedir and setting a comment if one is given
- useradd -m -c "${newGecos}" "${newUser}"
- # Set the password
- echo "${newUser}:${hashedPass}" | chpasswd -e
- # Create ed25519 ssh keys
- ssh-keygen -t ed25519 -f /home/"${newUser}"/.ssh/id_ed25519 -q -P ""
- # If we want rsa ssh keys, we use a higher number of bits
- # We can have this alongside the ed25519 key for compatibility with older hosts
- #ssh-keygen -f /home/"${newUser}"/.ssh/id_rsa -q -P "" -b 4096
- # Create a sudoers conf frag, ensuring that it has a blank newline at EOF
- # Ensuring it passes 'visudo' validation, and is installed with
- # the correct ownership and permissions.
- printf -- '%s\n' "some rule text" "" > /tmp/"${newUser}"
- if visudo -c -f /tmp/"${newUser}" &>/dev/null; then
- install -o root -g root -m 440 /tmp/"${newUser}" /etc/sudoers.d/"${newUser}"
- else
- printf '%s\n' "Sudo task failed"
- exit 1
- fi
- # Remove any remnants of that sudoers temp file
- rm -f /tmp/"${newUser}"
- # Echo some predefined text to the authorized keys file
- echo 'sometext' >> /home/"${newUser}"/.ssh/authorized_keys
- # Ensure the authorized_keys file has correct permissions
- chmod 600 /home/"${newUser}"/.ssh/authorized_keys
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement