Created
January 15, 2023 17:05
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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