脚本调用tshark分析网络数据包

当需要分析的网络数据包很庞大时,仅仅靠wireshark打开做分析不太现实,首先是内存限制,一般必须在服务器上进行解析;其次由于速度比较缓慢,打开之后还要分析或者二次分析,显得效率十分低下,因此可通过脚本直接调用wireshark的命令行程序tshark来进行解析,进而脚本里进行二次分析,基本可以一次到位,下面提供一个简单的分析perl脚本为例,统计处出数据包各端口流量以及所占的比例情况(想统计其它信息只需要修改tshark命令以及二次分析稍作修改),只需要将数据包当作参数运行即可:

perl XXXX.pl XXXX.pcap

 

#!/usr/bin/perl

use threads;
use Term::ANSIColor;

sub Get_pcap {

    my $pcap_path_file = shift;
    my $pcap_file;
    if($pcap_path_file =~ /.*\/(.*)/){
        $pcap_file = $1;
    }
    else {
        $pcap_file = $pcap_path_file;
    }
    return $pcap_file;
}

sub Ports_traffic {

    my ($four_trace_file, $four_parser_pf) = @_;

    my %ports_traffic;
    my $ports;
    my $traffic;
    my $total_traffic;

    open $FOUR, “tshark -r $four_trace_file -T fields -e tcp.port -e frame.len |”;
    while(<$FOUR>){
        if(/(\d+),(\d+)\s+(\d+)/){
            $srcports = $1;
            $dstports = $2;
                    $ports_traffic{$srcports} += $3;
                    $ports_traffic{$dstports} += $3;
                    $total_traffic += $3;
            }
    }
        close($FOUR);
    #    print $total_traffic;
        foreach my $key (sort { $ports_traffic{$b} <=> $ports_traffic{$a} } keys %ports_traffic ){
            my $traffic_rate = $ports_traffic{$key} * 100 / $total_traffic;
            print $four_parser_pf “$key    :    $ports_traffic{$key}    =>    $traffic_rate% \n”;
        }
}

############################################Main
chomp(my $file_list = $ARGV[0]);
print “Sorry, please run the script with a file list as ARGV !\n” and exit if !$file_list;
print “Sorry, trace file list $file_list not found !\n” and exit if !-f $file_list;
open my($PCAP), ‘<‘, $file_list;
while (my $trace_file = <$PCAP>){
    chomp($trace_file);
    my $pcap_file = Get_pcap($trace_file);

    my $parser_file = $pcap_file . “.ports_traffic”;
    unlink $parser_file if -f $parser_file;
    open my($PARSER), ‘>>’, $parser_file;

    my $t17 = threads->create(\&Ports_traffic, $trace_file, $PARSER);

    $t17->join();
    print color ‘bold green’;
    print “About $trace_file, ports_traffic information saved in $parser_file \n”;
    print color ‘reset’;
}
close($PARSER);
close($PCAP);

发表评论