Files
cacti/scripts/unix_tcp_connections.pl
7ca0582b3c Refactor Perl scripts with Code Quality findings (#6594)
* add perl syntax checking for scripts

* Update .github/workflows/syntax.yml

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* only show syntax errors

* Add support for ss

Fixed shell injection risk from piped netstat | grep by removing shell pipelines.
Added use strict; use warnings; and localized variables.
Added runtime fallback to ss when netstat is unavailable, with a clear failure when neither exists.

* Fix shell injection risk

apply fixes (safe open, strict/warnings, key whitelist, error handling).

* Update query_unix_partitions.pl

* Update unix_users.pl

add use strict/warnings  to flag issues
add better error handling

* Update weatherbug.pl

* add better suport for gree bsd

* Update loadavg.pl

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
2026-01-31 20:25:42 -05:00

62 lines
1.2 KiB
Perl

#!/usr/bin/env perl
use strict;
use warnings;
delete @ENV{qw(PATH)};
$ENV{PATH} = '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin';
my $grep_string = $ARGV[0] // '';
($grep_string) = $grep_string =~ /^([\w]+)$/ if $grep_string ne '';
chomp $grep_string;
sub find_cmd {
my @candidates = @_;
for my $cmd (@candidates) {
return $cmd if -x $cmd;
}
return undef;
}
my @cmd;
my $mode = '';
my $netstat = find_cmd('/bin/netstat', '/usr/bin/netstat', '/usr/sbin/netstat');
if (defined $netstat) {
@cmd = ($netstat, '-n');
$mode = 'netstat';
} else {
my $ss = find_cmd('/bin/ss', '/usr/bin/ss', '/usr/sbin/ss');
if (defined $ss) {
@cmd = ($ss, '-tan');
$mode = 'ss';
} else {
print 'U';
exit 1;
}
}
open(my $process, '-|', @cmd) or exit 1;
my $count = 0;
while (my $line = <$process>) {
chomp($line);
if ($mode eq 'netstat') {
next unless $line =~ /tcp/;
if ($grep_string ne '') {
next unless $line =~ /$grep_string/;
}
$count++;
} else {
next if $line =~ /^State\s+/;
if ($grep_string ne '') {
next unless $line =~ /$grep_string/;
}
$count++;
}
}
close($process);
print $count;