Alexey
Alexey

Reputation: 221

find all users who has over N process and echo them in shell

I'm writing script is ksh. Need to find all users who has over N process and echo them in shell. N reads from ksh.

I know what I should use ps -elf but how parse it, find users with >N process and create array with them. Little troubles with array in ksh. Please help. Maybe simple solutions can help me instead of array creating.

s162103@helios:/home/s162103$ ps -elf 
     0 S  s153308  4804     1   0  40 20        ?  17666        ? 11:03:08 ?           0:00 /usr/lib/gnome-settings-daemon --oa
     0 S     root  6546  1327   0  40 20        ?   3584        ? 11:14:06 ?           0:00 /usr/dt/bin/dtlogin -daemon -udpPor
     0 S webservd 15646   485   0  40 20        ?   2823        ?     п╪п╟я─я ?           0:23 /opt/csw/sbin/nginx
     0 S  s153246  6746  6741   0  40 20        ?  18103        ? 11:14:21 ?           0:00 iiim-panel --disable-crash-dialog
     0 S  s153246 23512     1   0  40 20        ?  17903        ? 09:34:08 ?           0:00 /usr/bin/metacity --sm-client-id=de
     0 S     root   933   861   0  40 20        ?   5234        ? 10:26:59 ?           0:00 dtgreet -display :14
     ...

when i type

ps -elf | awk '{a[$3]++;}END{for(i in a)if (a[i]>N)print i, a[i];}' N=1

s162103@helios:/home/s162103$ ps -elf | awk '{a[$3]++;}END{for(i in a)if (a[i]>N)print i, a[i];}' N=1
root 118
/usr/sadm/lib/smc/bin/smcboot 3
/usr/lib/autofs/automountd 2
/opt/SUNWut/lib/utsessiond 2
nasty 31
dima 22
/opt/oracle/product/Oracle_WT1/ohs/ 7
/usr/lib/ssh/sshd 5
/usr/bin/bash 11

that is not user /usr/sadm/lib/smc/bin/smcboot there is last field in ps -elf ,not user

Upvotes: 0

Views: 170

Answers (3)

Henk Langeveld
Henk Langeveld

Reputation: 8446

The minimal ps command you want to use here is ps -eo user=. This will just print the username for each process and nothing more. The rest can be done with awk:

ps -eo user= |
  awk  -v max=3 '{ n[$1]++ }
    END {
      for (user in n)
        if (n[user]>max)
          print n[user], user
  }'

I recommend to put the count in the first column for readability.

Upvotes: 0

Guru
Guru

Reputation: 16994

Something like this(assuming 3rd field of your ps command gives the user id):

 ps -elf | 
   awk '{a[$3]++;}
   END {
     for(i in a)
       if (a[i]>N)
         print i, a[i];
   }' N=3

Upvotes: 1

Alexey
Alexey

Reputation: 221

read number    
ps -elfo user= | sort | uniq -c | while read count user
do 
    if (( $count > $number )) 
    then 
      echo $user  
    fi  
done

That is best solution and it works!

Upvotes: 0

Related Questions