我需要按日期/时间戳(每小时)监视 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
答案2
top -n 1 -b | grep -Ev "Tasks:|Swap:|Cpu|Mem:" > top_file
grep "PID" top_file > top_test
sed -i '/PID/d;/top/d;/^$/d' top_file
awk '{print strftime("%m-%d-%Y-%H:%M:%S", systime())" " $0}' top_file > top_final
sed -i "s/./timestamp /1" top_test
cat top_final >> top_test
sed -i 's/( )*/\1/g;s/ /,/g' top_test