2013-04-05 59 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); 
相關問題