TOPコマンド出力にタイムスタンプを追加[閉じる]

TOPコマンド出力にタイムスタンプを追加[閉じる]

日付/タイムスタンプ(時間別)/ユーザーごとにCPUとメモリ使用率を監視する必要があります。以下の「TOP」コマンドで時間ごとのCPU使用率レポートを準備できるように、日付/タイムスタンプフィールドも追加する必要があります。

誰かがこれを行う方法を教えてもらえますか?

トップに戻る >> cpu.txt

 PID USER      PR  NI  VIRT  RES  SHR S   %CPU %MEM    TIME+  COMMAND
19402 psftpapp  20   0 2695m 203m  43m S    155  0.1   0:05.65 java
20285 cmtapp    20   0 10.0g 218m  24m S    111  0.1   0:03.34 java
18818 psftpapp  20   0 2710m 243m  43m S     89  0.1   0:08.74 java
18728 oafglapp  20   0 2719m 240m  43m S     86  0.1   0:08.80 java
20387 imxglapp  20   0 2866m  74m  20m S     32  0.0   0:00.98 java
20394 imxglapp  20   0 2862m  71m  20m S     31  0.0   0:00.94 java
45688 ams       20   0  189m  13m 3276 S      2  0.0 173:15.64 python2.6
 1285 oafglapp  20   0 2772m 393m  44m S      1  0.2   0:26.89 java
15349 root      20   0 17660 1924 1036 R      1  0.0   0:00.15 top
15701 imxglapp  20   0 10.0g 578m  24m S      1  0.2   0:14.75 java
32872 a1543065  20   0 10.0g 610m  24m S      1  0.2   2:00.03 java

私は次のような結果を得ます。

 top | awk 'NR%13==0 { printf  "%d %s\n",  systime(), $0 ; fflush(stdout) }'
1486713976     1 root      20   0 10560  844  708 S      0  0.0   0:32.48 init                                                                                          
1486713976    15 root      20   0     0    0    0 S      0  0.0   0:49.35 ksoftirqd/2                                                                                   
1486713976    28 root      RT   0     0    0    0 S      0  0.0   0:11.59 watchdog/5 

以下のようにする必要があります

top | awk 'NR%13==0 { printf  "%d %s\n",  systime(), $0 ; fflush(stdout) }'
02-10-2017-16:01:58     1 root      20   0 10560  844  708 S      0  0.0   0:32.48 init                                                                                          
02-10-2017-16:01:59    15 root      20   0     0    0    0 S      0  0.0   0:49.35 ksoftirqd/2                                                                                   
02-10-2017-16:02:00    28 root      RT   0     0    0    0 S      0  0.0   0:11.59 watchdog/5 

ベストアンサー1

top -b1 -n1 | awk -vtime="$(date +%m-%d-%Y-%T)" 'NR<7{print;next}NR==7{printf("Time\t\t\t\t%s\n",$0)}NR>8{printf("%s\t%s\n",time,$0)}' > cpu.txt


top -b1 -n1 -- gives the top output and come back to terminal
-vtime="$(date +"%m-%d-%Y-%T)"  -- store the current time to variable called time
NR<7{print;next} -- read the lines from 1 to 6 and print it. 
NR==7{printf("Time\t\t\t\t%s\n",$0)}  -- if it is 7th line, then add Time as first column
NR>8{printf("%s\t%s\n",time,$0)}'  -- add the calculated time in first field

その他の回答

https://stackoverflow.com/questions/16045104/add-timestamp-to-top-command-batch-output

https://stackoverflow.com/questions/39981410/shell-script-top-command-and-date-command-at-once

おすすめ記事