Key Code Examples
1. Bash Script โ System Health Check
#!/bin/bash
# system_health.sh โ Basic IT system monitoring script
echo "=== System Health Check ==="
echo "Date: $(date)"
echo ""
# CPU Load
echo "--- CPU Load ---"
uptime
# Memory Usage
echo "--- Memory Usage ---"
free -h
# Disk Usage
echo "--- Disk Usage ---"
df -h /
# Top 5 CPU processes
echo "--- Top 5 CPU Processes ---"
ps aux --sort=-%cpu | head -6
# Network connections
echo "--- Active Network Connections ---"
netstat -tuln 2>/dev/null || ss -tuln
# Check if a service is running
SERVICE="nginx"
if systemctl is-active --quiet $SERVICE; then
echo "$SERVICE is running"
else
echo "$SERVICE is NOT running"
fi
2. Python โ Network Scanner
import socket
import subprocess
from datetime import datetime
def network_scan(network_prefix="192.168.1"):
"""Scan local network for active hosts."""
print(f"Scanning {network_prefix}.0/24 ...")
print(f"Started: {datetime.now()}")
active_hosts = []
for i in range(1, 255):
ip = f"{network_prefix}.{i}"
# Use ping to check if host is active
result = subprocess.run(
["ping", "-n", "1", "-w", "100", ip],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
if result.returncode == 0:
print(f" Host {ip} is ONLINE")
active_hosts.append(ip)
print(f"\nScan complete. {len(active_hosts)} hosts found.")
return active_hosts
# Example usage (Windows)
# hosts = network_scan("192.168.1")
3. PowerShell โ Active Directory User Management
# Create a new AD user
$Name = "John Doe"
$SamAccountName = "jdoe"
$UserPrincipalName = "jdoe@eduverse.com"
$Password = ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force
New-ADUser `
-Name $Name `
-SamAccountName $SamAccountName `
-UserPrincipalName $UserPrincipalName `
-GivenName "John" `
-Surname "Doe" `
-DisplayName $Name `
-AccountPassword $Password `
-Enabled $true `
-Path "OU=Users,DC=eduverse,DC=com"
# Add user to groups
Add-ADGroupMember -Identity "IT-Department" -Members "jdoe"
Add-ADGroupMember -Identity "VPN-Users" -Members "jdoe"
# Get user info
Get-ADUser -Identity "jdoe" -Properties *
Get-ADGroupMember -Identity "IT-Department"
4. Python โ Database Connection & Query
import sqlite3
from contextlib import contextmanager
@contextmanager
def db_connection(db_path):
"""Context manager for database connections."""
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def get_user_count(db_path="company.db"):
with db_connection(db_path) as conn:
cursor = conn.execute("SELECT COUNT(*) as count FROM users")
return cursor.fetchone()["count"]
def get_users_by_department(db_path, department):
with db_connection(db_path) as conn:
cursor = conn.execute(
"SELECT id, name, email FROM users WHERE dept = ?",
(department,)
)
return [dict(row) for row in cursor.fetchall()]
def backup_database(source_path, backup_path):
with sqlite3.connect(source_path) as source:
with sqlite3.connect(backup_path) as backup:
source.backup(backup)
print(f"Backup created: {backup_path}")
# Example usage
# users = get_users_by_department("company.db", "Engineering")
# for user in users:
# print(f" {user['name']} ({user['email']})")
5. Python โ REST API with Flask
from flask import Flask, jsonify, request
app = Flask(__name__)
# In-memory "database"
servers = {
"srv-001": {"name": "web-01", "status": "running", "ip": "10.0.1.10"},
"srv-002": {"name": "db-01", "status": "running", "ip": "10.0.1.20"},
"srv-003": {"name": "app-01", "status": "stopped", "ip": "10.0.1.30"},
}
@app.route("/api/servers", methods=["GET"])
def list_servers():
return jsonify({"servers": list(servers.values()), "count": len(servers)})
@app.route("/api/servers/", methods=["GET"])
def get_server(server_id):
if server_id not in servers:
return jsonify({"error": "Server not found"}), 404
return jsonify(servers[server_id])
@app.route("/api/servers//start", methods=["POST"])
def start_server(server_id):
if server_id not in servers:
return jsonify({"error": "Server not found"}), 404
servers[server_id]["status"] = "running"
return jsonify({"message": f"Server {server_id} started"})
if __name__ == "__main__":
app.run(debug=True, port=5000)
6. Python โ Log File Analyzer
import re
from collections import Counter
from datetime import datetime
def analyze_log(log_file):
"""Parse and analyze a web server log file."""
ip_pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
error_pattern = re.compile(r'\s(4\d{2}|5\d{2})\s')
ip_counter = Counter()
error_counter = Counter()
total_requests = 0
error_count = 0
with open(log_file, 'r') as f:
for line in f:
total_requests += 1
ip_match = ip_pattern.search(line)
if ip_match:
ip_counter[ip_match.group()] += 1
error_match = error_pattern.search(line)
if error_match:
error_count += 1
error_counter[error_match.group().strip()] += 1
report = {
"total_requests": total_requests,
"error_count": error_count,
"error_rate": f"{(error_count/total_requests)*100:.2f}%",
"top_ips": ip_counter.most_common(5),
"error_codes": dict(error_counter),
}
return report
# Example output:
# {
# "total_requests": 50000,
# "error_count": 234,
# "error_rate": "0.47%",
# "top_ips": [("192.168.1.50", 1234), ...],
# "error_codes": {"404": 180, "500": 42, "403": 12}
# }
7. SQL โ IT Asset Management
-- Create IT asset tracking tables
CREATE TABLE employees (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(100) NOT NULL,
department VARCHAR(50),
email VARCHAR(100),
hire_date DATE DEFAULT CURRENT_DATE
);
CREATE TABLE assets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
asset_tag VARCHAR(20) UNIQUE NOT NULL,
type VARCHAR(30), -- laptop, monitor, phone, etc.
brand VARCHAR(50),
model VARCHAR(50),
serial_number VARCHAR(100),
purchase_date DATE,
warranty_expiry DATE,
status VARCHAR(20) DEFAULT 'available'
-- available, assigned, repair, retired
);
CREATE TABLE assignments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
asset_id INTEGER REFERENCES assets(id),
employee_id INTEGER REFERENCES employees(id),
assigned_date DATE DEFAULT CURRENT_DATE,
returned_date DATE,
notes TEXT
);
-- Common IT queries:
-- 1. Find all unassigned laptops
SELECT * FROM assets
WHERE type = 'laptop' AND status = 'available';
-- 2. Find assets under warranty
SELECT asset_tag, brand, model, warranty_expiry
FROM assets
WHERE warranty_expiry > DATE('now');
-- 3. Who has what?
SELECT e.name, e.department, a.asset_tag, a.brand, a.model
FROM employees e
JOIN assignments ass ON e.id = ass.employee_id
JOIN assets a ON ass.asset_id = a.id
WHERE ass.returned_date IS NULL;
8. Python โ Automated Backup Script
import os
import shutil
import gzip
from datetime import datetime
from pathlib import Path
def backup_directory(source_dir, backup_root, compress=True):
"""Create a timestamped backup of a directory."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
folder_name = Path(source_dir).name
backup_name = f"{folder_name}_{timestamp}"
backup_path = Path(backup_root) / backup_name
# Create backup
if compress:
backup_path = backup_path.with_suffix(".tar.gz")
shutil.make_archive(
str(backup_path).replace(".tar.gz", ""),
'gztar', source_dir
)
else:
shutil.copytree(source_dir, backup_path)
print(f"Backup created: {backup_path}")
return backup_path
def cleanup_old_backups(backup_root, days_to_keep=30):
"""Remove backups older than specified days."""
cutoff = datetime.now().timestamp() - (days_to_keep * 86400)
removed = 0
for backup_file in Path(backup_root).iterdir():
if backup_file.stat().st_mtime < cutoff:
if backup_file.is_dir():
shutil.rmtree(backup_file)
else:
backup_file.unlink()
removed += 1
print(f"Removed old backup: {backup_file}")
return removed
# Example usage
# backup_directory("/var/www/html", "/backups/web")
# backup_directory("/etc", "/backups/config")
# cleanup_old_backups("/backups", days_to_keep=90)
9. Python โ Server Monitoring with psutil
import psutil
import time
import smtplib
from email.mime.text import MIMEText
def check_system_health():
"""Check CPU, memory, disk, and network stats."""
report = {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"cpu_percent": psutil.cpu_percent(interval=1),
"memory": {
"total_GB": round(psutil.virtual_memory().total / (1024**3), 2),
"used_GB": round(psutil.virtual_memory().used / (1024**3), 2),
"percent": psutil.virtual_memory().percent,
},
"disk": {
"total_GB": round(psutil.disk_usage('/').total / (1024**3), 2),
"percent": psutil.disk_usage('/').percent,
},
"network": {
"bytes_sent_MB": round(psutil.net_io_counters().bytes_sent / (1024**2), 2),
"bytes_recv_MB": round(psutil.net_io_counters().bytes_recv / (1024**2), 2),
},
"processes": len(psutil.pids()),
}
return report
def send_alert(subject, body, to_email):
msg = MIMEText(body)
msg["Subject"] = f"[ALERT] {subject}"
msg["From"] = "monitor@eduverse.com"
msg["To"] = to_email
# smtplib.SMTP('localhost').send_message(msg)
def monitor_loop():
while True:
health = check_system_health()
if health["cpu_percent"] > 90:
send_alert("High CPU", str(health), "admin@eduverse.com")
if health["memory"]["percent"] > 85:
send_alert("High Memory", str(health), "admin@eduverse.com")
time.sleep(60) # Check every minute
# Example output:
# {
# "timestamp": "2026-10-15 14:30:00",
# "cpu_percent": 23.5,
# "memory": {"total_GB": 16.0, "used_GB": 8.2, "percent": 51.25},
# "disk": {"total_GB": 512.0, "percent": 67.3},
# "network": {"bytes_sent_MB": 1024.5, "bytes_recv_MB": 5120.8},
# "processes": 245
# }
10. YAML โ Docker Compose Configuration
version: "3.8"
services:
web:
image: nginx:latest
ports:
- "80:80"
- "443:443"
volumes:
- ./html:/usr/share/nginx/html
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- app
restart: unless-stopped
networks:
- frontend
- backend
app:
image: eduverse-app:latest
environment:
- DB_HOST=db
- DB_PORT=5432
- DB_NAME=eduverse
- REDIS_HOST=cache
ports:
- "5000:5000"
depends_on:
- db
- cache
restart: unless-stopped
networks:
- backend
db:
image: postgres:15
environment:
POSTGRES_DB: eduverse
POSTGRES_USER: admin
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped
networks:
- backend
cache:
image: redis:7-alpine
ports:
- "6379:6379"
restart: unless-stopped
networks:
- backend
volumes:
pgdata:
networks:
frontend:
backend:
Core Concepts
IT Service Management (ITSM)
Definition: The entirety of activities, policies, and processes used to design, plan, deliver, operate, and control IT services offered to customers.
Key Framework: ITIL (Information Technology Infrastructure Library) โ The most widely adopted ITSM framework with 5 core stages:
- Service Strategy: Define market, services, and value
- Service Design: Design new or changed services
- Service Transition: Build, test, and deploy services
- Service Operation: Manage services in live environment
- Continual Improvement: Align services with changing needs
Networking Fundamentals (OSI Model)
Definition: The OSI (Open Systems Interconnection) model is a conceptual framework with 7 layers that standardizes network communication.
- Layer 7 โ Application: HTTP, FTP, SMTP, DNS (user-facing protocols)
- Layer 6 โ Presentation: Data formatting, encryption (SSL/TLS)
- Layer 5 โ Session: Session management, authentication
- Layer 4 โ Transport: TCP (reliable), UDP (fast, unreliable)
- Layer 3 โ Network: IP addressing, routing (routers operate here)
- Layer 2 โ Data Link: MAC addresses, switches, Ethernet
- Layer 1 โ Physical: Cables, signals, hubs, electrical
Virtualization & Containerization
Virtualization: Creating virtual versions of physical resources (servers, storage, networks).
- Type 1 Hypervisor: Runs directly on hardware (VMware ESXi, Hyper-V, KVM)
- Type 2 Hypervisor: Runs on host OS (VirtualBox, VMware Workstation)
Containerization: Lightweight alternative that shares the host OS kernel.
- Docker: Platform for developing, shipping, and running containers
- Kubernetes: Container orchestration at scale
- Benefits: Portability, density, fast startup, resource efficiency
Identity & Access Management (IAM)
Definition: Framework of policies and technologies ensuring the right individuals access the right resources at the right time.
- Authentication: Verify identity (passwords, MFA, biometrics)
- Authorization: Determine permissions (RBAC, ABAC)
- SSO (Single Sign-On): One login for multiple systems (SAML, OAuth 2.0)
- MFA (Multi-Factor Authentication): 2+ verification factors required
- Privileged Access Management (PAM): Control admin/superuser accounts
Disaster Recovery & Business Continuity
Definition: Strategies to maintain or quickly resume critical business functions after a disaster.
- RPO (Recovery Point Objective): Maximum acceptable data loss (e.g., 24 hours of data)
- RTO (Recovery Time Objective): Maximum acceptable downtime (e.g., 4 hours)
- Backup Strategies: Full, incremental, differential backups
- DR Sites: Cold site (bare), warm site (partial), hot site (fully operational)
- Replication: Synchronous (zero data loss) vs. asynchronous (near-zero)
Cloud Computing Service Models
- IaaS (Infrastructure as a Service): Virtualized computing resources (AWS EC2, Azure VMs) โ You manage OS and above
- PaaS (Platform as a Service): Development platform (Heroku, Google App Engine) โ You manage apps and data
- SaaS (Software as a Service): Ready-to-use software (Gmail, Office 365, Salesforce) โ Vendor manages everything
- FaaS (Function as a Service): Serverless functions (AWS Lambda, Azure Functions) โ You only write function code
Deployment Models: Public cloud, private cloud, hybrid cloud, multi-cloud
IT Governance & Compliance
Definition: The leadership, organizational structures, and processes that ensure IT sustains and extends the organization's strategy.
- COBIT: Framework for IT governance and management
- ISO 27001: Information security management standard
- GDPR: EU data protection regulation
- HIPAA: Healthcare data protection (US)
- PCI DSS: Payment card industry data security standard
- SOC 2: Service organization controls for security, availability, and confidentiality
DevOps Culture & Practices
Definition: A cultural and technical movement that emphasizes collaboration between development and operations teams to deliver software rapidly and reliably.
- CI/CD: Continuous Integration / Continuous Delivery pipeline
- Infrastructure as Code (IaC): Manage infrastructure via code (Terraform, Ansible)
- Monitoring & Observability: Logging, metrics, tracing (ELK, Prometheus, Grafana)
- Version Control: Git as the single source of truth
- SRE (Site Reliability Engineering): Apply software engineering to operations
Worked Examples
Example 1: Calculating Network Bandwidth Requirements
Problem: A company has 200 employees, each needing 5 Mbps for video calls. The internet connection has 1 Gbps bandwidth. Is it sufficient?
Solution:
- Total bandwidth needed = 200 ร 5 Mbps = 1000 Mbps = 1 Gbps
- Available bandwidth = 1 Gbps
- Utilization = 1000 / 1000 = 100% (no headroom!)
- Recommendation: Upgrade to 2 Gbps or implement QoS (Quality of Service) to prioritize video traffic
- Rule of thumb: Maintain 30% headroom for burst traffic
Example 2: Subnetting Calculation
Problem: Given 192.168.10.0/24, create 4 subnets with equal hosts. Find the subnet mask and ranges.
Solution:
- Need 4 subnets โ borrow 2 bits (2ยฒ = 4) โ /26 mask
- Subnet mask: 255.255.255.192
- Hosts per subnet: 2โถ - 2 = 62 hosts
- Subnet 1: 192.168.10.0 โ 192.168.10.63 (broadcast)
- Subnet 2: 192.168.10.64 โ 192.168.10.127
- Subnet 3: 192.168.10.128 โ 192.168.10.191
- Subnet 4: 192.168.10.192 โ 192.168.10.255
Example 3: Backup Strategy Design
Problem: Design a backup strategy for a 2 TB database with RPO of 4 hours and RTO of 2 hours.
Solution:
- Full backup: Weekly (Sunday 2 AM) โ 2 TB ร 1 = 2 TB/week
- Incremental backup:
- Replication: Synchronous to hot DR site for zero data loss
- Storage needed: 2 TB (full) + 30 days ร 100 GB ร 6 = 18 TB incremental + 2 TB full = ~20 TB
- Recovery plan: Restore last full + replay incrementals โ meets 4-hour RPO
Example 4: Server Capacity Planning
Problem: A web app handles 10,000 requests/minute. Each server handles 500 req/min. How many servers needed with N+1 redundancy?
Solution:
- Base requirement: 10,000 / 500 = 20 servers
- N+1 redundancy: 20 + 1 = 21 servers
- Headroom at 70% utilization: 21 ร 0.7 = 14.7 effective โ 14.7 ร 500 = 7,350 req/min
- With auto-scaling: Scale out at 70% CPU, scale in at 30%
- Final Answer: 21 servers minimum, with auto-scaling group 15-30 servers
Example 5: Disk RAID Configuration
Problem: A file server needs 8 TB usable storage with fault tolerance for 1 disk failure. Compare RAID 5 and RAID 10.
Solution:
- RAID 5: (N-1) ร disk_size โฅ 8 TB โ 5 ร 2 TB = 10 TB raw, 8 TB usable
- RAID 5: 5 disks, can survive 1 disk failure, read fast, write slower (parity calc)
- RAID 10: Mirroring + Striping โ N ร disk_size / 2 โฅ 8 TB โ 8 ร 2 TB = 16 TB raw
- RAID 10: 8 disks, can survive multiple failures (if not same mirror pair), fast read+write
- Recommendation: RAID 10 for performance-critical, RAID 5 for capacity-focused
Practice Problems
Problem 1: IP Address Classification
Classify: 172.16.0.1, 10.0.0.1, 192.168.1.1, 8.8.8.8
Answer:
- 172.16.0.1 โ Class B, Private (172.16.0.0 โ 172.31.255.255)
- 10.0.0.1 โ Class A, Private (10.0.0.0 โ 10.255.255.255)
- 192.168.1.1 โ Class C, Private (192.168.0.0 โ 192.168.255.255)
- 8.8.8.8 โ Class A, Public (Google DNS)
Problem 2: Write a Shell Script to Monitor Disk Space
Create a script that alerts when disk usage exceeds 90%.
#!/bin/bash
THRESHOLD=90
PARTITION="/"
USAGE=$(df -h "$PARTITION" | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
echo "WARNING: $PARTITION is ${USAGE}% full!" | mail -s "Disk Alert" admin@eduverse.com
fi
Problem 3: Calculate Storage IOPS Requirements
A database needs 5,000 IOPS. Each 15K RPM SAS drive provides 180 IOPS. How many drives in RAID 10?
Answer: RAID 10 has 50% write penalty โ effective IOPS = 180 ร 0.5 = 90 IOPS/drive. 5000/90 = 56 drives. With 20% headroom โ 67 drives.
Problem 4: Design a Network for 3 Departments
Create VLANs for Engineering (50 users), Sales (30 users), and HR (20 users) with inter-VLAN routing.
! Cisco Switch Configuration
vlan 10
name Engineering
vlan 20
name Sales
vlan 30
name HR
! Assign ports to VLANs
interface range fa0/1-24
switchport mode access
switchport access vlan 10
interface range fa0/25-48
switchport mode access
switchport access vlan 20
! Router-on-a-stick for inter-VLAN routing
interface gi0/1.10
encapsulation dot1Q 10
ip address 10.0.10.1 255.255.255.0
interface gi0/1.20
encapsulation dot1Q 20
ip address 10.0.20.1 255.255.255.0
interface gi0/1.30
encapsulation dot1Q 30
ip address 10.0.30.1 255.255.255.0
Problem 5: Backup Rotation Schedule
Design a Grandfather-Father-Son (GFS) backup rotation for 1 month.
Answer:
- Son (daily): Incremental backups, kept for 7 days
- Father (weekly): Full backup every Sunday, kept for 4 weeks
- Grandfather (monthly): Full backup on 1st of month, kept for 12 months
- Total storage = 7 ร incremental + 4 ร full + 1 ร full
Problem 6: Implement Load Balancing
Configure Nginx as a reverse proxy / load balancer for 3 backend servers.
# /etc/nginx/conf.d/loadbalancer.conf
upstream backend {
least_conn;
server 10.0.1.10:8080 weight=3;
server 10.0.1.11:8080 weight=2;
server 10.0.1.12:8080 weight=1;
keepalive 32;
}
server {
listen 80;
server_name app.eduverse.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Problem 7: Troubleshoot Network Connectivity
A user cannot reach www.google.com (8.8.8.8). List the diagnostic steps.
Answer:
- Step 1:
ping 127.0.0.1 โ Check TCP/IP stack
- Step 2:
ping [default_gateway] โ Check local network
- Step 3:
ping 8.8.8.8 โ Check internet connectivity
- Step 4:
nslookup google.com โ Check DNS resolution
- Step 5:
tracert 8.8.8.8 โ Trace route to find where it fails
- Step 6: Check firewall rules and proxy settings
Problem 8: Calculate Cloud Costs
Estimate monthly cost for: 4 VMs (4 vCPU, 16 GB), 1 TB storage, 5 TB outbound data transfer (AWS).
Answer:
- EC2: 4 ร $140/mo (m5.xlarge) = $560
- EBS: 1 TB ร $0.10/GB = $100
- Data transfer: 5 TB ร $0.09/GB = $450
- Total: ~$1,110/month (before Reserved Instance discounts of 30-60%)