Last active
June 7, 2021 07:47
-
-
Save bijoy26/7985a14790bf1d91957d3f293eaf28f8 to your computer and use it in GitHub Desktop.
Create a new Debian based non-root user with specified group
This file contains 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
#!/bin/bash | |
##################################### | |
# File: spawn_user.sh | |
# Description: Create a new Debian based non-root user with specified group | |
# Created: Thursday, 2nd June 2021 | |
# Author: Anjum Rashid | |
# ----- | |
# Last Modified: Tuesday, Thursday, 3rd June 2021 | |
# ----- | |
##################################### | |
# make sure to run script as root or sudoer (sudo ./spawn_user.sh) | |
function collectUserInfo() { | |
echo "Enter new username:" | |
read username | |
checkExistingUser | |
echo "Enter new password:" | |
read password | |
echo "Enter groupname (existing) to assign:" | |
read group | |
checkExistingGroup | |
} | |
function checkExistingUser(){ | |
# check if 'id' finds a user or not | |
# 'id -u username' displays the uid only. '$?' contains the return status (0 or 1) | |
status_code=$(id -u "$username" &>/dev/null; echo $?) | |
if [[ $status_code -eq 1 ]] ; then | |
echo 'Cool choice!' | |
else | |
echo 'User already exists. Try again with a different username' | |
exit $status_code | |
fi | |
} | |
function checkExistingGroup(){ | |
# 'grep group /etc/group' displays matching group info | |
status_code_grp=$(grep -q $group /etc/group; echo $?) | |
if [[ $status_code_grp -eq 1 ]] ; then | |
echo "Group "$group" does not exist. Try again with an existing group" | |
exit $status_code_grp | |
else | |
echo ""$group" group selected for assignment." | |
fi | |
} | |
function setupNewUser() { | |
echo -e "\n################## STATUS LOG ##################\n" | |
# add new user, set group, create new home directory | |
useradd -G $group -m $username | |
echo "new user $username created and user group $group assigned!" | |
# update new user password by piping from STDIN | |
echo ""$username":"$password"" | chpasswd | |
echo "user password for $username is set!" | |
# change the default user shell to bash | |
chsh -s /bin/bash $username | |
echo "user $username shell updated to bash!" | |
} | |
function verifyUser() { | |
echo -e "\n################## NEW ENTRIES ##################\n" | |
echo -e "User entry (etc/passwd):\n\n\t$(grep "$username" /etc/passwd)\n" | |
echo -e "Password entry (etc/shadow):\n\n\t$(grep "$username" /etc/shadow)\n" | |
echo -e "Group entry (etc/group):\n\n\t$(grep "$group" /etc/group)\n" | |
} | |
collectUserInfo | |
setupNewUser | |
verifyUser |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment