Automating Linux User Creation with Bash Scripting
Tags: aws, devops, linux, bash
Published: 2024-07-03 12:27:37

Introduction:
Streamlining the process of creating and managing multiples users account in an organization where quite a number of developers have been recently onboarded can be very challenging for a SysOps engineer. Automating these tasks not only saves time but also ensures consistency and accuracy. This article will guide you through a Bash script that automates the process of creating users and groups on a Linux system. We will create a script that creates users and groups, sets passwords, and manages permissions. The script and article are part of the HNG Internship task, and you can learn more about the program by visiting the following links (https://hng.tech/internship) and (https://hng.tech/premium)

Script Breakdown
Prerequisites
Ensure that your system is authorized to create users, groups, and make changes to system files. To successfully run the script, you must have sudo access.

Script Overview:

# Set the log file and password file

```
LOG_FILE=/var/log/user_management.log
PASSWORD_FILE=/var/secure/user_passwords.txt
```

The script starts with a shebang (#!/bin/bash), indicating that it should be run in the Bash shell. It then sets the paths for the log file and the password file. These files will store logs of user creation actions and the generated passwords, respectively.

# Function to Create a User and Group

```
create_user() {
  username=$1
  groups=$2

  # Create the user group
  groupadd ${username}

  # Create the user and set the password
  useradd -m -g ${username} -G ${groups} ${username}
  password=$(generate_password)
  echo "${username}:${password}" | chpasswd

  # Set ownership and permissions for the home directory
  chown ${username}:${username} /home/${username}
  chmod 700 /home/${username}

  # Log the action
  echo "Created user ${username} with groups ${groups}" >> ${LOG_FILE}
}
```
The create_user function takes two arguments: the username and the groups the user should belong to. It performs the following actions:

Creates a user-specific group with groupadd.
Creates the user with useradd, assigns the user to their own group, and any additional groups.
Generates a random password using the generate_password function and sets it for the user with chpasswd.
Sets the ownership and permissions of the user's home directory.
Logs the creation action to the specified log file.

# Function to Generate a Random Password

```
generate_password() {
  < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32}; echo
}
```

The generate_password function uses /dev/urandom to generate a stream of random characters, filters them to include only alphanumeric characters, and then extracts a password of a specified length (default is 32 characters).

# Reading the Input File

```
while IFS=';' read -r username groups; do
  # Ignore whitespace
  username=$(echo ${username} | tr -d '[:space:]')
  groups=$(echo ${groups} | tr -d '[:space:]')
```

  # Create the user and group
  

```
create_user ${username} ${groups}
done < "$1"
```

This section reads the input file line by line, splitting each line into the username and groups based on the semicolon (;) delimiter. It removes any whitespace from the username and groups, then calls the create_user function to create the user and their groups.

# Writing Passwords to the Password File

```
echo "Username,Password" > ${PASSWORD_FILE}
for user in $(cut -d: -f1 ${PASSWORD_FILE}); do
  password=$(grep ${user} ${PASSWORD_FILE} | cut -d: -f2)
  echo "${user},${password}" >> ${PASSWORD_FILE}
```
done

This part initializes the password file with a header (Username,Password), then iterates through each user, extracts their password from the log file, and writes it to the password file.

# Setting Permissions for the Password File

```
chmod 600 ${PASSWORD_FILE}
```

Finally, the script sets the permissions of the password file to 600, ensuring that only the file owner (root) can read it.

Usage:
To use this script, create a text file (users.txt) containing usernames and their respective groups in the format user;group1,group2,.... For example:

Lily_Johnson;hr,management
David_williams;sales,marketing
Grace_Paterson;it,developers

Run the script with the text file as an argument:
sudo bash create_users.sh users.txt


# Conclusion
This script automates the creation of users and groups, sets up home directories with appropriate permissions, generates random passwords, and logs all actions. By using this script, system administrators can efficiently manage user accounts, ensuring consistency and security.

By automating user management tasks, administrators can focus on more critical aspects of their work, improving overall system efficiency and security. This script serves as a robust foundation for further customization and integration into larger automation workflows.