Automating User and Group Management with a Bash Script
Hello there! I'm Rasheed Bakare, a passionate DevOps Engineer with 2 years of hands-on experience in the exciting world of DevOps. My journey in the realm of technology has been a thrilling one, marked by a relentless pursuit of automation, efficiency, and innovation.
🚀 Professional Experience 🚀
Over the past two years, I've had the privilege of working in diverse environments and contributing to several high-impact DevOps projects. My work primarily revolves around crafting seamless and robust CI/CD pipelines, ensuring continuous integration and continuous delivery for software applications. I've had the opportunity to architect, implement, and optimize CI/CD workflows using tools like Jenkins, GitLab and CI/CD.
🔧 Tool Mastery 🔧
My toolkit is well-equipped with various DevOps technologies and practices. I've wielded Ansible and Terraform to orchestrate infrastructure as code (IaC), streamlining the provisioning and management of cloud resources. Docker and Kubernetes are my trusted companions when it comes to containerization and orchestration, enabling scalable and efficient deployments. Bash scripting and Python have been my allies in crafting automation solutions, from routine tasks to complex system configurations.
💡 Passion for Learning 💡
In the ever-evolving world of technology, I thrive on learning and staying ahead of the curve. I'm continuously exploring emerging DevOps trends, tools, and best practices to deliver optimal solutions.
🤝 Freelance Projects 🤝
Beyond my professional role, I've taken on exciting freelance DevOps projects. These experiences have allowed me to collaborate with a diverse range of clients, each with unique challenges and requirements. Whether it's automating deployment pipelines, optimizing infrastructure costs, or enhancing security postures, I relish the opportunity to make a meaningful impact.
I'm a firm believer in the DevOps philosophy of breaking down silos, fostering collaboration, and delivering value faster to end-users. If you're looking for a DevOps Engineer who's passionate about automation, well-versed in the DevOps toolchain, and dedicated to driving efficiency and reliability, let's connect and explore how we can create exceptional technology solutions together.
📧 Contact Me 📧
Feel free to reach out to me at bakarerasheed.a38@gmail.com or connect with me on https://www.linkedin.com/in/bakare-rasheed-9307b0211 to discuss potential collaborations, share knowledge, or simply geek out about all things DevOps. Let's embark on this exciting DevOps journey together! 🚀
#DevOps #CI/CD #Automation #InfrastructureAsCode #Containerization #Kubernetes #Cloud #Ansible #Terraform #BashScripting #Python #TechEnthusiast
Overview
As a SysOps engineer, one of your primary responsibilities is to manage user accounts and groups efficiently. In this article, we’ll walk through the creation of a Bash script that automates user and group management on a Linux system. This script reads a text file containing employee usernames and group names, creates users and groups as specified, sets up home directories with appropriate permissions, generates random passwords, and logs all actions.
Project Overview
The goal of this project is to simplify and automate the process of user and group management. The script, create_users.sh, takes a text file as input, where each line is formatted as user;groups. The script performs the following tasks:
Creates users and their respective personal groups.
Sets up home directories with proper permissions.
Generates random passwords for users.
Logs all actions to
/var/log/user_management.log.Stores generated passwords securely in
/var/secure/user_passwords.csv.
Requirements
Linux-based operating system (Ubuntu preferred)
opensslfor password generationBasic understanding of Bash scripting
Script Breakdown
Here’s a detailed breakdown of the create_users.sh script:
#!/bin/bash
Log file and secure password storage
LOG_FILE="/var/log/user_management.log" PASSWORD_FILE="/var/secure/user_passwords.csv"
Check if the input file is provided
if [ -z "$1" ]; then echo "Usage: $0 " exit 1 fi
USER_FILE="$1"
Ensure the log file and password file exist
touch "$LOG_FILE" mkdir -p /var/secure touch "$PASSWORD_FILE" chmod 600 "$PASSWORD_FILE"
Process each line in the user file
while IFS=';' read -r username groups; do
Ignore empty lines
[ -z "$username" ] && continue
Remove leading and trailing whitespace from the groups
groups=$(echo "$groups" | xargs)
Create a personal group with the same name as the user
if ! getent group "$username" > /dev/null; then groupadd "$username" echo "$(date) - Group $username created." >> "$LOG_FILE" fi
Create the user if they don't exist
if ! id -u "$username" > /dev/null 2>&1; then useradd -m -g "$username" "$username" echo "$(date) - User $username created with groups: $groups" >> "$LOG_FILE"
# Generate a random password password=$(openssl rand -base64 12) echo "$username:$password" | chpasswd echo "$username,$password" >> "$PASSWORD_FILE" echo "$(date) - Password set for $username" >> "$LOG_FILE"
# Set the correct permissions for the home directory chown -R "$username:$username" "/home/$username" chmod 700 "/home/$username" echo "$(date) - Permissions set for /home/$username" >> "$LOG_FILE" else echo "$(date) - User $username already exists. Skipping creation." >> "$LOG_FILE" fi
Add the user to the additional groups if specified
IFS=',' read -r -a group_array <<< "$groups" for group in "${group_array[@]}"; do if ! getent group "$group" > /dev/null; then groupadd "$group" echo "$(date) - Group $group created." >> "$LOG_FILE" fi usermod -aG "$group" "$username" echo "$(date) - User $username added to group $group" >> "$LOG_FILE" done done < "$USER_FILE"
echo "User creation process completed. Check the log file for details: $LOG_FILE"
Detailed Explanation
Log File and Secure Password Storage:
- The script starts by defining the log file and secure password storage locations. The log file records all actions performed by the script, and the password file stores generated passwords securely.
Check for Input File:
- The script checks if the input file is provided. If not, it displays usage instructions and exits.
Ensure Log and Password Files Exist:
- The script ensures that the log file and password file exist, creating them if necessary. It also sets the appropriate permissions for the password file to ensure it is secure.
Process Each Line in the User File:
- The script reads the input file line by line. For each line, it extracts the username and groups, ignoring empty lines and trimming whitespace from the groups.
Create Personal Group:
- For each user, the script creates a personal group with the same name as the user if it doesn't already exist.
Create User:
- If the user doesn't exist, the script creates the user, assigns them to their personal group, generates a random password, sets the password, and stores it securely. It also sets the correct permissions for the user's home directory.
Add User to Additional Groups:
- The script reads the additional groups from the input file, creates the groups if they don't exist, and assigns the user to these groups.
Logging:
- All actions are logged to
/var/log/user_management.log, and the generated passwords are stored securely in/var/secure/user_passwords.csv.
- All actions are logged to
Running the Script on AWS Ubuntu
- Update the Instance:
sudo apt update
sudo apt install -y openssl
Create and Prepare the Script:
Create the
create_users.shscript.Copy the script content into
create_users.shand save it.Make the script executable.
chmod +x create_users.shCreate the
users.txtFile:Create the
users.txtfile.Add user data to
users.txt.Bakare;sudo,dev,www-data
Rasheed;sudo
Abiola;dev,www-data
Run the Script:
sudo ./create_users.shusers.txtCheck the Log and Password Files:
sudo cat /var/log/user_management.logsudo cat /var/secure/user_passwords.csvConclusion
This Bash script simplifies the process of managing users and groups on a Linux system, making it easier for SysOps engineers to handle these tasks efficiently. By automating user creation, password generation, and group assignments, the script ensures consistency and saves time.
For more information about the HNG Internship and how you can be a part of it, visit HNG Internship and HNG Premium.