Skip to content

Instantly share code, notes, and snippets.

@SpareSimian
Last active October 9, 2022 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpareSimian/cc6ba11f13ccb71bbf207847e395b427 to your computer and use it in GitHub Desktop.
Save SpareSimian/cc6ba11f13ccb71bbf207847e395b427 to your computer and use it in GitHub Desktop.
List bans in fail2ban database
#!/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