Skip to content

Instantly share code, notes, and snippets.

@agent47nh
Created January 15, 2023 17:05
Show Gist options
  • Save agent47nh/86e0425dfe094a326c1cd88d4f936671 to your computer and use it in GitHub Desktop.
Save agent47nh/86e0425dfe094a326c1cd88d4f936671 to your computer and use it in GitHub Desktop.
Add user with SSH key, first argurment must be a valid username and second argument should be a valid SSH key. It also adds user to sudoers file, enabling the user to run super user command without password.
#!/usr/bin/env bash
NEWUSER="$1"
SSHKEY="$2"
# run script as superuser
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit 1
fi
if [ -z "$NEWUSER" ]; then
echo "No username provided"
exit 2
fi
if [ -z "$SSHKEY" ]; then
echo "No SSH key provided"
exit 3
fi
# check if user exists
if id -u "$NEWUSER" >/dev/null 2>&1; then
echo "User $NEWUSER already exists"
exit 4
fi
# check if adduser command exists
if ! command -v adduser >/dev/null 2>&1; then
echo "adduser command not found"
exit 5
fi
# check if usermod command exists
if ! command -v usermod >/dev/null 2>&1; then
echo "usermod command not found"
exit 6
fi
adduser "$NEWUSER" \
&& usermod -aG wheel "$NEWUSER" \
&& mkdir /home/"$NEWUSER"/.ssh \
&& touch /home/"$NEWUSER"/.ssh/authorized_keys \
&& echo "$SSHKEY" | tee /home/"$NEWUSER"/.ssh/authorized_keys > /dev/null \
&& chmod 700 /home/"$NEWUSER"/.ssh/ \
&& chmod 600 /home/"$NEWUSER"/.ssh/authorized_keys \
&& chown -R "$NEWUSER":"$NEWUSER" /home/"$NEWUSER"/.ssh/ \
&& dig +short myip.opendns.com @resolver1.opendns.com
# Add user to sudoers
echo "$NEWUSER ALL=(ALL) NOPASSWD:ALL" | tee -a /etc/sudoers > /dev/null
# Add user to sshd_config
echo "AllowUsers $NEWUSER" | tee -a /etc/ssh/sshd_config > /dev/null
# Restart sshd
systemctl restart sshd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment