Skip to content

Instantly share code, notes, and snippets.

@mrl22
Last active August 8, 2023 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrl22/f382361b2bda93afb7974b168e9310ca to your computer and use it in GitHub Desktop.
Save mrl22/f382361b2bda93afb7974b168e9310ca to your computer and use it in GitHub Desktop.
Create a Linux user through script
#!/bin/bash
# ------------------------------------------------------------------
# Am i Root user?
if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1
else
password=$(date +%s%N | sha256sum | head -c48)
useradd -s /bin/bash -g backup -m -p "$password" "$username"
if [ $? -eq 0 ]; then
echo "User has been added to system!"
chmod 700 /home/$username
read -p "Public Key : " pubkey
mkdir -p /home/$username/.ssh
echo "$pubkey" > /home/$username/.ssh/authorized_keys
chown -R $username:backup /home/$username/.ssh
chmod 700 /home/$username/.ssh
chmod 600 /home/$username/.ssh/authorized_keys
else
echo "Failed to add a user!"
exit 2
fi
fi
else
echo "Only root may add a user to the system."
exit 2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment