Skip to content

Instantly share code, notes, and snippets.

@rus364
Created May 27, 2024 07:22
Show Gist options
  • Save rus364/7fa4065d51d97f119035dd62d4824d36 to your computer and use it in GitHub Desktop.
Save rus364/7fa4065d51d97f119035dd62d4824d36 to your computer and use it in GitHub Desktop.
Add user to Debian or Ubuntu
#!/bin/bash
user="<user_name>"
key="<user_key>"
users_home=/home
sudoers_filename="99-transparent-sudoers"
dpkg-query -W sudo || apt update && apt install -y sudo
str=$(grep "PermitEmptyPasswords" /etc/ssh/sshd_config)
if [[ ${str} =~ ^# || ${str} =~ no$ ]]; then
echo "PermitEmptyPasswords is disabled."
else
sed -i 's~^PermitEmptyPasswords .*$~PermitEmptyPasswords no~g' /etc/ssh/sshd_config
service ssh restart || service sshd restart
echo "PermitEmptyPasswords has been disabled."
fi
# Add user
if [[ ! $(getent passwd ${user}) ]]; then
useradd ${user} -m -s /bin/bash
echo
echo "${user} user has been created."
else
echo
echo "${user} user already exists."
fi
# Add public key
if [[ ! -f ${users_home}/${user}/.ssh/authorized_keys ]]; then
mkdir -p ${users_home}/${user}/.ssh/
chown ${user}:${user} ${users_home}/${user}/.ssh/
chmod 0700 ${users_home}/${user}/.ssh/
echo ${key} >> ${users_home}/${user}/.ssh/authorized_keys
chown ${user}:${user} ${users_home}/${user}/.ssh/authorized_keys
chmod 0600 ${users_home}/${user}/.ssh/authorized_keys
echo
echo "Public key has been added for ${user} user."
else
echo
echo "Public key already set for ${user} user."
fi
if [[ ! -d /etc/sudoers.d/ ]]; then
echo "Sudo is not installed. You need to install it manually."
elif [[ ! -f /etc/sudoers.d/${sudoers_filename} ]]; then
echo "${user} ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/${sudoers_filename}
chmod 0440 /etc/sudoers.d/${sudoers_filename}
echo
echo "${user} user has been added to sudoers."
else
echo
echo "/etc/sudoers.d/${sudoers_filename} file already exists. Check that the ${user} user is in this file..."
if [[ ! $(grep "${user} ALL=(ALL) NOPASSWD:ALL" /etc/sudoers.d/${sudoers_filename}) ]]; then
echo "${user} ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/${sudoers_filename}
chmod 0440 /etc/sudoers.d/${sudoers_filename}
echo "${user} user has been added to sudoers."
else
echo
echo "${user} user already has administrative privileges."
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment