KnowHow

技術的なメモを中心にまとめます。
検索にて調べることができます。

Linuxのメモリやロードアベレージを1コマンドで取得したい。(コマンドレベル)

登録日 :2024/10/16 04:40
カテゴリ :Linux

sinfoコマンドを用いず、シェルで一つずつステータスを取得するスクリプト

ベースとなるコマンド

echo "$(hostname) | Load Average: $(uptime | awk '{print $10 $11 $12}') | Total Memory: $(free -m | awk '/Mem:/ {print $2}')MB | Used Memory: $(free -m | awk '/Mem:/ {print $3}')MB | Buff Memory: $(free -m | awk '/Mem:/ {print $6}')MB"

上記のコマンドをベースにシェルとして、複数のノードにsshでデータを表示する。

chech.sh

hostname=$(hostname)
load=$(uptime | awk '{print $10}')
total=$(free -h | awk '/Mem:/ {print $2}')
used=$(free -h | awk '/Mem:/ {print $3}')
free=$(free -h | awk '/Mem:/ {print $4}')
buff=$(free -h | awk '/Mem:/ {print $6}')
avail=$(free -h | awk '/Mem:/ {print $7}')

echo "$hostname | Load Average: $load | Total Memory: $total | Used Memory $used | Buff Memory $buff | Free Memory $free"

checkall.sh

nodes=("headnode" "compute01")
com="/home/app/bash/check.sh"

for node in "${nodes[@]}"
do
        ssh $node $com
done

実行結果

[root@headnode bash]# ./checkall.sh
headnode | Load Average: 0.03, | Total Memory: 770Mi | Used Memory 422Mi | Buff Memory 262Mi | Free Memory 86Mi
compute01 | Load Average: 0.00, | Total Memory: 770Mi | Used Memory 435Mi | Buff Memory 205Mi | Free Memory 129Mi
[root@headnode bash]#

値のチェック

[root@headnode bash]# free -h
              total        used        free      shared  buff/cache   available
Mem:          770Mi       415Mi        92Mi        39Mi       262Mi       192Mi
Swap:         1.6Gi       631Mi       1.0Gi
[root@headnode bash]#

補足

ステータスだけコンマ区切りで取得する場合
fetch_status.sh

load=$(uptime | awk '{print $10}')
total=$(free -m | awk '/Mem:/ {print $2}')
used=$(free -m | awk '/Mem:/ {print $3}')
free=$(free -m | awk '/Mem:/ {print $4}')
buff=$(free -m | awk '/Mem:/ {print $6}')
avail=$(free -m | awk '/Mem:/ {print $7}')

echo $load''$total','$used','$free','$buff','$avail

実行結果

[root@headnode bash]# ./fetch_status.sh
0.00,770,417,90,261,189
[root@headnode bash]#