如何将网络数据包捕获到MySQL

时间:2011-09-13 19:03:56

标签: mysql networking tcpdump sniffer tshark

我打算为WiFi(802.11)设计网络分析仪 目前我使用tshark来捕获和解析WiFi帧,然后将输出传递给perl脚本,以将解析后的信息存储到Mysql数据库。

我发现在这个过程中我错过了很多帧。我检查并且在管道期间框架似乎丢失了(当输出传递到perl以在Mysql中获取时) 这是怎么回事

(Tshark)-------帧丢失----> (Perl)--------> (MySQL的) 这就是我如何将tshark的输出传递给脚本:

sudo tshark -i mon0 -t ad -T fields -e frame.time -e frame.len -e frame.cap_len -e radiotap.length | perl tshark-sql-capture.pl 

这是我使用的perl脚本的简单模板(tshark-sql-capture.pl)

# preparing the MySQL
my $dns = "DBI:mysql:capture;localhost";
my $dbh = DBI->connect($dns,user,pass);
my $db = "captured";

while (<STDIN>) {
    chomp($data = <STDIN>);
    ($time, $frame_len, $cap_len, $radiotap_len) = split "  ", $data;
    my $sth = $dbh-> prepare("INSERT INTO $db VALUES (str_to_date('$time','%M %d, %Y %H:%i:%s.%f'), '$frame_len', '$cap_len', '$radiotap_len'\n)" );
    $sth->execute;
}

#Terminate MySQL
$dbh->disconnect;

任何可以帮助提高性能的想法都值得赞赏。或者可能有一种可以做得更好的替代机制。 现在我的表现是50%意味着我可以在我捕获的一半数据包中存储mysql。

3 个答案:

答案 0 :(得分:1)

写在管道中的东西不会丢失,可能真正发生的是tshark尝试写入管道但是perl + mysql太慢而无法处理输入因此pipeb已满,write会阻塞所以tshark只是丢弃数据包。

瓶颈可能是MySQL或Perl本身,但可能是数据库。检查CPU使用情况,测量插入率。然后选择更快的DB或写入多个DB。您还可以尝试批量插入并增加管道缓冲区的大小。

<强>更新

while (<STDIN>)

这会在$_中读取一行,然后忽略它。

答案 1 :(得分:0)

您可以使用FIFO文件,然后使用插入延迟读取数据包并在mysql中插入。

sudo tshark -i mon0 -t ad -T fields -e frame.time -e frame.len -e frame.cap_len -e radiotap.length > MYFIFO

答案 2 :(得分:0)

对于管道问题,您可以使用GULP http://staff.washington.edu/corey/gulp/

改进数据包捕获

来自手册页:

1) reduce packet loss of a tcpdump packet capture:
      (gulp -c works in any pipeline as it does no data interpretation)

        tcpdump -i eth1 -w - ... | gulp -c > pcapfile
      or if you have more than 2, run tcpdump and gulp on different CPUs
        taskset -c 2 tcpdump -i eth1 -w - ... | gulp -c > pcapfile

      (gulp uses CPUs #0,1 so use #2 for tcpdump to reduce interference)