top command in shell script

2019-06-07 09:30发布

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条回答
爷、活的狠高调
2楼-- · 2019-06-07 09:37

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.

查看更多
登录 后发表回答