· 7 years ago · Oct 08, 2018, 11:02 AM
1#!/usr/bin/perl
2use warnings;
3use strict;
4use DBI;
5use POSIX qw(strftime);
6use Text::ASCIITable;
7
8my $db_file = $ENV{'HOME'} . "/.log.db";
9my $dbh = DBI->connect( "dbi:SQLite:" . $db_file );
10my $table = Text::ASCIITable->new();
11$table->setCols( 'Time', 'IP', 'Message' );
12
13$dbh->do( "CREATE TABLE IF NOT EXISTS `entry` (
14 id INTEGER PRIMARY KEY,
15 timestamp int,
16 remote VARCHAR( 2048 ),
17 entry TEXT )" );
18
19if( $ARGV[0] && $ARGV[0] eq '--report' ) {
20 my $sql = 'SELECT * FROM `entry`';
21 if( $ARGV[1] && $ARGV[1] eq 'day' ) {
22 $sql .= ' WHERE `timestamp` > ' . $dbh->quote( time()-86400 );
23 } elsif( $ARGV[1] && $ARGV[1] eq 'week' ) {
24 $sql .= ' WHERE `timestamp` > ' . $dbh->quote( time()-604800 );
25 } elsif( $ARGV[1] && $ARGV[1] eq 'month' ) {
26 $sql .= ' WHERE `timestamp` > ' . $dbh->quote( time()-2629743 );
27 } elsif( $ARGV[1] && $ARGV[1] eq 'year' ) {
28 $sql .= ' WHERE `timestamp` > ' . $dbh->quote( time()-31556926 );
29 } elsif( $ARGV[1] && $ARGV[1] eq 'all' ) {
30 } elsif( $ARGV[1] && $ARGV[1] eq 'search' ) {
31 if( $ARGV[2] ) {
32 $sql .= ' WHERE `entry` LIKE ' . $dbh->quote( '%' . $ARGV[2] . '%' );
33 } else {
34 print "Unknown search string\n";
35 exit 1;
36 }
37 } else {
38 print "Unknown report requested\n";
39 exit 1;
40 }
41
42 my $sth = $dbh->prepare( $sql );
43 $sth->execute();
44 while( my $row = $sth->fetchrow_hashref() ) {
45 my $ts = strftime( '%H:%M:%S %m/%d/%Y', localtime( $row->{'timestamp'} ) );
46 $table->addRow( $ts, $row->{'remote'}, $row->{'entry'} );
47 }
48 print $table . "\n";
49
50} elsif( $ARGV[0] ) {
51 my $remote = 'Unknown';
52 my $message = '';
53 for( @ARGV ) {
54 $message .= $_ . " ";
55 }
56 if( $ENV{'SSH_CLIENT'} && $ENV{'SSH_CLIENT'} =~ /^(\d+\.\d+\.\d+\.\d+)\s+\d+\s+\d+$/ ) {
57 $remote = $1;
58 }
59 $dbh->do( "INSERT INTO `entry` (`id`, `timestamp`, `remote`, `entry`) VALUES(NULL, " . $dbh->quote( time() ) . ", " . $dbh->quote( $remote ) . ", " . $dbh->quote( $message ) . ")");
60 print "Logged '" . $message . "' from '" . $remote . "'\n";
61} else {
62 print "Usage: log <--report [day|month|year|all|search]> <message>\n";
63 exit 0;
64}