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
- Python: Ensure you have Python installed. Most Linux distributions come with it pre-installed.
-
Package Managers: This script supports
apt
andyum
, 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",
]
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)
Step 3: Running the Script
- Save the script as
install_packages.py
. - Make the script executable and run it:
chmod +x install_packages.py
python3 install_packages.py
This script automatically determines the package manager based on the Linux distribution and installs the specified packages.
Step 4: Adding Customizations
-
Error Handling: The
subprocess.CalledProcessError
exception ensures that if a package fails to install, the script will report it without stopping. - Logging: You can add logging to a file to keep track of installations.
-
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)
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
- Consistency: Ensures that the same packages and versions are installed across systems.
- Efficiency: Saves time by automating repetitive tasks.
- 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
Top comments (1)
Great tutorial! I also like using Python because it's much easier to handle errors and write reliable scripts compared to bash.