[shell] top/psコマンドの結果を定期的に保存

サーバの監視ツールには色々な種類があるけれども、
ちょっとこうしたいといった時には、shellスクリプト書いたほうがてっとり早かったり。
例えば、障害発生前後で、top/psがどういう状況だったのか?みたい時とか。

今回は、「cronで5分おきにshellスクリプトを実行し、Load Averageが5を超えたときに、top,ps結果を保存する
といった、Shellスクリプトを書いたのでメモしておく。

# vi /scripts/toppslog.sh
#!/bin/sh

# define
MAX_LOAD_AVG=5

# get Load Average
LOAD_AVG=`uptime | cut -d, -f4 | cut -d: -f2 | cut -d. -f1`

if [ $LOAD_AVG -gt $MAX_LOAD_AVG ]; then
  
  # make logfile
  LOG_TIME=`date '+%Y%m%d_%H%M%S'`
  LOG_FILE="/var/log/topps/tp${LOGTIME}.log"

  # top command
  echo -e "top cmd: ${LOG_TIME} \n****************" >> $LOG_FILE
  top -n 1 -b >> $LOG_FILE

  # ps command
  echo -e "ps cmd: ${LOG_TIME} \n*****************" >> $LOG_FILE
  ps alx --sort -rss >> $LOG_FILE

fi

ログ保存先ディレクトリの作成と実行権限の付与

# mkdir /var/log/topps/
# chmod 700 /scripts/toppslog.sh

cronで5分おきに実行する.

# echo */5 * * * * root /root/scripts/toppslog.sh > /etc/cron.d/toppslog

下記のように、ファイル名が”ymd_h:i:s.log”で保存されていく。

# ll /var/log/topps/
-rw-r--r-- 1 root root 19495 11月  4 15:00 tp20101104_150001.log
-rw-r--r-- 1 root root 20257 11月  4 15:05 tp20101104_150501.log
-rw-r--r-- 1 root root 20336 11月  4 15:10 tp20101104_151001.log

logrotateを行っていないので、その点は気をつける必要あり。
shellじゃなくてもperlとか慣れた言語で書いたほうが早いかも。

One Response to [shell] top/psコマンドの結果を定期的に保存

  1. Monex Scam says:

    A simple program to start a root shell if setup correctly with the suid. On RHEL-based systems appending 1 to the end of kernel command line will cause to start into runlevel 1 directly without asking for root password.

Leave a Reply to Monex Scam Cancel reply

Your email address will not be published. Required fields are marked *