2013-04-05 22 views
0

我有这个任务,它需要我从此日志文件中获取源IP和目标端口,并将它们添加到使用Perl创建的数据库表中dbi sqlite。 我试图写一个脚本来做,但它似乎没有工作。我将不胜感激任何帮助。日志文件可在 http://fleming0.flemingc.on.ca/~chbaker/COMP234-Perl/sample.log如何从日志文件中获取信息并使用Perl DBI将它们添加到数据库表sqlite

这里是我到目前为止的代码。

#!/usr/bin/perl 

use strict; 
use warnings; 
use DBI; 

my %ip2port; 
my $IPCount = keys %ip2port; 
my $portCount = 0; 
my $filename = "./sample.log"; 
open my $LOG, "<", $filename or die "Can't open $filename: $!"; 
LINE: while (my $line = <$LOG>) { 
my ($src_id) = $line =~ m!SRC=([.\d]+)!gis; my ($dst_port) = $line =~ m!DPT=([.\d]+)!gis; 
my $dbh = DBI->connect(   
    "dbi:SQLite:dbname=test.db", 
    "",       
    "",       
    { RaiseError => 1 },   
) or die $DBI::errstr; 


$dbh->do("INSERT INTO probes VALUES($src_id, $dst_port)"); 
$dbh->do("INSERT INTO probes VALUES(2,'$dst_port',57127)"); 
my $sth = $dbh->prepare("SELECT SQLITE_VERSION()"); 
$sth->execute(); 

my $ver = $sth->fetch(); 

print @$ver; 
print "\n"; 

$sth->finish(); 
$dbh->disconnect(); 
} 
+1

什么不行?你做了什么来诊断问题? – friedo 2013-04-05 20:20:13

+0

do语句不起作用,我想帮助验证天气我的脚本处于正确的状态,还是有错误 – user218001 2013-04-05 20:45:18

+0

哦,有错误没问题。但我仍然想知道你的意思是“不工作”。 – friedo 2013-04-05 20:46:01

回答

0

1)改变你的正则表达式:

my ($src_id) = $line =~ m!SRC=([\.\d]+)!g; 
my ($dst_port) = $line =~ m!DPT=([\d]+)!g; 

2)更改SQL的

$dbh->do("INSERT INTO probes VALUES('$src_id', $dst_port)"); 

UPDATE 在任何情况下,这是更好地建立与参数绑定的SQL语句并避免SQL注入问题:

$dbh->do("INSERT INTO probes VALUES(?,?)", undef, $src_id, $dst_port); 
相关问题