Automating software installations on Linux using Python.

Trix Cyrus - Nov 1 - - Dev Community

Author: Trix Cyrus

Waymap Pentesting tool: Click Here
TrixSec Github: Click Here

How to Automate Software Installations on Linux Using Python

Automating software installations on Linux with Python can simplify the process of setting up and managing packages across multiple systems. This guide will show you how to use Python to install packages on Linux using the most common package managers: apt (for Debian-based systems) and yum (for Red Hat-based systems).

Prerequisites

  1. Python: Ensure you have Python installed. Most Linux distributions come with it pre-installed.
  2. Package Managers: This script supports apt and yum, which cover most Linux distributions.

Step 1: Create a List of Packages to Install

First, create a list of packages you want to install. This can be a simple Python list. Here’s an example:

packages = [
    "curl",
    "vim",
    "git",
    "htop",
    "python3-pip",
]
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the Installation Function

The following script detects the Linux distribution and uses the appropriate package manager to install the packages from the list.

import os
import subprocess
import platform

# List of packages to install
packages = [
    "curl",
    "vim",
    "git",
    "htop",
    "python3-pip",
]

# Detect the package manager based on the Linux distribution
def detect_package_manager():
    distro = platform.linux_distribution()[0].lower()
    if "debian" in distro or "ubuntu" in distro:
        return "apt"
    elif "red hat" in distro or "centos" in distro:
        return "yum"
    else:
        raise Exception("Unsupported Linux distribution.")

# Function to install packages
def install_packages(packages):
    package_manager = detect_package_manager()

    for package in packages:
        try:
            print(f"Installing {package}...")

            if package_manager == "apt":
                subprocess.run(["sudo", "apt", "update"], check=True)
                subprocess.run(["sudo", "apt", "install", "-y", package], check=True)
            elif package_manager == "yum":
                subprocess.run(["sudo", "yum", "install", "-y", package], check=True)

            print(f"{package} installed successfully!")
        except subprocess.CalledProcessError:
            print(f"Failed to install {package}")

# Run the installation function
if __name__ == "__main__":
    install_packages(packages)
Enter fullscreen mode Exit fullscreen mode

Step 3: Running the Script

  1. Save the script as install_packages.py.
  2. Make the script executable and run it:
   chmod +x install_packages.py
   python3 install_packages.py
Enter fullscreen mode Exit fullscreen mode

This script automatically determines the package manager based on the Linux distribution and installs the specified packages.

Step 4: Adding Customizations

  1. Error Handling: The subprocess.CalledProcessError exception ensures that if a package fails to install, the script will report it without stopping.
  2. Logging: You can add logging to a file to keep track of installations.
  3. Configuration File: You can move the packages list to a configuration file, allowing easy updates without changing the script.

Step 5: Automate Installations on Multiple Machines

For system administrators managing multiple Linux systems, you can expand this script to handle SSH connections, allowing it to install packages remotely.

Example: Installing Packages Remotely Using Paramiko

import paramiko

def install_packages_remotely(host, username, password, packages):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(host, username=username, password=password)

        for package in packages:
            command = f"sudo apt install -y {package}"  # Adjust for the appropriate package manager
            stdin, stdout, stderr = ssh.exec_command(command)
            print(stdout.read().decode())
            print(stderr.read().decode())

        print(f"Packages installed on {host}")

    finally:
        ssh.close()

# Example usage
remote_host = "192.168.1.100"
username = "your_username"
password = "your_password"
install_packages_remotely(remote_host, username, password, packages)
Enter fullscreen mode Exit fullscreen mode

Important: Make sure to replace placeholders with actual values and use SSH keys for authentication instead of passwords for better security.


Benefits of Using This Automation Script

  1. Consistency: Ensures that the same packages and versions are installed across systems.
  2. Efficiency: Saves time by automating repetitive tasks.
  3. Scalability: Easily scalable to multiple systems with minimal changes.

With this approach, you can now set up your Linux environment quickly and efficiently, streamlining the process for personal or team-based setups.

~TrixSec

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .