小工具知识网

当前位置: 首页 > 行业知识 > 【bash】统计服务器信息脚本

行业知识

【bash】统计服务器信息脚本

2026-10-27 11:01:17 来源:互联网转载

起因

写一个bash脚本统计服务器的机器名、内网IP、CPU使用率、内存使用率、List{GPU使用率、显存}

()

脚本

#!/bin/bash# 主机名hostname=$(hostname)# 内网ipip=$(ip addr | grep 'inet ' | grep -v 127.0.0.1 | awk '{print }' | cut -d/ -f1)ip=$(echo "$ip"|tr '\n' ',')ip="${ip%,}"# cpu使用率cpu_used=$(top -bn1 | grep Cpu | awk '{print +}')mem_total=$(free -m | grep -e Mem -e '内存' | awk '{print }')mem_used=$(free -m | grep -e Mem -e '内存' | awk '{print }')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 -- --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*$//')    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"fiecho "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"

输出示例

command nvidia-smi existHostname: xxxIP: 192.168.xxx.xxxCPU 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}]
()

上一篇:皮皮果理财深度解析,体验与收益大揭秘!

下一篇:化学专业