리눅스 서버의 모든 상태를 점검하는 스크립트

리눅스 서버 상태를 한 번에 수집하는 점검 스크립트입니다. CPU, 메모리, 디스크, inode, 네트워크, systemd 실패, 커널 오류 로그를 섹션별로 정리했습니다.

리눅스 서버 전체 상태 점검 스크립트는 “명령어를 많이 실행하는 스크립트”가 아니라, 장애 판단에 필요한 정보를 짧은 시간 안에 빠짐없이 모으는 도구여야 합니다. CPU, 메모리, 디스크, inode, 네트워크, 서비스, 로그를 섹션별로 나누고, 명령이 실패해도 다음 항목을 계속 수집하도록 만드는 것이 좋습니다.

점검 스크립트 예시

아래 스크립트는 서버에 큰 부하를 주지 않는 범위에서 현재 상태를 수집합니다. 결과는 표준 출력으로 나오므로 파일로 저장하거나 메일/Slack 알림 도구와 연결할 수 있습니다.

#!/usr/bin/env bash
set -uo pipefail

HOST="$(hostname -f 2>/dev/null || hostname)"
NOW="$(date '+%Y-%m-%d %H:%M:%S %z')"

section() {
  printf '\n==== %s ====\n' "$1"
}

run() {
  local title="$1"
  shift
  printf '\n-- %s --\n' "$title"
  "$@" 2>&1 || printf '[WARN] command failed: %s\n' "$*"
}

section "basic"
echo "host=${HOST}"
echo "time=${NOW}"
run "uptime" uptime
run "kernel" uname -a
run "os-release" sh -c 'cat /etc/os-release | egrep "^(NAME|VERSION)="'

section "cpu-memory"
run "load average" sh -c "cat /proc/loadavg"
run "memory" free -h
run "top cpu processes" sh -c "ps -eo pid,ppid,stat,pcpu,pmem,comm --sort=-pcpu | head -n 11"
run "top memory processes" sh -c "ps -eo pid,ppid,stat,pcpu,pmem,comm --sort=-pmem | head -n 11"

section "disk"
run "filesystem usage" df -hT
run "inode usage" df -ih
run "block devices" lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS
run "read-only mounts" sh -c "mount | grep ' ro[),]' || true"

section "network"
run "addresses" ip -br addr
run "routes" ip route
run "listening ports" sh -c "ss -lntup | head -n 80"
run "dns" sh -c "getent hosts devmes.com || true"

section "services"
run "failed systemd units" sh -c "systemctl --failed --no-pager || true"
run "recent critical logs" sh -c "journalctl -p warning..alert -n 80 --no-pager || true"

section "kernel-storage-network-errors"
run "kernel error hints" sh -c "dmesg -T | egrep -i 'error|fail|reset|blocked for more than|I/O error|oom|segfault' | tail -n 80 || true"

저장하고 실행하기

sudo install -m 755 server-healthcheck.sh /usr/local/sbin/server-healthcheck.sh
/usr/local/sbin/server-healthcheck.sh

결과를 파일로 남기려면 날짜가 들어간 파일명으로 저장합니다.

sudo mkdir -p /var/log/server-healthcheck
/usr/local/sbin/server-healthcheck.sh \
  > "/var/log/server-healthcheck/health-$(date +%Y%m%d_%H%M%S).log" 2>&1

cron 등록

정기 수집은 너무 자주 돌릴 필요가 없습니다. 일반 서버라면 10분 또는 30분 단위로 충분합니다.

sudo crontab -e
*/10 * * * * /usr/local/sbin/server-healthcheck.sh > /var/log/server-healthcheck/latest.log 2>&1

장애 판단에 바로 쓰는 기준

스크립트 결과는 다음 기준으로 빠르게 읽습니다.

  • load average: CPU core 수보다 지속적으로 높으면 CPU 또는 I/O 대기를 의심합니다.
  • free: available 메모리가 낮고 swap 사용이 늘면 메모리 압박을 봅니다.
  • df -hT: 90% 이상 파일시스템은 증설/정리 후보입니다.
  • df -ih: inode 100%는 용량 여유와 별개로 장애를 만듭니다.
  • systemctl --failed: failed unit이 있으면 서비스별 로그를 바로 봅니다.
  • dmesg: I/O error, reset, blocked task, OOM 메시지는 우선순위가 높습니다.

주의할 점

ps aux 전체, 거대한 로그 전체, 무제한 du / 같은 명령은 점검 스크립트 안에서 서버에 부담을 줄 수 있습니다. 자동 점검 스크립트는 “짧고 반복 가능한 스냅샷”을 남기고, 상세 분석은 별도 명령으로 이어가는 구조가 안전합니다.

BGM EVER