离线分析数据包文件端口流量以及占比脚本

在验证正确性的时候,时常要统计指定端口的流量,也就是frame length,这里是一个简单的PERL程序,将打印所有的端口流量,以及流量所占比例,可以在Linux系统下安装有tshark的环境下运行

#!/usr/bin/perl
##########################################
##input:
##  trace file list
##output:
##  ports traffic information
##require:
##  tshark
##2014-03-24 HuiLi
###########################################

use threads;
use Term::ANSIColor;

sub Tshark {
        if ( -f "/usr/bin/tshark" || -f "/usr/local/bin/tshark" || -f "/usr/sbin/tshark" ){
#               print "OK, tshark exist !\n";
        }
        else {
                print "Tshark not found, please install it first !\n";
                exit;
        }
}

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;
                }
                #($ports, $traffic) = split /\s+/, $_;
                #$ports_traffic{$ports} += $traffic;
        }
            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 Function##########################################
Tshark();
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);

发表回复