#!/bin/bash

# Fetch all pods on the specified node along with their CPU usage
pods=$(kubectl get pods --all-namespaces -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.namespace}{"\t"}{.spec.nodeName}{"\n"}' | grep cn-hangzhou.172.16.6.12)

total_cpu_usage=0

echo "CPU_Usage(milliCPU)   Pod_Name"

# Loop through each pod running on the specified node and fetch its CPU usage
while read -r pod_name namespace node_name; do
    cpu_usage=$(kubectl top pod $pod_name -n $namespace --no-headers | awk '{print $2}')
    cpu_usage_value=$(echo $cpu_usage | sed 's/m//') # Remove 'm' (milliCPU) unit
    total_cpu_usage=$((total_cpu_usage + cpu_usage_value))
    printf "%-20s %s\n" "$cpu_usage" "$pod_name"
done <<< "$pods" | sort -rn # Pipe output to sort by CPU usage in reverse numeric order

echo "使用的 CPU 总量: $total_cpu_usage milliCPU"

要使用,替换上面的 grep cn-hangzhou.172.16.6.12 部分就行了


universe_king
3.4k 声望677 粉丝