Last active
October 9, 2022 17:51
-
-
Save SpareSimian/cc6ba11f13ccb71bbf207847e395b427 to your computer and use it in GitHub Desktop.
List bans in fail2ban database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -T -w | |
# dump current fail2ban bans for all jails in jail order, for use in | |
# daily emailed reports | |
use strict; | |
use DBI; | |
sub formatBantime { | |
my $banDurationSeconds = $_[0]; | |
my $banDuration; | |
if ($banDurationSeconds < 60) { | |
$banDuration = "$banDurationSeconds seconds"; | |
} elsif ($banDurationSeconds < 3600) { | |
my $minutes = $banDurationSeconds / 60; | |
$banDuration = "$minutes minutes"; | |
} elsif ($banDurationSeconds < (3600 * 24)) { | |
my $hours = $banDurationSeconds / 3600; | |
$banDuration = "$hours hours"; | |
} else { | |
my $days = $banDurationSeconds / (3600 * 24); | |
$banDuration = "$days days"; | |
} | |
return $banDuration; | |
} | |
my $driver = "SQLite"; | |
my $db_name = "/var/lib/fail2ban/fail2ban.sqlite3"; | |
my $dbd = "DBI:$driver:dbname=$db_name"; | |
my $dbh = DBI->connect($dbd, | |
undef, undef, | |
{ RaiseError => 1 }) | |
or die $DBI::errstr; | |
my $banCount = 0; | |
my $stmtJails = qq(SELECT name from jails where enabled = 1 order by name;); | |
my $objJails = $dbh->prepare($stmtJails); | |
my $retJails = $objJails->execute() or die $DBI::errstr; | |
while (my @rowJails = $objJails->fetchrow_array()) { | |
my $jail = $rowJails[0]; | |
my $stmtBans = qq(SELECT ip, timeofban, bantime from bans where jail = ? order by ip;); | |
my $objBans = $dbh->prepare($stmtBans); | |
my $retBans = $objBans->execute($jail) or die $DBI::errstr; | |
my $bans = ""; | |
my $banDurationSeconds; # could vary between IPs, just use the last one for each jail | |
while (my @rowBans = $objBans->fetchrow_array()) { | |
my $ip = $rowBans[0]; | |
my $timeOfBan = localtime($rowBans[1]); | |
$banDurationSeconds = $rowBans[2]; | |
$bans = $bans . sprintf(" %-15s banned at %24s for %s\n", $ip, $timeOfBan, formatBantime($banDurationSeconds)); | |
$banCount++; | |
} | |
if ("" ne $bans) { | |
my $banDuration = formatBantime($banDurationSeconds); | |
print "jail $jail for $banDuration\n"; | |
print $bans; | |
} | |
} | |
$dbh->disconnect(); | |
if ($banCount > 0) { | |
print "$banCount total bans\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment