user36814
user36814

Reputation: 141

How to using awk & cut

I don't have experience with awk & cut, please help me with my question I have command to count total connection to to my server port 80 from per ip address

netstat -na|grep ":80" |awk '{print $5}'|cut -d : -f1|sort | uniq -c | sort -nr
      4 173.252.80.117
      4 173.252.80.116
      4 173.252.80.113
      2 173.252.80.119
      2 173.252.80.118
      2 173.252.80.115
      1 66.249.64.170
      1 173.252.80.114
      1 173.252.80.112

I have command to list connection status between my server port 80 with per ip address

netstat -nat | grep ":80" | grep -v LISTEN | awk '{print $5 "\t" $6}' | sort | uniq -c
      1 192.168.14.91:54008     TIME_WAIT
      1 192.168.14.91:54009     TIME_WAIT
      1 192.168.14.91:54010     TIME_WAIT
      1 192.168.14.91:54011     TIME_WAIT
      1 192.168.14.91:54012     TIME_WAIT
      1 192.168.14.91:54013     TIME_WAIT
      1 192.168.15.82:54071     ESTABLISHED
      1 192.168.15.82:54072     ESTABLISHED
      1 192.168.15.82:54073     ESTABLISHED
      1 192.168.15.82:54074     ESTABLISHED
      1 192.168.15.82:54075     ESTABLISHED
      1 192.168.15.82:54076     ESTABLISHED

How do I change my command to make output like :

3 192.168.14.91 ESTABLISHED 2 192.168.14.91 FIN_WAIT2 6 192.168.14.91 TIME_WAIT 6 192.168.15.82 ESTABLISHED 2 192.168.15.82 SYN_RECEIVED 6 192.168.15.82 TIME_WAIT

Upvotes: 1

Views: 670

Answers (2)

Ed Morton
Ed Morton

Reputation: 203274

Change

netstat -na |
grep ":80" |awk '{print $5}'|cut -d : -f1|sort | uniq -c

to

netstat -na |
awk -v OFS='\t' '/:80/{split($5,a,/:/); cnt[a[1]]++} END{for (ip in cnt) print cnt[ip], ip}'

and

netstat -nat |
grep ":80" | grep -v LISTEN | awk '{print $5 "\t" $6}' | sort | uniq -c

to

netstat -nat |
awk -v OFS='\t' '/:80/ && !/LISTEN/{split($5,a,/:/); cnt[a[1] OFS $6]++} END{for (ip in cnt) print cnt[ip], ip}'

and | sort -nr to the ends as you like.

Upvotes: 0

BMW
BMW

Reputation: 45233

by awk

netstat -nat |awk '!/LISTEN/&&/:80/{split($5,a,":");b[a[1] FS $6]++}END{for (i in b) print b[i],i}'

Upvotes: 2

Related Questions