Table of contents
Overview
System administrators and SysOps engineers are frequently entrusted with maintaining user accounts and groups in the dynamic world of modern IT infrastructure. Even though it's a normal process, it may get tedious and error-prone, especially in companies that are growing quickly or have a high employee turnover rate. Automation of user and group management is crucial to overcoming these obstacles. We can expedite these administrative chores and ensure that they are completed swiftly, reliably, and with the least amount of human intervention by utilizing Bash scripting.
This article explores the development of create_users.sh
, a Bash script intended to automate the steps involved in adding users, forming groups, configuring home directories, and handling passwords. The script generates passwords, logs the operations, runs the relevant commands, and reads from a predetermined input file containing users and the groups that belong to them.
Setting
Imagine that a business has recently hired a sizable number of fresh developers. It is required to create user accounts for each developer and assign them to groups corresponding to their access privileges and permissions. Password setup, group assignment, and account creation by hand can be time-consuming and prone to mistakes. Inaccuracies in this procedure may result in access problems, security flaws, and ineffective onboarding.
Automation not only lessens these dangers but also drastically cuts down on the time and effort needed to complete these kinds of repetitive jobs. It guarantees that each new user is configured consistently, with appropriate logs for monitoring and troubleshooting. To further increase the system's resilience, automated scripts can incorporate error handling to handle scenarios in which users or groups already exist gently.
We will look at how to utilize create_users.sh
, a script that combines both efficiency and automation ideas, in this guide. We'll review each component, outline its reasoning and procedures, and show you how to include it in your SysOps toolbox to simplify user and group management.
You will have a working script at the end of this article along with a better knowledge of how automation may improve your administrative procedures and make them more dependable, safe, and efficient. Now let's explore how this script can change the way you administer groups and user accounts in your Linux system.
Prerequisites
Before we proceed with running the create_users.sh
script, ensure you have the following prerequisites in place:
1. Linux Environment:
- The script is intended to run on a Linux system. Ensure you have access to a Linux environment, such as an Ubuntu machine or a Docker container running a Linux image.
2. Administrative Privileges:
- You need to have administrative (root) privileges on the machine where you will run the script. This is required to create users and groups, and to set file permissions.
3. Required Commands:
The script relies on several Linux commands that must be installed and accessible in your environment. Ensure the following commands are available:
- useradd
: Used to create new user accounts.
- chpasswd
: Used to change user passwords.
- groupadd
: Used to create new groups.
- usermod
: Used to modify user accounts.
- getent
: Used to query system databases (e.g., for checking if a group exists).
- openssl
: Used to generate secure random passwords.
4. Input File:
- Prepare a text file containing the usernames and groups in the required format. Each line should be formatted as
username;groups
(e.g.,light;sudo,dev,www-data
).
5. Permissions for Secure Directory:
- Ensure that the directory
/var/secure
can be created and the necessary permissions can be set. This directory will store the generated passwords securely.
6. Logging Directory:
- Ensure that the directory
/var/log
exists and is writable by the script. This is where the activity log will be stored.
7. Installation of OpenSSL:
- OpenSSL is required for generating random passwords. Install it using the package manager of your Linux distribution if it is not already installed:
Script Explanation
Shebang and Argument Check
Shebang
The script begins with a shebang (**#!/bin/bash), which is a special sequence of characters used in Unix-like operating systems. The shebang is placed at the very top of the script and indicates which interpreter should be used to execute the script. In this case, #!/bin/bash tells the system to use the Bash shell to interpret the script.
The shebang is crucial for ensuring that the script is run with the correct interpreter, especially when multiple shell environments are available on the system. It makes the script portable and executable on any system with Bash installed.
Argument Check
Immediately following the shebang, the script includes a section to check if the required argument (the input file) is provided. This is an essential step to ensure the script has all the necessary information to proceed.
In this snippet:
if [ $# -eq 0 ]; then
checks if the number of arguments ($#) passed to the script is zero.echo "Usage: $0 <file>" prints a usage message to the user, indicating how to correctly run the script. $0 represents the name of the script itself.
exit 1 terminates the script with a status code of 1, indicating that an error occurred due to the missing argument.
input_file=$1 assigns the first argument ($1) to the variable input_file, which will be used later in the script to
Input, Log, and Password Files
The script specifies the input file containing the usernames and groups, a log file to record all actions, and a secure password file to store the generated passwords. The log file, located at /var/log/user_management.log, captures the execution details for auditing and troubleshooting. The password file, stored securely at /var/secure/user_passwords.csv, contains the usernames and their randomly generated passwords, with restricted access to ensure confidentiality.
Setup Secure Directory
Creating Secure Directory
The script ensures the existence of a secure directory to store the password file. It creates the directory /var/secure if it doesn't already exist and sets its permissions to 700, ensuring that only the owner has read, write, and execute permissions. This setup protects the sensitive information contained in the password file from unauthorized access.
Clear Previous Logs and Password Files
Initialize Files
Before proceeding with user creation, the script clears any existing content in the log file (/var/log/user_management.log) and the password file (/var/secure/user_passwords.csv). This ensures that the logs and passwords recorded during the current execution are fresh and relevant, preventing any mix-up with previous runs.
Generate Random Passwords
Password Generation Function
The script includes a function to generate random passwords for the users. This function uses openssl rand -base64 12
to create a secure, 12-character password in base64 encoding. Each generated password is unique and complex, enhancing the security of the user accounts created by the script.
Process Input File
Reading and Processing Each Line
The script reads the input file line by line, splitting each line into a username and associated groups using the semicolon (;) as a delimiter. This structured approach ensures each user and their respective groups are processed correctly, and ready for creation and assignment.
User Creation and Group Assignment
Check for Existing User
Before creating a new user, the script checks if the user already exists in the system using the id command. This step prevents duplicate user creation and avoids potential conflicts or errors.
Create User and Set Password
If the user does not already exist, the script creates the user with a home directory and sets a random password generated by the password function. The username and password are then saved securely in the password file.
Add User to Additional Groups
The script parses the additional groups specified for each user and ensures each group exists. It then adds the user to these groups, providing them with the necessary permissions and access rights as defined by the organization's structure.
Logging and Finalization
Logging Actions
Throughout the execution, the script logs each significant action, such as user creation, password setting, and group assignments, to /var/log/user_management.log. This logging facilitates auditing, troubleshooting, and verification of the script's operations, ensuring transparency and accountability.
Completion Message
At the end of the script, a completion message is logged to indicate that the user creation process has finished. This message provides a clear endpoint for the script’s execution, confirming that all specified users and groups have been processed successfully.
Conclusion
Using this script for automated user management significantly improves efficiency and accuracy in handling large-scale user and group creation tasks. It eliminates manual errors, ensures secure password handling, and provides comprehensive logging for auditing purposes. This automation is particularly beneficial for organizations onboarding multiple new hires, streamlining the process and freeing up valuable time for SysOps engineers.
Further Reading
For more resources on DevOps and SysOps roles, visit the HNG Internship websites: