0


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

起因

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

脚本

#!/bin/bash# 主机名hostname=$(hostname)# 内网ipip=$(ip addr |grep'inet '|grep-v127.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;thenecho"command nvidia-smi not exist"elsegpu_info=""echo"command nvidia-smi exist"total_devices=$(($(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)-1))foriin`seq0 $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','-f1)USED_MEMORY=$(echo"$MEMORY_INFO"|cut-d','-f2)# 计算内存使用率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}=="."]];thenMEMORY_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 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}]
标签: bash 服务器 chrome

本文转载自: https://blog.csdn.net/u011308433/article/details/139116444
版权归原作者 xst3300 所有, 如有侵权,请联系我们删除。

“【bash】统计服务器信息脚本”的评论:

还没有评论