DEV Community

Olatunbosun Salako
Olatunbosun Salako

Posted on

User and Group Management Script

Script Explanation
The script automates the creation of users and groups on a Linux system, assigns users to specified groups, sets random passwords, and logs the operations.

  1. Argument Check
    Image description
    The script checks if exactly one argument (the input file) is provided. If not, it displays an error message and exits.

  2. Setting up Variables and Directory and File Setup

Image description

  • - Assigns the input filename to the variable filename.
  • - Defines the path for the password file (passwd) and the log file (logfile).
  • - Creates the /var/secure directory if it does not exist.
  • - Creates or updates the password file (/var/secure/user_passwords.txt) and sets its permissions to 600 (read-write for the owner only).
  • - Creates the /var/log directory if it does not exist.
  • - Creates or updates the log file (/var/secure/user_management.log) and sets its permissions to 644 (read-write for the owner, read-only for others).

3.** Processing the Input File**

Image description

  • Reads the input file line by line, splitting each line into user and groups based on the ; delimiter.
  • Trims whitespace from username and groups.

4.** User Creation **

Image description

  • Checks if the user already exists using id -u.
  • If the user does not exist, creates the user and logs the action.
  1. Group Creation and Assigning of users

Image description

  • Splits the groups string into an array of individual group names.
  • For each group, checks if it exists using getent group.
  • If the group does not exist, creates the group and logs the action.
  • Adds the user to each group and logs the action.
  1. *Password Setting *

Image description

  • Generates a random password using openssl rand -base64 12.
  • Sets the user's password using chpasswd.
  • Logs the password setting action

Thanks for reading...
Olatunbosun Salako
Devops engineer
hng tech internship

Top comments (0)