I'm trying to make a script for Windows that will only count the number of Established, Time_Wait, and Closed_Wait connections on a system and print them in command prompt. I had already made a shell script that can do this on Linux boxes, but shell scripts to not work in Windows. I attempted to use a .bat in order to execute the script but that is not working (probably because it's still a shell script in Windows :/)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!
Asked
Active
Viewed 1,322 times
-2
-
What args are you using to generate the input, and please provide a sample of exactly the output should look like. – stevieb Sep 03 '15 at 17:50
-
My original input from the Linux script is: ESTABLISHED=`netstat -nat | egrep 'ESTABLISHED' | wc -l` TIME_WAIT=`netstat -nat | egrep 'TIME_WAIT' | wc -l` CLOSE_WAIT=`netstat -nat | egrep 'CLOSE_WAIT' | wc -l` SYN_SENT=`netstat -nat | egrep 'SYN_SEND' | wc -l` SYN_RECV=`netstat -nat | egrep 'SYN_RECVEIVED' | wc -l` echo $ESTABLISHED echo $TIME_WAIT echo $CLOSE_WAIT echo $SYN_SENT echo $SYN_RECV The output should just the count of each connection status on 5 separate lines. – monkeychef Sep 03 '15 at 18:02
-
@monkeychef You should edit your original post with that information. – Matt Jacob Sep 03 '15 at 18:40
1 Answers
1
The following (should) work without making any changes on both *nix and Windows. I've tested it on Ubuntu w/ Perl v.5.18.0, Linux Mint w/ Perl v5.22.0 and Win2k8R2 (w/ Strawberry Perl v5.8.8).
#!/usr/bin/perl
use strict;
use warnings;
my @stat = split '\n', `netstat -nat`;
my @wanted = qw(
ESTABLISHED
TIME_WAIT
CLOSED_WAIT
SYN_SENT
SYN_RECV
);
my %data = map {$_ => 0} @wanted;
for (@stat){
s/^\s+//;
my $status;
if ($^O eq 'MSWin32'){
$status = (split)[3];
}
else {
$status = (split)[5];
}
next if ! $status;
$data{$status}++ if defined $data{$status};
}
print "$data{$_}\n" for @wanted;

stevieb
- 9,065
- 3
- 26
- 36
-
This is fantastic, thank you! I attempted to add two other status's (syn_sent and syn_received) by modifying line 6 and adding two lines at the end however that seems to break the script. Is there a certain way this needs to be done? – monkeychef Sep 03 '15 at 19:06
-
I've made some significant efficiency changes. If you want to add more entries, put them in the `@wanted` list. The output prints in the order the `@wanted` list is in. You can add/remove from that list and it will not affect anything other than the output. – stevieb Sep 04 '15 at 00:35
-
1