D&C GLug - Home Page

[ Date Index ] [ Thread Index ] [ <= Previous by date / thread ] [ Next by date / thread => ]

[LUG] how to use perl DBI?

 

Thanks to Simon's hint I got trafstats running in the end,
but it is total overkill for what I need. So I thought I would
write my 2nd ever Perl Script. (machine is running Debian/Stable)

I got the first part going by modifying the
code in section 10.4 of O'Reilly Perl for System Administration

#!/usr/bin/perl -T -W
use strict;
use warnings;

use Net::PcapUtils;
use NetPacket::Ethernet;
use NetPacket::IP;

my $myip = "10.0.0.4";
my $prog = "udp port 123 and dst host $myip";

$| = 1;

die "unable to perform capture\n"
       if (Net::PcapUtils::loop(\&grab_ip, FILTER => $prog, PROMISC
=>0, DEV => eth0));

sub grab_ip{
       my ($arg,$hdr,$pkt) = @_ ;
       my $src_ip = NetPacket::IP->decode(
               NetPacket::Ethernet::strip($pkt))->{src_ip};

       print "$src_ip\n";
}

but I really want to replace that print statememt with a 
line to insert the src_ip into a Postgresql database.

the database is there (ntp-stats)
# psql -U david -l
       List of databases
  Name    |  Owner   | Encoding
-----------+----------+-----------
david     | david    | SQL_ASCII
mydb      | david    | SQL_ASCII
ntp-stats | david    | SQL_ASCII
template0 | postgres | SQL_ASCII
template1 | postgres | SQL_ASCII
trafstats | david    | SQL_ASCII
(6 rows)

I can connect to it
# psql -U david ntp-stats
ntp-stats=# \d
    List of relations
   Name    | Type  | Owner
------------+-------+-------
ntptraffic | table | david
(1 row)

but of course there is nothing in it yet
ntp-stats=# select * from ntptraffic;
ipaddress | at
-----------+----
(0 rows)

The at column was created with 'at timestamp not null default now()'
so hopefully it should be an automatic timestamp of when the ipaddress
was inserted.

so I tried a quick hack to try out DBI (based on chapter 10
of MySQL from O'Reilly)

#!/usr/bin/perl -T -W
use strict;
use warnings;
use DBI;

my $user = "david";
my $mydb = "ntp-stats";
my $dbh = DBI->connect("DBI:Pg:$mydb", $user, undef);

$dbh->disconnect;

but all I get is -

DBI->connect(ntp-stats) failed: missing "=" after "ntp-stats" in
connection info string at ./test4.pl line 8
Can't call method "disconnect" on an undefined value at ./test4.pl
line 10.

how do you connect to a Postgresql database?

best regards
Dave
-- 
http://www.morgad.no-ip.info/index.html    gpg:0x64B5E037 
Distributed Proofreaders: http://www.pgdp.net
The NTP server pool http://www.pool.ntp.org

--
The Mailing List for the Devon & Cornwall LUG
Mail majordomo@xxxxxxxxxxxxx with "unsubscribe list" in the
message body to unsubscribe. FAQ: www.dcglug.org.uk/linux_adm/list-faq.html