top command in shell script

送分小仙女□ 提交于 2019-12-23 04:06:09

问题


I am trying to get first 5 lines of top command through expect script. Im calling this expect script from a shell script along with some other stuff.

top | head -5 gives me below output ie without cpu stats-

top - 09:10:58 up 46 days, 17:03, 12 users, load average: 0.01, 0.02, 0.00 Tasks: 138 total, 1 running, 137 sleeping, 0 stopped, 0 zombie

Mem: 16432400k total, 8408096k used, 8024304k free, 609200k buffers Swap: 6290736k total, 0k used, 6290736k free, 6754356k cached

If I run just top command on that remote server I can see there is a 2-3 second delay before the CPU states line is updated, can some one please help me to get all 5 lines with updated cpu states? Below is my expect script -

#!/usr/bin/expect -f
set user1 abc
set pass1 pass
set timeout 8
match_max 1000
spawn ssh -C -o stricthostkeychecking=no $user1@<ip>
expect "*?assword:*"
send  "$pass3\r"
expect "?xterm*"
send "\r"
send "top | head -5\r"
expect eof

回答1:


You need to run top in batch mode instead of the default interactive mode. In addition you need to define the number of iterations that top performs for getting its measurements.

num_iterations=3
top -b -n $num_iterations | head -5

If you want the output to only list the top 5 processes and skip the statistic header displayed, you can try this:

num_iterations=3
top -b -n $num_iterations | sed -n '8,12p'

Also tune the value of num_iterations as per your need.



来源:https://stackoverflow.com/questions/15184386/top-command-in-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!