Python is the most popular programming language in the world — and for good reason. It is readable, versatile, and incredibly powerful. Whether you want to automate boring tasks, build web applications, analyze data, or dive into machine learning, Python is the tool that can do it all.
And there is no better platform to develop Python on than Linux. Python comes pre-installed on most Linux distributions, integrates seamlessly with the system, and gives you access to powerful development tools right from the terminal.
Why Python on Linux?
- Pre-installed: Most Linux distributions include Python out of the box
- Native integration: Python scripts can directly interact with Linux system tools
- Package management: pip and virtual environments work flawlessly
- Server deployment: Your Python apps will run on Linux servers in production
- Development tools: vim, VS Code, PyCharm all have excellent Linux support
- Automation: Python is the go-to language for system administration scripts
Setting Up Python on Linux
# Check if Python is already installed
python3 --version
# Install Python (if needed)
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip python3-venv python3-dev
# RHEL/AlmaLinux
sudo dnf install python3 python3-pip python3-devel
# Verify pip (package installer)
pip3 --version
Virtual Environments — Your Best Friend
Virtual environments keep each project's dependencies isolated. This prevents conflicts between projects and keeps your system clean.
# Create a project directory
mkdir ~/my-python-project && cd ~/my-python-project
# Create a virtual environment
python3 -m venv venv
# Activate it
source venv/bin/activate
# Install packages — they stay inside this environment
pip install requests flask pandas
# Save your dependencies
pip freeze > requirements.txt
# Deactivate when done
deactivate
Python Basics: The Building Blocks
Variables and Data Types
# Python uses dynamic typing — no need to declare types
name = "Linux" # String (text)
version = 6.1 # Float (decimal number)
cores = 8 # Integer (whole number)
is_awesome = True # Boolean (True/False)
distros = ["Ubuntu", "Fedora", "Debian"] # List
server = {"ip": "10.0.0.1", "port": 22} # Dictionary
# f-strings for easy formatting (Python 3.6+)
print(f"Running {name} kernel {version} on {cores} cores")
# Type checking
print(type(name)) # <class 'str'>
print(type(cores)) # <class 'int'>
Control Flow
# If/elif/else
disk_usage = 85
if disk_usage > 90:
print("CRITICAL: Disk almost full!")
elif disk_usage > 75:
print("WARNING: Disk usage is high")
else:
print("OK: Disk usage is normal")
# For loops
services = ["nginx", "postgresql", "ssh", "cron"]
for service in services:
print(f"Checking {service}...")
# List comprehension (Pythonic way)
even_numbers = [x for x in range(20) if x % 2 == 0]
uppercase_services = [s.upper() for s in services]
📚 Start Learning Python
Whether you are a complete beginner or want to deepen your knowledge:
- Python for Absolute Beginners — €14.90 — No prior experience needed, learn from scratch
- Python Programming: 200 Practice Exercises — €9.90 — Learn by doing with hands-on challenges
- Python 3 Fundamentals — €19.90 — Deep dive into Python core features
Functions — Reusable Code Blocks
# Basic function
def greet(name):
return f"Hello, {name}!"
print(greet("Linux")) # Hello, Linux!
# Function with default parameters
def check_port(host, port=22, timeout=5):
"""Check if a port is open on a host."""
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
result = sock.connect_ex((host, port))
return result == 0
finally:
sock.close()
# Lambda functions (small anonymous functions)
servers = [
{"name": "web1", "load": 75},
{"name": "web2", "load": 45},
{"name": "db1", "load": 90},
]
sorted_servers = sorted(servers, key=lambda s: s["load"])
Object-Oriented Programming (OOP)
OOP lets you organize code into reusable blueprints called classes. This is essential for larger projects.
class Server:
"""Represents a Linux server."""
def __init__(self, hostname, ip_address, os="Ubuntu"):
self.hostname = hostname
self.ip = ip_address
self.os = os
self.services = []
self.is_online = True
def add_service(self, service_name, port):
self.services.append({"name": service_name, "port": port})
print(f"[{self.hostname}] Added {service_name} on port {port}")
def status(self):
state = "ONLINE" if self.is_online else "OFFLINE"
return f"{self.hostname} ({self.ip}) - {state} - {len(self.services)} services"
# Inheritance
class WebServer(Server):
def __init__(self, hostname, ip_address, web_server="nginx"):
super().__init__(hostname, ip_address)
self.web_server = web_server
self.sites = []
def deploy_site(self, domain):
self.sites.append(domain)
print(f"[{self.hostname}] Deployed {domain} via {self.web_server}")
# Usage
web = WebServer("web-prod-01", "10.0.1.10")
web.add_service("nginx", 443)
web.deploy_site("example.com")
print(web.status())
📚 Master Python OOP
- Mastering Python OOP — 2nd Edition (2026) — €7.90 — Updated OOP patterns and best practices
- Mastering Python OOP — 1st Edition — €6.90 — Solid OOP foundations
File Handling
# Reading a file
with open("/var/log/syslog", "r") as f:
first_10_lines = [next(f) for _ in range(10)]
print("".join(first_10_lines))
# Writing a file
from datetime import datetime
with open("report.txt", "w") as f:
f.write("Server Status Report\n")
f.write("=" * 40 + "\n")
f.write(f"Generated: {datetime.now()}\n")
# Reading CSV
import csv
with open("servers.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['hostname']} - {row['ip']}")
# Working with JSON
import json
config = {
"database": {"host": "localhost", "port": 5432},
"cache": {"enabled": True, "ttl": 300}
}
with open("config.json", "w") as f:
json.dump(config, f, indent=2)
with open("config.json", "r") as f:
loaded = json.load(f)
print(loaded["database"]["host"])
Practical Linux Automation with Python
Python shines when automating system administration tasks. Here are real-world scripts you can use today.
System Monitoring Script
#!/usr/bin/env python3
"""Monitor disk, CPU, and memory usage."""
import shutil
import psutil
from datetime import datetime
def check_system():
print(f"\nSystem Health Check - {datetime.now().strftime('%Y-%m-%d %H:%M')}")
print("-" * 50)
# Disk usage
disk = shutil.disk_usage("/")
disk_pct = (disk.used / disk.total) * 100
status = "CRITICAL" if disk_pct > 90 else "WARNING" if disk_pct > 75 else "OK"
print(f"Disk: {disk_pct:.1f}% used [{status}]")
# Memory
mem = psutil.virtual_memory()
status = "CRITICAL" if mem.percent > 90 else "WARNING" if mem.percent > 75 else "OK"
print(f"Memory: {mem.percent}% used [{status}]")
# CPU
cpu_pct = psutil.cpu_percent(interval=1)
status = "CRITICAL" if cpu_pct > 90 else "WARNING" if cpu_pct > 75 else "OK"
print(f"CPU: {cpu_pct}% [{status}]")
check_system()
Log File Analyzer
#!/usr/bin/env python3
"""Analyze Nginx access logs for traffic patterns."""
import re
from collections import Counter
from pathlib import Path
def analyze_log(log_path="/var/log/nginx/access.log"):
if not Path(log_path).exists():
print(f"Log file not found: {log_path}")
return
ips = Counter()
pages = Counter()
pattern = r'(\d+\.\d+\.\d+\.\d+).*?"(\w+) (.+?) HTTP.*?" (\d+)'
with open(log_path) as f:
for line in f:
match = re.search(pattern, line)
if match:
ip, method, path, status = match.groups()
ips[ip] += 1
pages[path] += 1
print(f"\nTotal requests: {sum(ips.values()):,}")
print(f"\nTop 10 IP addresses:")
for ip, count in ips.most_common(10):
print(f" {ip:20s} {count:>6,} requests")
analyze_log()
Automated Backup Script
#!/usr/bin/env python3
"""Backup important directories with compression and rotation."""
import os
import tarfile
from datetime import datetime, timedelta
from pathlib import Path
BACKUP_DIR = Path("/backups")
DIRS_TO_BACKUP = ["/etc/nginx", "/var/www", "/home"]
KEEP_DAYS = 7
def create_backup():
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = BACKUP_DIR / f"backup_{timestamp}.tar.gz"
print(f"Creating backup: {backup_file}")
with tarfile.open(backup_file, "w:gz") as tar:
for directory in DIRS_TO_BACKUP:
if os.path.exists(directory):
tar.add(directory)
size_mb = backup_file.stat().st_size / (1024 * 1024)
print(f"Backup complete: {size_mb:.1f} MB")
def cleanup_old_backups():
cutoff = datetime.now() - timedelta(days=KEEP_DAYS)
removed = 0
for f in BACKUP_DIR.glob("backup_*.tar.gz"):
if datetime.fromtimestamp(f.stat().st_mtime) < cutoff:
f.unlink()
removed += 1
print(f"Cleanup: removed {removed} old backups")
create_backup()
cleanup_old_backups()
Web Requests and API Integration
import requests
# Simple GET request
response = requests.get("https://httpbin.org/json")
data = response.json()
print(data)
# Download a file with progress
def download_file(url, filename):
response = requests.get(url, stream=True)
total = int(response.headers.get('content-length', 0))
downloaded = 0
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
downloaded += len(chunk)
if total:
pct = (downloaded / total) * 100
print(f"\rDownloading: {pct:.1f}%", end="")
print(f"\nSaved: {filename}")
# API integration
def get_server_status(api_url, api_key):
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get(f"{api_url}/status", headers=headers)
if response.status_code == 200:
return response.json()
return None
Database Access with Python
import sqlite3
# SQLite — perfect for small projects
conn = sqlite3.connect("servers.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS servers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hostname TEXT NOT NULL,
ip_address TEXT NOT NULL,
os TEXT DEFAULT 'Ubuntu',
status TEXT DEFAULT 'active'
)
""")
cursor.execute(
"INSERT INTO servers (hostname, ip_address, os) VALUES (?, ?, ?)",
("web-01", "10.0.1.10", "AlmaLinux 9")
)
conn.commit()
cursor.execute("SELECT * FROM servers WHERE status = ?", ("active",))
for row in cursor.fetchall():
print(f"Server: {row[1]} ({row[2]}) - {row[3]}")
conn.close()
# PostgreSQL — for production applications
import psycopg2
conn = psycopg2.connect(
host="localhost", database="myapp",
user="appuser", password="secure_password"
)
cursor = conn.cursor()
cursor.execute("SELECT hostname, ip_address FROM servers WHERE status = %s", ("active",))
for hostname, ip in cursor.fetchall():
print(f"{hostname}: {ip}")
conn.close()
📚 Python for Real Projects
- Python and SQLite: Small DB Apps — €16.90 — Build database-driven applications
- Automating Microsoft 365 with Python — €12.90 — Real-world automation projects
- OpenAI API Mastery with Python — €9.90 — Build AI-powered applications
Error Handling
# Always handle errors gracefully
def safe_read_file(filepath):
try:
with open(filepath, "r") as f:
return f.read()
except FileNotFoundError:
print(f"File not found: {filepath}")
return None
except PermissionError:
print(f"Permission denied: {filepath}")
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
# Custom exceptions
class ServerError(Exception):
def __init__(self, hostname, message):
self.hostname = hostname
super().__init__(f"[{hostname}] {message}")
try:
raise ServerError("web-01", "Connection refused on port 443")
except ServerError as e:
print(f"Server error: {e}")
Essential Python Tools for Linux
| Tool | Purpose | Install |
|---|---|---|
| pip | Package installer | Included with Python |
| venv | Virtual environments | python3 -m venv |
| black | Code formatter | pip install black |
| flake8 | Linter (code quality) | pip install flake8 |
| pytest | Testing framework | pip install pytest |
| ipython | Interactive shell | pip install ipython |
| requests | HTTP library | pip install requests |
| fabric | Remote server automation | pip install fabric |
Project Ideas to Build Your Skills
- Server Health Dashboard: Monitor multiple servers and display status in a terminal UI
- Log Analyzer: Parse and visualize Nginx/Apache logs with charts
- Automated Backup System: Compress, encrypt, and rotate backups with notifications
- Network Scanner: Scan your local network for active devices and open ports
- Config File Manager: Template and deploy configuration files across servers
- REST API: Build a simple API with Flask to manage server inventory
- Chatbot: Create a Telegram or Discord bot for server notifications
- Web Scraper: Collect and compare prices, product data, or news automatically
Conclusion
Python on Linux is a powerful combination that opens doors to system administration, web development, data science, and automation. Start with the basics, practice with real scripts, and gradually take on larger projects. The scripts in this guide are not just examples — they are tools you can adapt and use in your daily work.
The Python ecosystem is enormous, but you do not need to learn everything at once. Focus on solving one real problem at a time, and your skills will grow naturally.