0

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

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

#!/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();
}
4

1 回答 1

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);
于 2013-04-05T21:04:32.007 回答