#!/bin/bash # # Service Management Utility # # WARNING: This script is provided for educational purposes ONLY. # Unauthorized use to interrupt services is illegal and unethical. # # PURPOSE: Demonstrates techniques for monitoring and controlling services # with proper authentication and logging for legitimate administration. # Configuration LOG_FILE="/var/log/maintenance.log" AUTH_USERS_FILE="authorized_users.txt" # Check if running as root if [ "$EUID" -ne 0 ]; then echo "This script requires root privileges" exit 1 fi # Functions log_action() { echo "$(date '+%Y-%m-%d %H:%M:%S') - $USER - $1" | tee -a "$LOG_FILE" } is_authorized() { if [ ! -f "$AUTH_USERS_FILE" ]; then echo "Error: Authorization file not found" return 1 fi grep -q "^$USER$" "$AUTH_USERS_FILE" return $? } show_usage() { echo "Usage: $0 [options] " echo "Options:" echo " -h, --help Show this help message" echo " -l, --list List running services" echo " -f, --firewall Manage firewall rules" echo "" echo "Actions:" echo " start Start a service" echo " stop Stop a service" echo " restart Restart a service" echo " status Show service status" echo "" echo "Examples:" echo " $0 stop nginx" echo " $0 --firewall block 80" } list_services() { log_action "Listed running services" systemctl list-units --type=service --state=running } manage_service() { local action=$1 local service=$2 if ! systemctl list-unit-files --type=service | grep -q "$service"; then echo "Error: Service $service not found" return 1 fi log_action "Executing: systemctl $action $service" systemctl "$action" "$service" echo "Service $service $action operation completed" log_action "Completed $action on $service" } manage_firewall() { local action=$1 local port=$2 if [ "$action" == "block" ]; then log_action "Blocking port $port" ufw deny "$port" elif [ "$action" == "allow" ]; then log_action "Allowing port $port" ufw allow "$port" else echo "Error: Unknown firewall action" return 1 fi echo "Firewall rule applied for port $port" } # Main script if ! is_authorized; then echo "Error: User $USER not authorized to run this script" log_action "UNAUTHORIZED ACCESS ATTEMPT" exit 1 fi if [ $# -lt 1 ]; then show_usage exit 1 fi case "$1" in -h|--help) show_usage ;; -l|--list) list_services ;; -f|--firewall) if [ $# -lt 3 ]; then echo "Error: Missing arguments for firewall management" show_usage exit 1 fi manage_firewall "$2" "$3" ;; start|stop|restart|status) if [ $# -lt 2 ]; then echo "Error: Missing service name" show_usage exit 1 fi manage_service "$1" "$2" ;; *) echo "Error: Unknown action $1" show_usage exit 1 ;; esac exit 0