起因
写一个bash脚本统计服务器的机器名、内网IP、CPU使用率、内存使用率、List{GPU使用率、显存}
脚本
bash
#!/bin/bash
# 主机名
hostname=$(hostname)
# 内网ip
ip=$(ip addr | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1)
ip=$(echo "$ip"|tr '\n' ',')
ip="${ip%,}"
# cpu使用率
cpu_used=$(top -bn1 | grep Cpu | awk '{print $2+$4}')
mem_total=$(free -m | grep -e Mem -e '内存' | awk '{print $2}')
mem_used=$(free -m | grep -e Mem -e '内存' | awk '{print $3}')
mem_rate=$((mem_used*100/mem_total))
gpu_info="[]"
if ! command -v nvidia-smi >/dev/null 2>&1; then
echo "command nvidia-smi not exist"
else
gpu_info=""
echo "command nvidia-smi exist"
total_devices=$(($(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-1))
for i in `seq 0 $total_devices`; do
# 获取 GPU 内存使用情况
MEMORY_INFO=$(nvidia-smi --id="$i" --query-gpu=memory.total,memory.used --format=csv,noheader,nounits)
# 解析内存信息
TOTAL_MEMORY=$(echo "$MEMORY_INFO" | cut -d ',' -f 1)
USED_MEMORY=$(echo "$MEMORY_INFO" | cut -d ',' -f 2)
# 计算内存使用率
MEMORY_USAGE_PERCENT=$(echo "scale=5; $USED_MEMORY / $TOTAL_MEMORY * 100" | bc)
MEMORY_USAGE_PERCENT=$(echo "$MEMORY_USAGE_PERCENT" | sed 's/\(\.[0-9]*[1-9]\)0*$/\1/')
if [[ ${MEMORY_USAGE_PERCENT:0:1} == "." ]]; then
MEMORY_USAGE_PERCENT="0$MEMORY_USAGE_PERCENT"
fi
# 构造 JSON 对象
json="{\"gpu_idx\":$i,\"total_memory\":$TOTAL_MEMORY,\"used_memory\":$USED_MEMORY,\"memory_rate\":$MEMORY_USAGE_PERCENT}"
gpu_info+=",$json"
done
# 移除开头的逗号
gpu_info=$(echo "$gpu_info" | sed 's/^,//')
# 添加结束的方括号
gpu_info+="]"
gpu_info="[$gpu_info"
fi
echo "Hostname: $hostname"
echo "IP: $ip"
echo "CPU Usage: $cpu_used%"
echo "Memory Usage: $mem_used MB / $mem_total MB, $mem_rate%"
echo "GPU Info: $gpu_info"
输出示例
bash
command nvidia-smi exist
Hostname: xxx
IP: 192.168.xxx.xxx
CPU Usage: 0.9%
Memory Usage: 16125 MB / 257376 MB, 6%
GPU Info: [{"gpu_idx":0,"total_memory":24564,"used_memory": 16065,"memory_rate":65.4},{"gpu_idx":1,"total_memory":24564,"used_memory": 15900,"memory_rate":64.728},{"gpu_idx":2,"total_memory":24564,"used_memory": 680,"memory_rate":2.768},{"gpu_idx":3,"total_memory":24564,"used_memory": 680,"memory_rate":2.768}]