Skip to content

Instantly share code, notes, and snippets.

@m3mnoch
Created May 16, 2024 23:04
Show Gist options
  • Save m3mnoch/099b75feaa65bf9414b5a6c50182597b to your computer and use it in GitHub Desktop.
Save m3mnoch/099b75feaa65bf9414b5a6c50182597b to your computer and use it in GitHub Desktop.
#!/bin/bash
# Check if the script is run as root
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run as root." >&2
exit 1
fi
# Prompt for the username
read -p "Enter the username for the new user: " username
# Add the new user
useradd -m -s /bin/bash "$username"
if [ $? -ne 0 ]; then
echo "Failed to add user $username" >&2
exit 1
fi
# Add the user to the sudo group
usermod -aG sudo "$username"
if [ $? -ne 0 ]; then
echo "Failed to add user $username to the sudo group" >&2
exit 1
fi
# Create the .ssh directory and authorized_keys file
mkdir -p /home/"$username"/.ssh
touch /home/"$username"/.ssh/authorized_keys
if [ $? -ne 0 ]; then
echo "Failed to create .ssh directory or authorized_keys file for $username" >&2
exit 1
fi
# Set the correct permissions
chown -R "$username":"$username" /home/"$username"/.ssh
chmod 700 /home/"$username"/.ssh
chmod 600 /home/"$username"/.ssh/authorized_keys
if [ $? -ne 0 ]; then
echo "Failed to set the correct permissions for .ssh directory or authorized_keys file for $username" >&2
exit 1
fi
# Prompt for the public key and add it to the authorized_keys file
read -p "Enter the public key for the new user: " pubkey
echo "$pubkey" > /home/"$username"/.ssh/authorized_keys
if [ $? -ne 0 ]; then
echo "Failed to add the public key to authorized_keys file for $username" >&2
exit 1
fi
echo "User $username has been added to the sudo group and .ssh directory has been set up with the correct permissions and the public key."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment