Mon Mar  6 23:56:13 CET 2006

ssh logs


For a long time now I've wanted some sort of summary of all
the connections (successful and otherwise) to my main openssh
server. I've searched a little half-heartedly earlier, and I
didnt find anything interesting.

Today I decided to give it another shot, and found breakinguard.
Its a nice perl hack which notices if someone has tried and
failed to log in to the machine, and if the person fails more
than N times, will block the offending ip for M
seconds. Nice!

This doesnt really cover the converse situation though- I
want a breakdown of all the logins- both failed and
successful. So I wrote a little hack which does it. Its not
pretty, but it does its job.

use Getopt::Std;

getopts('hc', \%opts) || usage();
if ( defined($opts{h}) || (!defined($opts{c}))) {

# ssh logfile
my $LOGFILE='/var/log/auth.log';

# search for this day
my $prefix=`date "+%b %e "`; chop $prefix;
my $rgx=qr/$prefix/;

# start
open (LOG, "<$LOGFILE");
my @list = grep {/^$rgx/} <LOG>;
close LOG;

my %accepted;
my %failed;

foreach my $line (@list) {
my ($user , $ip) =  
$line =~ /Accepted.*?for (\w*?) from (.*?) port/;
if (defined($user) && defined($ip)) {
${$accepted{$ip}}{$user} = ${$accepted{$ip}}{$user} + 1;
} else {
($user , $ip) = 
$line =~ /Failed.*?for invalid user (\w*?) from (.*?) port/;
if (defined($user) && defined($ip)) {
${$failed{$ip}}{$user} = ${$failed{$ip}}{$user} + 1;

foreach my $i (sort {$a =~ /^(\d+)\./ 
$b =~ /^(\d+)\./
} (keys %accepted, keys %failed) ) {
print $i . "\n";
foreach my $u (sort keys %{  $accepted{$i}  }    ) {
print "\t+ $u\t" . ${$accepted{$i}}{$u} . "\n";
foreach my $u (sort keys %{  $failed{$i}  }    ) {
print "\t- $u\t" . ${$failed{$i}}{$u} . "\n";

sub usage {
print "Usage:\n\t$0 -c to run.\n";
exit 1;
The output is very rudimentary, but its enough to stick in root's crontab at, say a minute to midnight. --