#!/usr/bin/env bash # # Run a simple server health check. # # The script reports CPU load, memory usage, disk usage, network interfaces, # listening ports, and the top processes by CPU and memory. # # Usage: # bash server_health_check.sh # bash server_health_check.sh --output /tmp/server-health.txt # # Options: # --output FILE Save the report to a file. # --help Show this help message. set -Eeuo pipefail output_file="" usage() { sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//' } section() { printf '\n===== %s =====\n' "$1" } run_report() { section "SERVER" printf 'Hostname: %s\n' "$(hostname)" printf 'Date: %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" printf 'Uptime: %s\n' "$(uptime -p 2>/dev/null || uptime)" section "CPU" printf 'Load average: %s\n' "$(awk '{print $1, $2, $3}' /proc/loadavg)" if command -v top >/dev/null 2>&1; then top -bn1 | head -n 5 fi section "MEMORY" free -h section "DISK" df -hT | grep -vE 'tmpfs|devtmpfs' section "NETWORK INTERFACES" if command -v ip >/dev/null 2>&1; then ip -brief address else ifconfig 2>/dev/null || true fi section "LISTENING PORTS" if command -v ss >/dev/null 2>&1; then ss -tulpen 2>/dev/null || ss -tulpen elif command -v netstat >/dev/null 2>&1; then netstat -tulpen 2>/dev/null || netstat -tulpn else printf 'Neither ss nor netstat is available.\n' fi section "TOP PROCESSES BY CPU" ps -eo pid,user,comm,%cpu,%mem --sort=-%cpu | head -n 11 section "TOP PROCESSES BY MEMORY" ps -eo pid,user,comm,%cpu,%mem --sort=-%mem | head -n 11 } while [[ "$#" -gt 0 ]]; do case "$1" in --output) output_file="${2:-}" shift 2 ;; --help|-h) usage exit 0 ;; *) printf 'ERROR: unknown option: %s\n' "$1" >&2 usage >&2 exit 1 ;; esac done if [[ -n "$output_file" ]]; then run_report > "$output_file" printf 'Health check saved to %s\n' "$output_file" else run_report fi