Python Scripts for RHEL: Automate User Management, Monitoring & Backups

System administration often involves repetitive tasks such as file management, user account creation, service monitoring, and system backups. While Linux-based operating systems like Red Hat Enterprise Linux (RHEL) offer various tools to manage these tasks, automation can help save time, reduce human error, and improve overall efficiency.

Python, a high-level programming language, is an excellent tool for automating system administration tasks. It is easy to learn, has a rich set of libraries, and provides flexibility to perform a wide range of administrative operations.

In this article, we will explore how to use Python scripts for automating common system administration tasks on RHEL.

Prerequisites: What You Need Before Automating with Python on RHEL

Before you start automating system administration tasks using Python on RHEL, it’s important to ensure that the necessary software and privileges are in place.

You will need a running RHEL system to begin working with Python scripts for automation, which could be a physical or virtual machine.

If you’re new to RHEL or Linux in general, you can download a trial version of RHEL or install a free alternative like Alma Linux or Rocky Linux (which is binary-compatible with RHEL) to practice.

Next, you need to install Python, which comes pre-installed on RHEL. If it is not installed, you can install it using the yum package manager.

sudo yum install python3

Once Python 3 is installed, you can check the installation again:

python3 --version

1. Automating User Management

Managing user accounts is a common administrative task, and Python’s subprocess module lets you easily add, remove, and modify users by interacting with the shell.

Creating a User

Here’s a simple Python script that automates the process of adding a new user:

import subprocess

def create_user(username):
    try:
        # Create a user using the useradd command
        subprocess.run(['sudo', 'useradd', username], check=True)
        print(f"User '{username}' created successfully.")
    except subprocess.CalledProcessError:
        print(f"Failed to create user '{username}'.")

if __name__ == "__main__":
    user_name = input("Enter the username to create: ")
    create_user(user_name)

Deleting a User

To delete a user, you can use a similar approach with the userdel command.

import subprocess

def delete_user(username):
    try:
        subprocess.run(['sudo', 'userdel', username], check=True)
        print(f"User '{username}' deleted successfully.")
    except subprocess.CalledProcessError:
        print(f"Failed to delete user '{username}'.")

if __name__ == "__main__":
    user_name = input("Enter the username to delete: ")
    delete_user(user_name)
Automating User Management with Python
Automating User Management with Python

2. Automating File Management

Automating file management tasks such as file creation, deletion, and permission changes can be a great way to reduce manual effort.

Checking If a File Exists

Here’s a simple script to check if a specific file exists and print a message accordingly:

import os

def check_file_exists(file_path):
    if os.path.exists(file_path):
        print(f"The file '{file_path}' exists.")
    else:
        print(f"The file '{file_path}' does not exist.")

if __name__ == "__main__":
    file_path = input("Enter the file path to check: ")
    check_file_exists(file_path)

Changing File Permissions

You can also automate changing file permissions using Python’s os.chmod() function, which allows you to modify file permissions:

import os

def change_permissions(file_path, permissions):
    try:
        os.chmod(file_path, permissions)
        print(f"Permissions of '{file_path}' changed to {oct(permissions)}.")
    except Exception as e:
        print(f"Failed to change permissions: {e}")

if __name__ == "__main__":
    file_path = input("Enter the file path: ")
    permissions = int(input("Enter the permissions (e.g., 755): "), 8)
    change_permissions(file_path, permissions)
Automating File Management with Python
Automating File Management with Python

3. Automating System Monitoring

Python scripts can be used to monitor system performance and generate alerts when something is wrong.

Monitoring Disk Usage

The shutil module can help you check the available disk space on the root filesystem and print a warning if the disk usage exceeds a threshold.

import shutil

def check_disk_usage(threshold=80):
    total, used, free = shutil.disk_usage("/")
    used_percent = (used / total) * 100

    print(f"Disk usage: {used_percent:.2f}% used.")

    if used_percent > threshold:
        print("Warning: Disk usage is above the threshold!")

if __name__ == "__main__":
    check_disk_usage()

Monitoring System Load

You can also monitor CPU load using Python’s psutil library (which might need to be installed):

pip install psutil

Once installed, use it to fetch system load:

import psutil

def check_system_load():
    load = psutil.getloadavg()
    print(f"System load (1, 5, 15 minute averages): {load}")

    if load[0] > 1.5:
        print("Warning: High system load!")

if __name__ == "__main__":
    check_system_load()
Automating System Monitoring with Python
Automating System Monitoring with Python

4. Automating System Backups

Backups are an essential part of system administration, and you can automate file backups with Python using the shutil module.

Backing Up a Directory

This script automatically backs up a directory by copying it to a specified location using shutil.copytree().

import shutil
import os

def backup_directory(source_dir, backup_dir):
    try:
        # Create backup directory if it doesn't exist
        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)
        
        backup_path = os.path.join(backup_dir, os.path.basename(source_dir))
        shutil.copytree(source_dir, backup_path)
        print(f"Backup of '{source_dir}' completed successfully.")
    except Exception as e:
        print(f"Failed to backup directory: {e}")

if __name__ == "__main__":
    source_directory = input("Enter the source directory to back up: ")
    backup_directory_path = input("Enter the backup destination directory: ")
    backup_directory(source_directory, backup_directory_path)
Conclusion

Automating system administration tasks using Python can save you time and reduce human error. From managing users to monitoring system health and creating backups, Python scripts provide a flexible and powerful solution for administrators.

You can modify and expand these scripts based on your specific needs. Python’s ease of use and extensive library support make it an excellent tool for automating a wide variety of system administration tasks on RHEL and other Linux distributions.

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

5 Comments

Leave a Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.