#!/usr/bin/env bash # k8s-status.sh — 通过 kubectl 读取 K3s 集群状态,解析输出核心字段 # 用法: # bash k8s-status.sh # 默认 kubectl + 当前 kubeconfig # KUBECONFIG=/etc/rancher/k3s/k3s.yaml bash k8s-status.sh # 环境变量: KUBECTL(kubectl 路径,默认 kubectl)、KUBECONFIG set -euo pipefail KUBECTL_CMD=(kubectl) if [[ -n "${KUBECTL:-}" ]]; then KUBECTL_CMD=("$KUBECTL") fi if [[ -n "${KUBECONFIG:-}" ]]; then KUBECTL_CMD+=(--kubeconfig "$KUBECONFIG") fi echo "===================== K3s 集群状态巡检 =====================" echo "时间: $(date '+%Y-%m-%d %H:%M:%S %Z')" echo echo "────── ① 节点状态(全量 -o wide)──────" "${KUBECTL_CMD[@]}" get nodes -o wide echo echo "────── ② 节点健康解析(核心字段,jsonpath 精确提取)──────" "${KUBECTL_CMD[@]}" get nodes -o jsonpath=' {range .items[*]} { .metadata.name}{"\t"}{ .status.conditions[?(@.type=="Ready")].status}{"\t"}{ .metadata.labels.node-role\.kubernetes\.io/control-plane}{"\t"}{ .status.nodeInfo.kubeletVersion}{"\t"}{ .status.addresses[?(@.type=="InternalIP")].address}{"\t"}{ .status.addresses[?(@.type=="ExternalIP")].address}{"\t"}{ .status.nodeInfo.osImage}{"\t"}{ .status.nodeInfo.kernelVersion}{"\t"}{ .status.nodeInfo.containerRuntimeVersion}{"\n"} {end}' | awk -F'\t' 'NF { role = ($3 == "true") ? "control-plane" : "worker" printf " %-26s %-7s %-14s %-14s 内网IP=%-16s 公网IP=%-16s %s | %s | %s\n", $1, $2, role, $4, $5, $6, $7, $8, $9 }' echo echo "────── ③ 节点资源占用(CPU/内存)──────" if "${KUBECTL_CMD[@]}" top nodes 2>/dev/null; then : else echo " (metrics-server 暂不可用,跳过)" fi echo echo "────── ④ Pod 总数 & 按节点分布 ──────" TOTAL=$("${KUBECTL_CMD[@]}" get pods -A --no-headers 2>/dev/null | wc -l | tr -d ' ') echo " 集群 Pod 总数: ${TOTAL:-0}" "${KUBECTL_CMD[@]}" get pods -A -o wide --no-headers 2>/dev/null | awk '{print $8}' | sort | uniq -c | awk '{printf " %s: %s 个 pod\n", $2, $1}' echo echo "────── ⑤ 异常 Pod(非 Running/Completed)──────" "${KUBECTL_CMD[@]}" get pods -A --no-headers 2>/dev/null | awk '$4 != "Running" && $4 != "Completed" { printf " [%s] %s/%s: %s (%s)\n", $1, $2, $3, $4, $5 }' echo " (无输出即全部健康)" echo echo "────── ⑥ 最近 Warning 事件(最多 5 条)──────" "${KUBECTL_CMD[@]}" get events -A --field-selector type=Warning --sort-by=.lastTimestamp 2>/dev/null | awk 'NR==1 {next} {print " " $0}' | tail -5 || true echo echo "===================== 巡检完成 ====================="