1) Purpose & Scope
- Goal: Detect if a server is running with an unexpected time zone and auto-correct it, while writing an auditable log and sending an alert.
- Why it matters: Wrong time zone can corrupt log timelines, break scheduled jobs, impact SLAs, and compliance for time-stamped records.
- Applies to: Most systemd-based Linux distributions (RHEL/CentOS/Alma/Rocky 7+, Ubuntu 16.04+, Debian 9+). Non-systemd distros will require adaptation.
2) Configuration
Define your expected time zone.
Create /etc/time-sync.conf:
EXPECTED_ZONE=America/Los_Angeles
EMAIL_TO=navneet.kashyap@example.team
MODE=enforce # values: check | enforce
3) Hardened Script
Install to /usr/local/bin/check_time_sync.sh and make it executable.
#!/usr/bin/env bash
set -euo pipefail
LOGFILE=”/var/log/time_sync.log”
CONFIG=”/etc/time-sync.conf”
EXPECTED_ZONE=”America/Los_Angeles” # default; can be overridden by CONFIG
EMAIL_TO=”navneet.kashyap@example.team”
MODE=”enforce” # check | enforce
if [[ -f “$CONFIG” ]]; then
# shellcheck disable=SC1090
source “$CONFIG”
fi
if [[ $EUID -ne 0 ]]; then
echo “This script must be run as root” >&2
exit 1
fi
TIMESTAMP=$(date ‘+%F %T’)
HOST=$(hostname -f 2>/dev/null || hostname)
CURRENT_ZONE=$(timedatectl show -p Timezone –value 2>/dev/null || echo “unknown”)
log() { echo “$TIMESTAMP – $*” >> “$LOGFILE”; logger -t time_sync “$*”; }
if [[ “$CURRENT_ZONE” != “$EXPECTED_ZONE” ]]; then
log “ALERT: Timezone mismatch on $HOST. Expected: $EXPECTED_ZONE, Found: $CURRENT_ZONE”
if [[ “$MODE” == “enforce” ]]; then
if timedatectl set-timezone “$EXPECTED_ZONE” 2>>”$LOGFILE”; then
NEW_ZONE=$(timedatectl show -p Timezone –value)
log “FIXED: Timezone changed to $NEW_ZONE”
if command -v mail >/dev/null 2>&1; then
printf “[%s] Timezone auto-corrected on %s: %s -> %s\n” “$TIMESTAMP” “$HOST” “$CURRENT_ZONE” “$NEW_ZONE” \
| mail -s “Time Sync Auto-Fix Alert ($HOST)” “$EMAIL_TO”
fi
else
log “ERROR: Failed to set timezone to $EXPECTED_ZONE”
if command -v mail >/dev/null 2>&1; then
printf “[%s] Failed to set timezone to %s on %s (current: %s)\n” “$TIMESTAMP” “$EXPECTED_ZONE” “$HOST” “$CURRENT_ZONE” \
| mail -s “Time Sync Auto-Fix FAILURE ($HOST)” “$EMAIL_TO”
fi
exit 2
fi
else
# check-only mode
if command -v mail >/dev/null 2>&1; then
printf “[%s] Timezone mismatch detected on %s: expected %s, found %s (no change applied)\n” \
“$TIMESTAMP” “$HOST” “$EXPECTED_ZONE” “$CURRENT_ZONE” \
| mail -s “Time Sync ALERT ($HOST)” “$EMAIL_TO”
fi
fi
else
log “OK: Timezone is correct ($CURRENT_ZONE)”
Fi
4) Scheduling
Add to root’s crontab (sudo crontab -e):
*/5 * * * * /usr/local/bin/check_time_sync.sh



