#Lab 02: Server Health Monitor
Build a server health monitoring script.
#🎯 Objectives
- Monitor multiple servers
- Check services and ports
- Generate alerts
#Implementation
Create health-monitor.sh:
bash
1#!/bin/bash
2set -euo pipefail
3
4# Configuration
5SERVERS_FILE="servers.txt"
6ALERT_EMAIL="admin@example.com"
7
8check_port() {
9 local host=$1 port=$2
10 nc -zw3 "$host" "$port" 2>/dev/null
11}
12
13check_http() {
14 local url=$1
15 curl -sf --max-time 5 "$url" > /dev/null
16}
17
18send_alert() {
19 local message=$1
20 echo "[ALERT] $message"
21 # echo "$message" | mail -s "Server Alert" "$ALERT_EMAIL"
22}
23
24monitor() {
25 echo "=== Health Check: $(date) ==="
26
27 while IFS=, read -r name host port; do
28 if check_port "$host" "$port"; then
29 echo "✅ $name ($host:$port)"
30 else
31 echo "❌ $name ($host:$port)"
32 send_alert "$name is down!"
33 fi
34 done < "$SERVERS_FILE"
35}
36
37# Create sample servers file
38cat > servers.txt << EOF
39Google,google.com,443
40GitHub,github.com,443
41Local,localhost,8080
42EOF
43
44monitor#✅ Success Criteria
- Monitors multiple servers
- Shows clear status
- Handles failures gracefully