I’m having difficulty with one little bit of my code.
open ("files","$list");
while (my $sort = <files>) {
chomp $sort;
foreach my $key (sort keys %ips) {
if ($key =~ $sort) {
print "key $key\n";
my $match =qx(iptables -nL | grep $key 2>&1);
print "Match Results $match\n";
chomp $match;
my $banned = $1 if $match =~ (/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/);
print "Banned Results $banned\n";
if ($key =~ $banned) {
print "Already banned $banned\n";
} else {
system ("iptables -A INPUT -s $key -j DROP");
open my $fh, '>>', 'banned.out';
print "Match Found we need to block it $key\n";
print $fh "$key:$timestamp\n";
close $fh;
}
}
}
}
So basically what I’m doing is opening a list of addresses 1 per line.
Next I’m sorting down my key variable from another section of my script and matching it with my list, if it matches then it continues on to the if statement.
Now with that matched key I need to check and see if its blocked already or not, so I’m using a qx to execute iptables and grep for that variable. If it matches everything works perfectly.
If it does not match, in other words my iptables -nL | grep $key returns a blank value instead of moving on to my else statement it “grabs” that blank value for $match and continues to execute.
For the life of me I can’t figure out how to strip that blank value out and basically show it as no return.
I know there are modules for iptables etc however I have to keep this script as generic as possible.
The problem is that, when
iptablesreturns no results,$bannedis left at its default value ofundef. Used as a regex, $banned matches every string, so your condition:always matches. I think what you meant to write was probably
which will fail if either
$bannedisundef(because$matchedwas empty or didn’t match the regex) or if the IP address you pulled out with the regex was somehow different from$key.If you’re confident that the first IP in the
iptablesresult will be the same as$keythen you could simplify your condition to just