Script that only counts Established, TIME_WAIT, and Closed Wait connections using Netstat
Your script can be slightly modified to only process the states you need:
netstat -ant | awk '/ESTABLISHED|LISTEN|CLOSE_WAIT/ {print $6}' | \
sort | uniq -c | sort -n
A further step would be to everything with awk
, e.g. :
netstat -ant | awk '
/ESTABLISHED|LISTEN|CLOSE_WAIT/ {count[$6]++}
END {
for(s in count) {
printf("%12s : %6d\n", s, count[s]);
}
}'
Related videos on Youtube
monkeychef
Updated on September 18, 2022Comments
-
monkeychef over 1 year
I'm trying to make a script (using Perl, but it isn't necessary) that will only count the number of Established, Time_Wait, and Closed_Wait connections on a system and print them in terminal. So far I've figured out that I can use :
netstat -ant | awk '{print $6}' | sort | uniq -c | sort -n
in order to print all of the connections, but when I run this from a script it will not print in terminal and it also gives me some connections that I am not looking for such as Listen and Foreign. The reason why it must only show Established, Time_Wait, and Closed_Wait is because the script is being used by a monitoring program that will fail if any other connection types show up. Can anyone make a suggestion? Thanks!
-
monkeychef over 8 yearsmy %count; open my $NET, '-|', qw{ /bin/netstat -ant } or die $!; <$NET> ; <$NET> ;#Removes "Foreign" while (<$NET>) { my ($protocol, $recv, $send, $local_addr, $foreign_addr, $state) = split; # Do whatever you need with the information, e.g. $count{$state}++; } for my $state (keys %count) { print "$state\t$count{$state}\n"; }
-
Andy Dalton over 8 yearsnetstat -nat | egrep 'ESTABLISHED|TIME_WAIT|CLOSE_WAIT' | wc -l
-
-
monkeychef over 8 yearsThis was fantastic, thank you! Is there any way you could also help develop the rest of the script so that when the program is run it only outputs those three lines?
-
jlliagre over 8 yearsIt's hard to tell without more information about what the rest of the script should be.
-
monkeychef over 8 yearsI really just need the script to ignore anything else that could pop up such as FIN_WAIT2, I'm only looking for established, time wait, and close wait.