Files
banip/ban2mysql.pl
2025-01-26 17:18:15 +01:00

138 lines
3.7 KiB
Perl

#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use DateTime;
use Data::Printer;
use File::Slurp;
use Mojo::UserAgent;
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
$year = $year+1900;
my $month2int = {
'jan' => '01',
'feb' => '02',
'mar' => '03',
'apr' => '04',
'may' => '05',
'jun' => '06',
'jul' => '07',
'aug' => '08',
'sep' => '09',
'oct' => '10',
'nov' => '11',
'dez' => '12'
};
# Connect to the database.
my $dbh = DBI->connect("DBI:MariaDB:database=kram;host=edna",
"steffen", "66WXRlvF0UUV",
{'RaiseError' => 1});
my @file = read_file('sys.log.1');
my $ua = Mojo::UserAgent->new();
my %nolandforip;
my %nolandips;
my $hundred = 0;
my $first = 0;
$nolandips{$first} = ();
for my $l ( @file ) {
my ( $month, $day, $h, $m, $s, $kat, $src, $dst, $port ) = $l =~ /(.*?) (.*?) (..):(..):(..) 192.*banIP\/...-wan\/drop\/(.*?):.*SRC=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) DST=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*DPT=(\d+)/;
#$ua->get("http://ip-api.com/json/$src" => {Accept => '*/*'})->result->body;
# p $ua;
my $dt = '';
if ( $month ) {
$month = $month2int->{lc $month};
my $mysqldt = "$year-$month-$day $h:$m:$s";
my $dt1 = DateTime->new(
year => $year,
month => $month,
day => $day,
hour => $h,
minute => $m,
second => $s
);
# p $dt;
my $da = $dbh->selectrow_hashref('SELECT * FROM banip_attacker WHERE src = ? and port = ?', undef, $src, $port );
if ( $da ) {
my ( $year2, $month2, $day2, $h2, $m2, $s2) = $da->{updated} =~ /(....)-(..)-(..) (..):(..):(..)/;
my $dt2 = DateTime->new(
year => $year2,
month => $month2,
day => $day2,
hour => $h2,
minute => $m2,
second => $s2
);
my $cmp = DateTime->compare( $dt1, $dt2 );
if ( $cmp == 1 ) {
$dbh->do('UPDATE banip_attacker set count = count + 1, updated = ? WHERE src = ? and port = ?', undef, $mysqldt, $src, $port );
}
if ( ! $nolandforip{$src} ) {
if ( !$da->{land} ) {
$nolandforip{$src} = 1;
if ( $hundred == 100 ) {
$first ++;
$nolandips{$first} = ();
$hundred = 0;
}
push @{$nolandips{$first}}, {"query"=> $src, "fields"=> "country,countryCode,query", "lang"=> "de"};
$hundred ++;
}
}
} else {
$dbh->do(
'INSERT INTO banip_attacker (
created,
updated,
src,
dst,
port,
kat)
VALUES (
?,
?,
?,
?,
?,
?)', undef,
$mysqldt,
$mysqldt,
$src,
$dst,
$port,
$kat);
}
}
}
for my $ar ( keys %nolandips ) {
my $req = $ua->post("http://ip-api.com/batch" => {Accept => '*/*'} => json => $nolandips{$ar} )->result->json;
# p $req;
for my $query ( @$req ) {
$dbh->do('UPDATE banip_attacker set land = ? WHERE src = ?', undef, $query->{country}, $query->{query} );
}
# p $nolandips{$ar};
}