简体   繁体   English

如何使用Perl DBI sqlite从日志文件中获取信息并将其添加到数据库表

[英]How to get information from log files and add them to database table using Perl DBI sqlite

I have this assignment which requires me to take the source ip and destination port from this log file and add them to a database table i created using Perl dbi sqlite. 我有这项工作,需要我从此日志文件中获取源IP和目标端口,并将它们添加到我使用Perl dbi sqlite创建的数据库表中。 i have tried to write a script that does that but it does not seem to work. 我试图编写一个脚本来做到这一点,但它似乎不起作用。 i would appreciate any help. 我将不胜感激任何帮助。 The log file is available at http://fleming0.flemingc.on.ca/~chbaker/COMP234-Perl/sample.log 日志文件位于http://fleming0.flemingc.on.ca/~chbaker/COMP234-Perl/sample.log

here is the code i have so far. 这是我到目前为止的代码。

#!/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) Change your regular expression: 1)更改您的正则表达式:

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

2) Change your SQL's 2)更改您的SQL

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

UPDATE In any case, it's better to build sql sentences with parameter binding and avoid the SQL-injection problems: UPDATE无论如何,最好使用参数绑定来构建sql语句,并避免SQL注入问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM