From 92379574efacf922aff34e3030b0d8aad95a0fdf Mon Sep 17 00:00:00 2001 From: Sergey Kalinin Date: Fri, 15 Jan 2021 18:43:34 +0300 Subject: [PATCH] Initial release --- README.md | 1 + cgi/loginsearch | 288 ++++++++++++++++++++++++ cgi/search | 173 +++++++++++++++ cgi/usersearch | 117 ++++++++++ etc/protocol.csv | 499 ++++++++++++++++++++++++++++++++++++++++++ etc/rdrcollector.conf | 4 + rdrarchiver.pl | 76 +++++++ rdrcolld | 27 +++ rdrcollector.pl | 219 ++++++++++++++++++ 9 files changed, 1404 insertions(+) create mode 100644 README.md create mode 100755 cgi/loginsearch create mode 100755 cgi/search create mode 100755 cgi/usersearch create mode 100644 etc/protocol.csv create mode 100644 etc/rdrcollector.conf create mode 100755 rdrarchiver.pl create mode 100755 rdrcolld create mode 100755 rdrcollector.pl diff --git a/README.md b/README.md new file mode 100644 index 0000000..3fc9297 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +rdrcollector - Сервис сбора RDR (Raw Data Records) потока с CISCO SCE и cgi-скрипты для визуализации. diff --git a/cgi/loginsearch b/cgi/loginsearch new file mode 100755 index 0000000..533522e --- /dev/null +++ b/cgi/loginsearch @@ -0,0 +1,288 @@ +#!/usr/bin/perl + +######################################################################### +# +# CGI скрипт для поиска и визуализации данных собранных rdrcollector-ом +# по логину абонента +# +# Автор: Сергей Калинин e-mail: banzaj28@yandex.ru +# распространяется под лицензией GPL +# (c) 2015 +######################################################################### + +use CGI ':standard'; +use DBI; +use Time::Local; + +# Вывод заголовка +print header(-type=>'text/html', -charset=>'utf-8'); +print start_html("Поиск сессий абонента по имени пользователя"); +print "

Поиск сессий абонента по имени пользователя

\n"; +print "
\n"; + +print_prompt(); +do_work(); +print_tail(); + +read_protocol(); + +print end_html; + + +######################################################################### +# описание процедур +######################################################################### + +# вывод формы с полями +sub print_prompt { + print start_form; + print "

"; + print ""; + print ""; + print ""; + print "
Дата (ДД.ММ.ГГГГ)".textfield('date')."
Имя пользователя".textfield('login')."
"; + #print "sss"; + # print "

",reset; + print submit('Action','Выполнить'); + print end_form; + print "


\n"; +} + +# проверка корректности даты +sub match_date { + my $input = shift; + if ($input =~ m!^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$!) { + # At this point, $1 holds the year, $2 the month and $3 the day of the date entered + if ($3 == 31 and ($2 == 4 or $2 == 6 or $2 == 9 or $2 == 11)) { + return 0; # 31st of a month with 30 days + } elsif ($3 >= 30 and $2 == 2) { + return 0; # February 30th or 31st + } elsif ($2 == 2 and $3 == 29 and not ($1 % 4 == 0 and ($1 % 100 != 0 or $1 % 400 == 0))) { + return 0; # February 29th outside a leap year + } else { + return $input; # Valid date + } + } else { + return 0; # Not a date + } +} + +sub do_work { + my $key; + my $cmd; + # получаем данные введённые в форме + # и проверяем формат + my $date = match_date(param(date)); + my $login = param(login); + my $contract = param(contr); + # если данные введены не верно выводим сообщение + chomp $login; + + if ($login eq "") + { + print "Введите имя пользователя"; + exit; + } + if ($date eq "" || $date == 0) + { + print "Необходимо корректно ввести дату"; + exit; + } + + login_search($date, $login, $contract) +} + + +sub ip_search { + my $key; + my $cmd; + # получаем данные введённые в форме + # и проверяем формат + my $date = $_[0]; + my ($date_start, $t_start) = split (" ", $_[1]); + my ($date_stop, $t_stop) = split (" ", $_[2]); + my $src = $_[3]; + my $dst; + # Преобразуем дату и время в unixtime + # начало сессии + my ($hour, $min, $sec) = split(':',$t_start); + my ($year, $month, $day) = split('-',$date_start); + my $time_start = timelocal($sec,$min,$hour,$day,$month,$year)."\n"; + # конец сессии + ($hour, $min, $sec) = split(':',$t_stop); + ($year, $month, $day) = split('-',$date_stop); + my $time_stop = timelocal($sec,$min,$hour,$day,$month,$year)."\n"; + + + # если данные введены не верно выводим сообщение + if ($dst eq 0 || $src eq 0) + { + print "Введите корректный IP адрес"; + exit; + } + + # формируем каталог для поиска в соответствии с датой + my ($dday,$dmonth,$dyear) = split(/\./,$date); + my $dir = "/var/srv/rdrcollector/$dyear/$dmonth/$dday"; + # формируем команду поиска данных в зависимости от даты и IP адресов (1 или 2 адреса) + # определяем каталог в архиве и если он есть ищем данные в файлах этого каталога + # если такого каталога нет - поиск производится в кэше. + if (-d $dir) + { + if ($dst eq "") { + $cmd = "/usr/bin/gzip -c -d ".$dir."/*.gz | /usr/bin/grep -h ".$src."@"; + } else { + $cmd = "/usr/bin/gzip -c -d ".$dir."/*.gz | /usr/bin/grep -h ".$src."@ | /bin/grep ".$dst; + } + } else { + print "Данные за $date в архиве не найдены производится поиск за последние сутки
"; + if ($dst eq "") { + $cmd = "/usr/bin/grep -h ".$src."@ /var/cache/rdrcollector/*"; + } else { + $cmd = "/usr/bin/grep -h ".$src."@ /var/cache/rdrcollector/* | /usr/bin/grep ".$dst; + } + } + # выполняем команду поиска и выводим данные ввиде html-таблицы + #print "

Список TCP/IP сессий c адреса ".$src." за ".$date."

"; + # заголовок таблицы + print ""; + my $i = 0; + my $bgcolor; + my $session_up; + my $session_down; + # команда выполняется и результат обрабатывается циклом + foreach my $lines (`$cmd`) { + my $expr = $i % 2; + # чередование цвета фона строк для чётных и не чётных + if ($expr eq 0) { + $bgcolor = "#fffff"; + } else { + $bgcolor = "#c5eaff"; + } + # разбиваем строку на поля для удобства вывода. + my ($date_time, $client, $client_ip, $server_ip, $up_down, $protocol_sign) = split(/\t/, $lines); + # определяем IP абонента + my ($user_ip, $group) = split("@", $client); + # проверка на пустое поле даты или идетнификатора абонента + # бывают покоцанные файлы + if ($date_time eq "" || $client eq "") + { + next; + } + # преобразуем дату время найденного соединения в unixtime + my ($t, $date) = split(" ", $date_time); + ($day, $month, $year) = split(/\./,$date); + ($hour, $min, $sec) = split(':',$t); + #print "$date_time - $hour $min $sec $day $month $year
"; + my $time = timelocal($sec, $min, $hour, $day, $month, $year); + # сравниваем дату и время TCP/IP сессии с датой и временем сессии абонента в биллинге + # и если она входит в диапазон, выводим на экран + if ($time > $time_start && $time < $time_stop) { + # отбрасываем записи о "пустых" соединениях +# if ($client_ip ne ":" || $server_ip ne ":") { + # считаем трафик + my ($up, $down) = split("/", $up_down); + $session_up += $up; + $session_down += $down; + # определяем название протокола по его подписи + $protocol = read_protocol("$protocol_sign"); + # вводим данные + print ""; + print ""; + print "\n"; + $i++; +# } + } +# exit; + } + print "\n"; + print "
ДатаАбонентIP клиентаIP сервераТрафик вх/исхПротоколИнформация
$date_time$client$client_ip$server_ip$up_down$protocol$info_string
Всего трафика$session_up / $session_down
"; +} + +sub print_tail { + print "
© 2015, OOO \"Терион\"
"; +} + +# читаем файл с описанием протокола +sub read_protocol { + #print $_[0]; + $cmd = "/usr/bin/grep -h \'".$_[0]."\' /usr/local/etc/protocol.csv"; + my $lines = `$cmd`; + #print "$lines"; + if ($lines) { + my ($prot, $signature) = split(";", $lines); + return $prot; + } else { + return $_[0]; + } +} +# поиск данных в БД биллинга +sub login_search { + + my $login = param(login); + my $date = param(date); + my $contract = param(contr); + + if ($contract ne "") + { + print "

Договор - $contract

\n"; + } + my ($day,$month,$year) = split(/\./, $date); + + # определяем имя таблицы с сессиями + my $table = "inet_session_log_1_".$year."".$month; + # конектимся к GLPI базе. + my $dsn = 'DBI:mysql:bgbilling:192.168.1.250'; + my $db_user_name = 'netflow'; + my $db_password = 'Cbcntvfnbpfwbz112318'; + my ($id, $password); + my $dbh = DBI->connect($dsn, $db_user_name, $db_password); + + # форматируем дату для запроса + my $date_begin = $year."-".$month."-".$day." 00:00:00"; + my $date_end = $year."-".$month."-".$day." 23:59:59"; + + # формируем SQL запрс + my $sth = $dbh->prepare(qq{select c.title, serv.login, INET_NTOA(CONV(HEX( session.ipAddress ), 16, 10)) as ip, session.sessionStart, session.sessionStop from + inet_serv_1 serv + left join $table session on serv.id = session.servid + left join contract c on c.id = serv.contractid + LEFT outer JOIN inet_serv_1 as parentServ ON serv.parentId>0 AND serv.parentId=parentServ.id + where serv.contractid <> '2' and serv.login = '$login' AND session.parentId=0 + and session.sessionStart >= '$date_begin' AND session.sessionStart <= '$date_end'}); + + # Выполняем запрос к БД + $sth->execute(); + + # если в предыдущем запорсе ничего не найден обращаемся к таблице с активными сессиями + if ($sth->rows == 0) + { + $sth = $dbh->prepare(qq{select c.title, i_c_1.username, INET_NTOA(CONV(HEX( i_c_1.ipAddress ), 16, 10)) as ip , session.sessionstart, session.sessionstop + from inet_connection_1 i_c_1 + join inet_session_1 session on session.connectionid = i_c_1.id + join inet_serv_1 i_s_1 on i_s_1.id = i_c_1.servid + join contract c on c.id = i_s_1.contractid + where i_c_1.parentid = 0 and i_c_1.username = '$login' and session.sessionStart >= '$date_begin'}); + + $sth->execute(); + } + + print "

Найдено записей - ".$sth->rows."

"; + + # получаем данные запроса форматируем и выводим на экран + while (($title, $login, $ip, $start, $stop) = $sth->fetchrow_array()) + { + if ($stop eq "") + { + $stop = $date_end; + } + #print "Договор - $title
Имя пользователя - $login
IP - $ip
Cессиия - $start - $stop
"; + print "

IP - $ip
Cессиия - $start - $stop

"; + # запускаем процедуру поиска сессий в файла RDR коллектора + ip_search($date, $start, $stop, $ip); + } + $sth->finish(); + # Отцепляемся от БД + $dbh->disconnect(); + +} diff --git a/cgi/search b/cgi/search new file mode 100755 index 0000000..7cc02a4 --- /dev/null +++ b/cgi/search @@ -0,0 +1,173 @@ +#!/usr/bin/perl + +######################################################################### +# +# CGI скрипт для поиска и визуализации данных собранных rdrcollector-ом +# +# Автор: Сергей Калинин e-mail: banzaj28@yandex.ru +# распространяется под лицензией GPL +# (c) 2015 +######################################################################### + +use CGI ':standard'; +# Вывод заголовка +print header(-type=>'text/html', -charset=>'utf-8'); +print start_html("Форма поиска сессий абонента"); +print "

Поиск сессий абонента

\n"; +print "
\n"; + +print_prompt(); +do_work(); +print_tail(); + +read_protocol(); + +print end_html; + +# вывод формы с полями +sub print_prompt { + print start_form; + print "

"; + print ""; + print ""; + print ""; + print ""; + print "
Дата (ДД.ММ.ГГГГ)".textfield('date')."
IP 1".textfield('src_ip')."
IP 2".textfield('dst_ip')."
"; + #print "sss"; + # print "

",reset; + print submit('Action','Выполнить'); + print end_form; + print "


\n"; +} + +# Проверка введённого IP адреса на корректность +sub match_ip +{ + my $ip = $_[0]; + if ($ip eq "") + { + return ""; + } + #print $ip; + if ($ip =~ m/^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$/ ) + { + return $ip; + } else { + return 0; + } +} + +# проверка корректности даты +sub match_date { + my $input = shift; + if ($input =~ m!^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$!) { + # At this point, $1 holds the year, $2 the month and $3 the day of the date entered + if ($3 == 31 and ($2 == 4 or $2 == 6 or $2 == 9 or $2 == 11)) { + return 0; # 31st of a month with 30 days + } elsif ($3 >= 30 and $2 == 2) { + return 0; # February 30th or 31st + } elsif ($2 == 2 and $3 == 29 and not ($1 % 4 == 0 and ($1 % 100 != 0 or $1 % 400 == 0))) { + return 0; # February 29th outside a leap year + } else { + return $input; # Valid date + } + } else { + return 0; # Not a date + } +} + +sub do_work { + my $key; + my $cmd; + # получаем данные введённые в форме + # и проверяем формат + my $date = match_date(param(date)); + my $dst = match_ip(param(dst_ip)); + my $src = match_ip(param(src_ip)); + # если данные введены не верно выводим сообщение + if ($dst eq 0 || $src eq 0) + { + print "Введите корректный IP адрес"; + exit; + } + if ($date eq "" || $date == 0) + { + print "Необходимо корректно ввести дату"; + exit; + } + if ($dst eq "" && $src eq "") + { + print "Необходимо ввести IP адрес"; + exit; + } + # формируем каталог для поиска в соответствии с датой + my ($day,$month,$year) = split(/\./,$date); + my $dir = "/var/srv/rdrcollector/$year/$month/$day"; + + # формируем команду поиска данных в зависимости от даты и IP адресов (1 или 2 адреса) + # определяем каталог в архиве и если он есть ищем данные в файлах этого каталога + # если такого каталога нет - поиск производится в кэше. + if (-d $dir) + { + if ($dst eq "") { + $cmd = "/usr/bin/gzip -c -d ".$dir."/*.gz | /usr/bin/grep -h ".$src; + } else { + $cmd = "/usr/bin/gzip -c -d ".$dir."/*.gz | /usr/bin/grep -h ".$src." | /bin/grep ".$dst; + } + } else { + print "Данные за $date в архиве не найдены производится поиск за последние сутки
"; + if ($dst eq "") { + $cmd = "/usr/bin/grep -h ".param(src_ip)." /var/cache/rdrcollector/*"; + } else { + $cmd = "/usr/bin/grep -h ".param(src_ip)." /var/cache/rdrcollector/* | /usr/bin/grep ".param(dst_ip); + } + } +# print $cmd; +# exit; + # выполняем команду поиска и выводим данные ввиде html-таблицы + print "

Список TCP/IP сессий c адреса ".param(src_ip)." за ".$date."

"; + print ""; + my $i = 0; + my $bgcolor; + foreach my $lines (`$cmd`) { + my $expr = $i % 2; + # чередование цвета фона строк для чётных и не чётных + if ($expr eq 0) { + $bgcolor = "#fffff"; + } else { + $bgcolor = "#c5eaff"; + } + # разбиваем строку на поля для удобства вывода. + my ($date_time, $client, $client_ip, $server_ip, $up_down, $protocol_sign) = split(/\t/, $lines); + # вывод данных + my ($user_ip, $group) = split("@", $client); + my ($t, $date) = split(" ", $date_time); + my ($d,$m,$y) = split(/\./,$date); + + $protocol = read_protocol("$protocol_sign"); + print ""; + print ""; + print "\n"; + $i++; + } + + print "
ДатаАбонентIP клиентаIP сервераТрафик вх/исхПротоколИнформация
$date_time$client$client_ip$server_ip$up_down$protocol$info_string
"; +} + +sub print_tail { + print "
© 2015, OOO \"Терион\"
"; +} + +# читаем файл с описанием протокола +sub read_protocol { + #print $_[0]; + $cmd = "/usr/bin/grep -h \'".$_[0]."\' /usr/local/etc/protocol.csv"; + my $lines = `$cmd`; + #print "$lines"; + if ($lines) { + my ($prot, $signature) = split(";", $lines); + return $prot; + } else { + return $_[0]; + } +} diff --git a/cgi/usersearch b/cgi/usersearch new file mode 100755 index 0000000..3885dd2 --- /dev/null +++ b/cgi/usersearch @@ -0,0 +1,117 @@ +#!/usr/bin/perl +############################################################################# +# +# CGI скрипт для поиска данных абонента в биллинге на основе даты и ip адреса +# +# вызывается из скрипта search с параметрами сессии: +# IP-Адрес, День, Месяц, Год, Время +# +# например: +# cgi-bin/usersearch?ip=4.8.5.1&day=01&month=03&year=2015&t=00:09:46 +# +# Автор: Сергей Калинин email: banzaj28@yandex.ru +# распространяется под лицензией GPL +# (c) 2015 +######################################################################### + + +use CGI ':standard'; +use DBI; + +# Вывод заголовка +print header(-type=>'text/html', -charset=>'utf-8'); +print start_html("Данные по абоненту"); +#print "

Поиск сессий абонента

\n"; +print "

Данные по абоненту

"; +print "
\n"; + +# выполняем процедуры описанные ниже +print_prompt(); +do_search(); +print_tail(); +print end_html; + + +################################################################### +# Описание процедур +################################################################### + +# Выводим параметры поиска на экран +sub print_prompt { + my $date = param(day); + my $month = param(month); + my $year = param(year); + my $date = join("\.", $date, $month, $year); + print "

Параметры поиска

"; + print "IP адрес - ".param(ip); + print "
Дата - ".$date; + print "
Время - ".param(t)."

"; +} + + +# поиск данных в БД биллинга +sub do_search { + + my $ip = param(ip); + my $day = param(day); + my $month = param(month); + my $year = param(year); + my $time = param(t); + # определяем имя таблицы с сессиями + my $table = "inet_session_log_1_".$year."".$month; + # форматируем дату для запроса + my $date = $year."-".$month."-".$day." ".$time; + # конектимся к GLPI базе. + my $dsn = 'DBI:mysql:bgbilling:192.168.1.250'; + my $db_user_name = 'netflow'; + my $db_password = 'Cbcntvfnbpfwbz112318'; + my ($id, $password); + my $dbh = DBI->connect($dsn, $db_user_name, $db_password); + + +# my $table = "inet_session_log_1_".$year."".$month; + + # формируем SQL запрс + + my $sth = $dbh->prepare(qq{select c.title, serv.login, INET_NTOA(CONV(HEX( session.ipAddress ), 16, 10)) as ip, session.sessionStart, session.sessionStop from inet_serv_1 serv + left join $table session on serv.id = session.servid + left join contract c on c.id = serv.contractid + where serv.contractid <> '2' and INET_NTOA(CONV(HEX( session.ipAddress ), 16, 10)) = '$ip' and session.sessionStart <= '$date' AND session.sessionStop >= '$date' + + }); +# my $sth = $dbh->prepare(qq{select c.title, serv.login, INET_NTOA(CONV(HEX( session.ipAddress ), 16, 10)) as ip, session.sessionStart, session.sessionStop from inet_serv_1 serv +# left join $table session on serv.login = session.username +# left join contract c on c.id = serv.contractid +# where serv.contractid <> '2' and INET_NTOA(CONV(HEX( session.ipAddress ), 16, 10)) = '$ip' and session.sessionStart <= '$date' AND session.sessionStop >= '$date' +# }); + # Выполняем запрос к БД + $sth->execute(); + # если в предыдущем запросе ничего не найдено ищем в таблице активных сессий + if ($sth->rows == 0) + { + $sth = $dbh->prepare(qq{select c.title, i_c_1.username, INET_NTOA(CONV(HEX( i_c_1.ipAddress ), 16, 10)) as ip , session.sessionstart, session.sessionstop + from inet_connection_1 i_c_1 + join inet_session_1 session on session.connectionid = i_c_1.id + join inet_serv_1 i_s_1 on i_s_1.id = i_c_1.servid + join contract c on c.id = i_s_1.contractid + where i_c_1.parentid = 0 and INET_NTOA(CONV(HEX( i_c_1.ipAddress ), 16, 10)) = '$ip' and session.sessionStart <= '$date'}); + + $sth->execute(); + } + + print "

Найдено записей - ".$sth->rows."

"; + # получаем данные запроса форматируем и выводим на экран + while (($title, $login, $ip, $start, $stop) = $sth->fetchrow_array()) + { + print "Договор - $title
Имя пользователя - $login
IP - $ip
Cессиия - $start - $stop
"; + } + $sth->finish(); + # Отцепляемся от БД + $dbh->disconnect(); + +} + +sub print_tail { + print "
© 2015, OOO \"Терион\"
"; +} + diff --git a/etc/protocol.csv b/etc/protocol.csv new file mode 100644 index 0000000..2d8811f --- /dev/null +++ b/etc/protocol.csv @@ -0,0 +1,499 @@ +;;;; +ACEStream;118104064;;; +Adobe Reader Cloud;252182784, 252183040;;; +AdobeCloud;252183040, 252183000;;; +Akamai;255983872;;; +Alicall Callback;101712640;;; +Alicall Control(TCP/UDP call);101712896;;; +Alicall over TCP;101712128;;; +Alicall over UDP;101711872;;; +Amazon Appstore;134873856;;; +Amazon Instant Video;NA;;; +AmazonAppDownload;134873600;;; +AmazonCloud;251920384;;; +AmazonCloud Drive;251920640;;; +AmazonCloud Player;251920896;;; +AmazonInstantVideo;221335808, 221336064;;; +Ameba.jp;253100288;;; +AndroidMarketDataFlow;134807808;;;120717312 +Angle Media;201392159;201392153;201392153; +AntsP2P;119406592;201392138;; +Apple IMessage;187695616;;; +Apple iMessage Image and Video;187695616;;; +Apple iMessage text;187695360;;; +AppleMaps;50868224;;; +ARD Mediathek;220332288;;; +ArteMediathek;220856576;;; +Audio over HTTP;201392133;50398464;; +BaiBao Download;118751232;201392152;; +BaiBao Networking;118751488;201392152;; +Baidu;134959872, 134960128, 134960384;;; +Baidu Appstore;134959616;;; +Baidu Movie;201392135;134479872;;84934912 +BBC iplayer ListenLive over RTMP;120522496;;;84935168 +BBC iplayer WatchLive over RTMP;120522240;;;84935424 +Bebo;50860032, 50860288, 50860544;;;84935680 +Behavioral RTP;201392155;201392149;201392149;84934656 +Behavioral Skype VoIP;201392156;201392150;201392150; +Behavioral SkypeIN;201392157;201392151;201392151; +Behavioral SkypeOUT;201392158;201392152;201392152; +Behavioral VoIP;201392154;201392148;201392148; +Binary over HTTP;201392134;50398976;; +BitCoin;121659648;;; +BitLord torrent client;118096384, 118096896;;; +Bitmessage;195166464;;; +BitTorrent;118095872;;; +BitTorrent Aged Flow Continuation;118096640;;; +BitTorrent File Transfer;118096384;;; +BitTorrent File Transfer DNA;118099200;;; +BitTorrent File Transfer DNA - Uni Client Request;118099456;;; +BitTorrent Networking;118096128;;; +BitTorrent Networking DNA;118098688;;; +BitTorrent Networking DNA - Uni Client Request;118098944;;; +BitTorrent Sync;118099968;;; +BR Mediathek;220397824;;; +BT Sport;220463360;;; +Bump;121647360;;; +Candy Crush Saga;270012672;;; +Carousel;NA;;; +Cbox;218760448;;; +Certificate-Based OpenVPN over TCP;167969280;;; +Certificate-Based OpenVPN over UDP;167969024;;; +ChampionsOnlineTCP;269156608;;; +ChatON;193986816;;; +ChatON;193986816;;; +CinepolisKlic;219742464, 219742720;;; +Citrix over TCP;285278720;;; +Citrix over TCP - Unidirectional Client Request;285278464;;; +clipfish.de;219676928;;; +CloudME;252055808;;; +Club Box;201392131;134414336;; +COD BlackOps TCP;269287680;;; +COD BlackOps UDP;269287936;;; +Comm;87056640, 87056896;;; +Crackle;220266752;;; +Crashplan;254804224;;; +Credentials-Based OpenVPN over TCP;167969792;;; +Credentials-Based OpenVPN over UDP;167969536;;; +CUWorld;184942592;201392134;; +CUWorld over Jabber;184943104;201392134;; +CUWorld over RTP;184942848;201392134;; +Dailymotion;219152896;;; +DailyMotionWebcamUpload;219152640;;; +Daum MyPeople Voice;87097600;;; +Daum-login;67698944;;; +Deezer;—;;; +DHCP;100794368;;; +Dial91;87073024;;; +Dijjer;119078912;201392144;; +DingoTel;84541440;;; +Direct Connect;117899264;;; +Direct Connect Client;117899520;;; +Direct Connect Servers;117899776;;; +DNS;33685505;;; +Dota2;270008576;;; +Download;134284544;;; +Download-Unidirectional Client Request;134284800;;; +DroidVPN;168046848, 168047104;;; +Dropbox signature;134742016;;; +eBay;302317824;;; +eBuddy XMS;189792512;;; +EDonkey;117833728;;; +Einy SSL;121307392;;; +Encapsulated ESP;167904000;;; +Encrypted BitTorrent;118096896;118096384;; +ESPN Streaming;221368320, 221368576, 221368832;;; +Exosee;119275520;201392160;; +Eyebeam;87077120;;; +Facebook Messenger Chat;87036160;;; +Facebook Over HTTPS;252117248;;; +Facebook Slingshot;195235840;;; +Facebook voip;87036416;;; +Facebook_SPDY;87036672, 252117760, 255984128;;; +FacebookVoip;87036416;;; +Facetime Data Flow UDP;86507776;;; +Fasttrack File Transfer non HTTP;117572096;;; +Fasttrack File Transfer over HTTP;117572352;;; +Fasttrack Networking;117571840;;; +Feidian;201392129;120127488;; +Fileguri HTTP Like over UDP;120980224;;; +Fileguri over HTTP;120979712;;; +Fileguri over HTTP - Unidirectional Client Request;120979968;;; +Filetopia File Transfer;118227456;;; +Filetopia Networking;118227200;;; +Final Fantasy;269680896, 269681152;;; +Flash YouTube (YouTube Audio);221249792;;; +Flash YouTube HQ;50404096;;; +Flash YouTube HQ Unidirectional Client Request;50404352;;; +FourSquare;252313856, 252314112;;; +FoxTube;220987648;;; +Fring;85000192;;; +Fring VOIP;85000448;;; +FTP;50462720;;; +FunshionTCP Buffering;218890240;;; +FunshionTCP Buffering - Unidirectional Client Request;218890496;;; +FunshionUDP Playing;218890752;;; +FunshionUDP Playing - Unidirectional Client Request;218891008;;; +Furthur;119209984;201392208;; +Gadu Gadu Chat-Photo-FT New;185533696;;; +Gadu Gadu Login New;185533440;;; +Gadu-FT;185532928;;; +Gadu-login-chat;185532672;;; +Gadu-Radio;185533184;;; +Generic;16777216;;; +Generic Download;16842752;—;; +Generic Non-Established TCP;16908288;—;; +Generic-IPV6;16973824;;; +Generic-IPV6-Non Established;16974592;;; +Getflix;168063232;;; +Gmail Video;85526544;;; +Gmail Video SSL;85526016;;; +Gmail Video TCP;85525504;;; +Gmail Video UDP;85525760;;; +Gmail VOIP SSL;85526528;;; +Gmail VOIP TCP;85526272;;; +Gnutella 2 Networking;117506816;;; +Gnutella File Transfer;117506560;;; +Gnutella Networking;117506304;;; +Google Hangout;85525760, 85526016, 85526528, 85526544, 185075456;;; +Google Maps;190844928;;; +Google Plus;256200704;;; +Google search;256180480, 256180736;;; +Google Talk;201392130;185073664;; +Google Talk SSL;185075968;;; +Google Talk Voice RTP;185075712;;; +Google Voice over HTTPS;85524480;;; +Google_SPDY;251724800, 134808576, 256180992, 221315072, 50373120, 50373376, 256201216, 256201472, 67568384, 251986176;;; +GoogleDrive;251985920;;; +GoogleEarth;251723776;201392133;; +GoogleEarthSSL;251724544;;; +GoogleGoggles;50409472;;; +GoogleMaps;190845184;;; +GooglePlayMovies;—;;; +GroupMe;195035648;;; +Guruguru;119668736;201392129;; +H323;84344832;;; +HBO Streaming;221364224, 221364480, 221364736;;; +Hike;195100928;;; +Hike Message Counting;195101184, 195101440, 195101696, 195101952;;; +Hike Messengerq;195100928;;; +Hopster;235012096;201392136;; +Hotline File Transfer;117768704;;; +Hotline Networking;117768448;;; +Hotline over HTTP;117769216;;; +Hotline Tracker;117768960;;; +HTTP;50397184;;; +HTTP POST;50438144;;; +HTTP-Tunnel;234946560;201392153;; +icloud;251854848;;; +ICQ File Transfer;184877568;201392132;; +ICQ Networking;184877312;201392132;; +ICQ PTT;184877824;201392132;; +Icq Voice;184879616;;; +ICQ VoIP;184878080;201392141;; +iFone Platinum;87068928, 87069184;;; +iheart Radio;256,212,992,256,213,000,000,000,000;;; +IMAP;67239936;;; +iMessage;187695872;;; +iMessage count;NA;;; +Imgur;252903680;;; +Instagram Login or Share;121635072;;; +Instagram Video;121635328, 121635584;;; +Internet Video Youtube RTMP;218365952;;; +iOS OTA Update;—;;; +Iperf;285802752, 285803008;;; +IPSEC;167903488;;; +IPSec over tcp;167903744;;; +iQIYI TV;221319424, 221319680, 221319936, 221320192, 221320448, 221320704, 221320960;;; +iQIYI- TV Box App1ication;221319424, 221319680, 221319936;;; +IRC;184614912;;; +isakmp;167903488;;; +iTube;221184256;;; +iTunes;134283520;;; +iTunes Download;134283776;;; +iTunes Radio;134285056;;; +iTunes Radio;134285312;;; +ITV Player;221356288, 221356544, 221356800, 221357056;;; +Jabber;185008128;201392135;; +JabberSSL;185008640;;; +JaJah YahooPhoneOut UDP;84608768;;; +Joost;201392138;201392132;120324096; +Joyn;87081216, 87081472;;; +Kakao Call;88081152;;; +Kakao Chat;88080640;;; +Kakao Ring;88080896;;; +Kakao Talk;88081408, 88081664;;; +Kakao Talk Message Count;88081920, 88082176, 88082432;;; +Keek;256049408;;; +Knight Online;269943040;;; +Kontiki;119144448;201392224;; +KSVOD4TV;NA;;; +Kuro;119603200;201392128;; +LapLink over SSL;285344512;;; +LapLink over TCP;285344000;;; +LapLink over TCP - Unidirectional Client Request;285344256;;; +League of Legends;269877504, 269877760;;; +LeTV;221331712, 221331968;;; +LINE;87032064, 87032570, 356;;; +Line Camera;87032832;;; +Line File Transfer;87033088;;; +Line Message Count;87033344, 87033600, 87033856;;; +LINE SIP;2265129760;;; +LINE SSL;2265129060;;; +Line Voice;87032576;;; +Line Voice;87032576;;; +LineVoip;87032576;;; +LinkedIn;252576000;;; +Location Free;201392137;201392130;120258560; +LogMeInIgnition;285474816;;; +Lottofile over TCP;121176320;;; +Lottofile over TCP - Unidirectional Client Request;121176576;;; +Lovefilm;50405376;;; +LoveFilm;50405376;;; +Mac;134947072;;; +MacOsUpdate;134947328;;; +Mailru;87060992, 87061504, 87060736,87061248;;; +Mailru;87060992, 87060736, 87061248;;; +Manolito File Transfer;118030848;;; +Manolito Networking;118030592;;; +Maple Story Control;268501760;;; +Maple Story Control - Unidirectional Server Response;268502016;;; +Maple Story Data;268501248;;; +Maple Story Data - Unidirectional Server Response;268501504;;; +MediaFire;252641280, 252641536;;; +MediaHint;168067328;;; +Megacloud;253755648;;; +MessageMe;195043600;;; +MGCP;84279296;;; +Microsoft OneDrive;252051712;;; +Mobile MMS;50724864;—;; +Monkey3 over TCP;121241856;;; +Monkey3 over TCP - Unidirectional Client Request;121242112;;; +Mozy;50864384;;; +MS MMS;50659328;;; +MS Push Mail;201392139;201392134;67502080; +Mumble Chat;86573312;;; +Mumble Voice;86573568;;; +Mute;118423552;;; +My_Com-MyMail;67830272, 67830016;;; +My-video.de;220734208;;; +mychat;195232000,195232256, 87061504;;; +Myvideo.de;220733696, 220733952;;; +Napster;134348800;;; +NateonTalkcall;87040000;;; +NateonTalkFileTransfer;87040512;;; +NateonTalkSSL;87040256;;; +NBColympics;221118720, 256114688;;; +NDRMediathek;220790784;;; +Neonet Download;118620416;;; +Netflix;218759168, 218759680,218759936, 2187560192;;; +Nimbuzz;186647296;;; +Nimbuzz over Jabber;186646784;;; +Nimbuzz over Jabber-Unidirectional Client Request;186647040;;; +Nimbuzz over RTP;186647296;;;101122048 +NNTP;67174400;;; +Nodezilla;118489088;;; +NowTV;219611648;;; +NTP;100925440;201392150;; +NymGo;87064832;;; +Onlive;269615360, 269615616;;; +ooVoo IM;185468416;;; +ooVoo Voice SSL;185468160;;; +OpenDrive;255918336;;; +Opera Mobile signature;50413568;;; +Origin Chat;269484800;;; +Origin Login;269484288;;; +Pandora Audio, Pandora_SSL, Pandora;251789568, 251789824, 251789312;;; +PeerEnabler;119341056;201392176;; +Play Station4;270074112;;; +Poco; ;201392133;118882304; +POCO Download;118882560;201392146;; +POCO Networking;118882304;201392146;; +POP3;67305472;;; +PPLive-P2P;118947840;201392147;; +PPStream Download;118816768;201392145;; +PPStream Networking;118817024;201392145;; +PPStv (PPStream);118821120;;; +Pptp;201392161;201392155;201392155; +Prosieben;220922112, 220922368;;; +Proxpn VPN;168055040;;; +Proxy-based OpenVPN;167970560;;; +PSK-Based OpenVPN over TCP;167970048;;; +PSK-Based OpenVPN over UDP;167970304;;; +PTT Winphoria SIP;84213760;;; +PutIo;252248320;;; +Qik;87052544, 87052800, 87053056;;; +QQ;184745984, 184746240, 184747008,184747776;;; +QQ Networking;184746240;201392151;; +QQ_Android;184748544, 184748800;;; +QQ-IM;184745984;201392151;; +Quake3 Gaming Server;268566528;;; +Qvod;219087104, 219087872, 219088128;;; +Qvod over HTTP;219087872;;; +Qvod over http split initiator;219087616;;; +Qvod over TCP;219087104;;; +Qvod over UDP;219087360;;; +Radius Access;100729088;—;; +Radius Accounting;100729344;—;; +RapidShare;252379392;;; +Rdio;256209152, 256208896;;; +Remote Desktop Connection;286261504;;; +Rodi;119537664;201392140;; +RTL Now;220201216;;; +RTMPE;218170112;;; +RTP;84082688;;; +RTSP;50593792;;;120782848 +saavn;190841088;;; +SAT1;220664064;;; +Satellite Direct;219545856;;; +SCTP Protocol;17039360;;; +Share;118292480;;; +Shoutcast;121643264;;; +SilkRoad (Game);269746432;;; +SinaWeibo;220667904;;; +SIP;84148224;;; +Skinny;84475904;;; +SkyDrive;252051712;;; +SkyDriveNetDnld;252051968;;; +Skype;84412160;;; +Skype;84410368;;; +Skype-VoIP-Mobile-To-PC;84412160;;; +SkyStore UK;221360384, 221360640;;; +Slacker Radio;256204800, 256205056;;; +Sling;50855936;201392139;; +SMTP;67371008;;; +Snapchat;195039744;;; +Sohu TV;221339904, 221340160;;; +Songsari over HTTP;121110784;;; +Songsari over HTTP - Unidirectional Client Request;121111040;;; +Songsari over TCP;121111296;;; +Songsari over TCP - Unidirectional Server Response;121111552;;; +Songsari over UDP;121111808;;; +SopCast;201392160;201392154;201392154; +Soribada;119799808;201392130;; +Soulseek File Transfer;118358528;;; +Soulseek Networking;118358272;;; +Sound Cloud;50417920, 50418170;;; +Soundcloud_HTTPS;50417920;;; +SPDY;167838208;;; +SPDY;167838208;;; +SpeedTest;50872576, 50872832, 55067392, 55067648;;; +SpeedyShare-Download;1346392352;;; +SpiderOak Hive;252772608;;; +Spotify;121373952, 121374208, 121374464;;; +Spotify Music P2P;121373440;;; +Spotify Music P2P-Unidirectional Client Request;121373696;;;120848640 +Spotify Networking;121372928;;;120848896 +Spotify Networking-Unidirectional Client Request;121373184;;; +SSDP-P2P;100859904;201392144;; +SSH over TCP;168034560;;; +SSL;167837696;;; +SSL Aged Flow Continuation;167837952;;; +Starcraft2;268894208, 268894464, 268894720;;; +Steam Downlaod;268636160;;; +Steam Friends;268640256;;; +StreetFighterIV;268697600;;; +StromMedia;121655552, 121655808;;; +STUN;100990976;201392142;; +Supercell-Clash of Clans;270020608, 270020864;;; +Tango;85983232, 85983488, 85983744, 85984000;;; +Tango Message count;85985024, 85984256, 85984512, 85984768;;; +TeamForstress2 TCP;269353216;;; +TeamFortress2 UDP;269353472;;; +TeamViewer;285409536, 285409792;;; +TELNET SPLIT INITIATE;101319242;;; +TELNET SPLIT INITIATOR;101319168;;; +Temp Gmail Video SSL;85525248;;; +Temp Gmail Video TCP;85524992;;; +Tencent App Gem;134955264, 134955520;;; +Tencent Weibo;285806848;;; +TencentWeibo;285806592;;; +Teredo Generic;16909056;;; +TFTP;50528256;;; +Thunder Networking;119013376;201392149;; +Titan-Fall;270016768;;; +Tivibu;220659712;;; +TomatoPang over TCP;121045248;;; +TomatoPang over TCP - Unidirectional Client Request;121045504;;; +Tor;120848384, 120849152;;; +Tor;201392162;201392156;; +Tor Over HTTP;—;—;—; +Tor Over HTTP—Unidirectional Client Request;—;—;—; +TotalMovie;219480320, 219480576;;; +Truphone over SIP;85458944;;; +TTNET Muzik;252969216;;; +Tudou;221053184, 221053440, 221053696, 221053952;;; +TuneIn Radio;220594432;;; +TunnelBear;168042752, 168043008, 168043264;;; +Twitch tv;256184320,256184576,221323520, 256188416, 221327616;;; +Twitter;252510464;;; +Twitter_SPDY;252510720;;; +Ubisoft Uplay;269811968;;; +UbuntuoneFT;191889920;;; +UbuntuoneLogin;191889664;;; +UbuntuoneStreaming;191890176;;; +UC Data;184811520;201392148;; +UC Networking;184811776;201392148;; +Ultrasurf;121651456;;; +Ultrasurf;121651712, 121651968, 121652224;;; +UNBLOCKUS;168058880;;; +V-share;119734272;201392131;; +VGTV and VGDirekte;25619512, 221344000, 256192768, 221348096, 256196864;;; +Viber;85918464;;; +Viber;85918720;;; +Viber;85918976;;; +Viber;85919232, 85923328, 85919488, 85923584, 85919744;;; +Viber ControlFlow Over TCP;85917952;;; +Viber ControlFlow Over TCP - Unidirectional Client Request;85918208;;; +Viber DataFlow Over UDP;85918464;;; +Viber Message;85920000, 85921792, 85922048;;; +Viddy;219349504;;; +Video over HTTP;201392132;50397952;; +Vimeo;219414784;;; +Vk;252707072;;; +Vopium_Call;89260032;;; +Vopium_WebIM_Call;89194496;;; +VopiumSSL;89128960;;; +Wandoujia;134951680, 134951936, 134952192;;; +Wandoujia Appstore;134951424;;; +Warcraft3_Login;269222144;;; +Warcraft3_Tcp;269222400;;; +Warez;118685696;;; +Warez Download;118685952;;; +Warez Networking;118686208;;; +Waste;118554624;;; +Watchever;221352192;;; +Watchitoo;219349248;;; +WazeGPS;50434304;;; +WeChat;87048448, 87048704;;; +Wechat Message Count;87048960, 87049216, 87049472;;; +Wetransfer;252838144;;; +WhatsApp;185598208, 185598720;;; +WhatsApp Message Count;185598720;;; +Windows Live Messenger;201392140;201392131;185139200; +Windows Store;134942976, 134943232;;; +Windows Store AppDownload;134943488, 134943744;;; +Windows Update;101187840;;; +Windows Update;101187840, 101188096;;; +WINMX;117637120;;; +Winny 1;117702912;;; +Winny 2;117703168;;; +Wuakitv;220598272;;; +Xbox One;268763392, 268763648;;; +Xbox_Video/Browsing;220672256, 220672512, 220672768, 220673024;;; +Xunlei Kankan;121667840, 121668096;;; +Yahoo General Login;184683264;;; +Yahoo Messenger;184680448;;; +Yahoo Messenger VoIP_JaJah Call Setup;84608512;;; +Yahoo Screen;220528896;;; +Yahoo VoIP;84606976;—;; +Yahoo VoIP UDP;84609536;;; +Yandex.disk;255852800, 255853056;;; +Youtube;50404096,5040435;;; +YouTube HD;50403072;;; +YouTube HTTPS;221249536, 50372608, 50372864;;; +YouTube Normal;50403584;;; +Zattoo;201392136;201392129;120193024; +ZDF Mediathek;253034752;;; +Zenmate;168050944;;; +ZONA;121663744;;; diff --git a/etc/rdrcollector.conf b/etc/rdrcollector.conf new file mode 100644 index 0000000..3897160 --- /dev/null +++ b/etc/rdrcollector.conf @@ -0,0 +1,4 @@ +source-ip=192.168.1.243 +source-port=10000 +out-dir=/var/cache/rdrcollector +archive-dir=/var/srv/rdrcollector \ No newline at end of file diff --git a/rdrarchiver.pl b/rdrarchiver.pl new file mode 100755 index 0000000..a016fe5 --- /dev/null +++ b/rdrarchiver.pl @@ -0,0 +1,76 @@ +#!/usr/bin/perl + +######################################################### +# Скрипт для архивирования файлов созданных rdrcollector +# +# вызывается командой: +# rdrarchiver.pl /usr/local/etc/rdrcollector.conf +# +# Запускается по крону с требуемой периодичностью (сутки) +# +# Автор: Сергей Калинин e-mail: banzaj28@yandex.ru +# распространяется под лицензией GPL +# (c) 2015 +######################################################### + +use IO::File; +use Getopt::Long; +use File::Path qw(make_path); + +my $opts_pair = IO::File->new("$ARGV[0]") or +die "Can not open: $opts{'conf'} $!\n"; + +while (<$opts_pair>) +{ + ($key, $value) = split('='); + $value =~ s/^\s+|\s+$//g; + $opts{$key} = $value; + #print $opts{'source-port'}; +} +$opts_pair->close(); + +# определяем текущую системную дату +my $date = ` /bin/date "+%Y %m %d %H %M %S"`; +my ($cur_year,$cur_month,$cur_day,$cur_hour,$cur_min,$cur_sec) = split('\s',$date); + +#print "$cur_year,$cur_month,$cur_day,$cur_hour,$cur_min,$cur_sec"; + + +# ищем файлы старше 1 дня и архивируем +#$arch = '/bin/find '.$opts{'out-dir'}.' -type f -mtime +1 -exec gzip {} \; -print > rdrcollector.log'; +#print "$arch\n"; +#my $result = `$arch`; + +# Получаем список заархивированных файлов +opendir(DIR, "$opts{'out-dir'}"); +my @files = grep('*',readdir(DIR)); + +#print files; +#my @files = grep(/\.gz/,readdir(DIR)); +closedir(DIR); + +# создаем каталог для соответствующих сжатых файлов +foreach my $file (@files) +{ + #print $file; + # в зависимости от имени файла определяем и создаём каталог куда его перемещать + my $year = substr($file,0,4); + my $month = substr($file,4,2); + my $day = substr($file,6,2); + + #print "$year $month $day - $cur_day\n"; + + if ($day ne $cur_day) { + $dir = $opts{'archive-dir'}."/".$year."/".$month."/".$day; + make_path $dir; + my $cmd = '/usr/bin/gzip '.$opts{'out-dir'}.'/'.$file; + #print $cmd."\n"; + my $result = `$cmd`; + #print $result; + # Перемещаем файл в соответствующий каталог + $move = '/bin/mv '.$opts{'out-dir'}.'/'.$file.'.gz '. $dir.' > rdrcollector.log'; + print "$move\n"; + my $mvResult = `$move`; + } + +} diff --git a/rdrcolld b/rdrcolld new file mode 100755 index 0000000..d284110 --- /dev/null +++ b/rdrcolld @@ -0,0 +1,27 @@ +#!/usr/bin/perl +################################################### +# скрипт для запуска rdrcollector-а демоном +# +# Автор: Сергей Калинин e-mail: banzaj28@yandex.ru +# распространяется под лицензией GPL +# (c) 2015 +################################################### +use warnings; +use strict; +use Daemon::Control; +use Getopt::Long; + +GetOptions(\ my %opt, 'conf=s', 'source-ip=s', 'source-port=s', 'out-dir=s', 'help', 'verbose'); + + +exit Daemon::Control->new( + name => "RDR collector daemon", + path => '/var/cache/rdrcollector', + + program => '/usr/local/bin/rdrcollector.pl --conf /usr/local/etc/rdrcollector.conf', + #program_args => [ '--city', $OPT{city} ], + #program_args => ['--source-ip', $opt{'source-ip'}, '--source-port', $opt{'source-port'}, '--out-dir', $opt{'out-dir'}], + + pid_file => '/var/run/rdrcollector.pid', +)->run; +#->run_command( 'start' ); diff --git a/rdrcollector.pl b/rdrcollector.pl new file mode 100755 index 0000000..2ab8db3 --- /dev/null +++ b/rdrcollector.pl @@ -0,0 +1,219 @@ +#!/usr/bin/perl + +######################################################## +# Сервис сбора RDR потока с CISCO SCE +# Принимает RDR-данные и формирует текстовые файлы +# +# Автор: Сергей Калинин e-mail: banzaj28@yandex.ru +# распространяется под лицензией GPL +# (c) 2015 +######################################################### + +use strict; +use RDR::Collector; +use IO::File; +use Switch; +use Getopt::Long; + +use vars qw(%opts); + +my $help = 0; +my $verbose = 0; +my $conf_file; +my $key; +my $value; + +GetOptions(\%opts, 'conf=s', 'source-ip=s', 'source-port=s', 'out-dir=s', 'help', 'verbose'); + +if (defined($opts{'help'})) +{ + print STDERR <new("$opts{'conf'}") or +die "Can not open: $opts{'conf'} $!\n"; +while (<$opts_pair>) +{ + ($key, $value) = split('='); + $value =~ s/^\s+|\s+$//g; + $opts{$key} = $value; + #print $opts{'source-port'}; +} +$opts_pair->close(); + +print "ServerIP = $opts{'source-ip'} \nServerPort = $opts{'source-port'}\nOut dir = $opts{'out-dir'}\n"; + +my $rdr_client = new RDR::Collector( + [ + ServerIP => $opts{'source-ip'}, + ServerPort => $opts{'source-port'}, + Timeout => 2, + DataHandler => \&display_data + ] + ); + + # Setup the local RDR listener + my $status = $rdr_client->connect(); + + # If we could not listen tell us why. + if ( !$status ) + { + print "Status was '".$rdr_client->return_status()."'\n"; + print "Error was '".$rdr_client->return_error()."'\n"; + exit(0); + } + # Now just wait for RDR data. + $rdr_client->check_data_available(); + exit(0); + + # This routine is called from DataHandler when the module + # instance is initialised. + # 4 parameters are returned, internal ref, remote IP, remote Port and + # the raw data + +sub display_data +{ + my ( $glob ) = shift; + my ( $remote_ip ) = shift; + my ( $remote_port ) = shift; + my ( $data ) = shift; + my $attribute_line; + my $data_line; + my @keys = keys %{$data}; + # каталог для работы + my $workDir = "$opts{'out-dir'}"; + #определяем текущую даты и время + my $date = ` /bin/date "+%Y %m %d %H %M %S"`; + my ($year,$month,$day,$hour,$min,$sec) = split('\s',$date); + + #rint "$year,$month,$day,$hour,$min,$sec"; + + my $outString; + my $date_time; + my $subscriber_id; + my $client_ip; + my $client_port; + my $server_ip; + my $server_port; + my $up; + my $down; + my $info_string; + my $protocol_signature; + my $fileName; + # имя выходного файла, вида /home/svk/tmp/2015/2/26/201502260929 +# my $fileName = $workDir."/".$year."".$month."".$day."".$hour."".$min; + # выводим название файла в консоль +# if ( $opts{'verbose'} ) { print "print $fileName;\n"; } + # выдёргиваем нужные нам поля и преобразуем по необходимости + foreach my $key_name ( @keys ) + { + #print $key_name." - ".${$data}{$key_name}; + + $outString = ""; + # преобразуем время из unixtime в нормальный вид + if ($key_name eq "report_time" || $key_name eq "end_time") + { + #if (${$data}{$key_name} eq "") {return; } + #print ${$data}{$key_name}."\n"; + my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime( ${$data}{$key_name} ); + $year += 1900; + $mon += 1; + if ($mon < 10) + { + $mon = "0".$mon; + } + if ($mday < 10) + { + $mday = "0".$mday; + } + if ($hour < 10) + { + $hour = "0".$hour; + } + if ($min < 10) + { + $min = "0".$min; + } + if ($sec < 10) + { + $sec = "0".$sec + } + $date_time = "$hour:$min:$sec $mday.$mon.$year"; + # имя выходного файла, вида /home/svk/tmp/2015/2/26/201502260929 + $fileName = $workDir."/".$year."".$mon."".$mday."".$hour."".$min; + if ( $opts{'verbose'} ) { print "print $fileName;\n"; } + } else { + if ( $opts{'verbose'} ) { print "$key_name - ${$data}{$key_name}\n"; } + } + switch ($key_name) { + case "flavour_id" { + } + case "protocol_signature" { + $protocol_signature = ${$data}{$key_name}; + } + case "subscriber_id" { + $subscriber_id = ${$data}{$key_name}; + } + case "client_ip" { + $client_ip = ${$data}{$key_name}; + } + case "client_port" { + $client_port = ${$data}{$key_name}; + } + case "server_ip" { + $server_ip = ${$data}{$key_name}; + } + case "server_port" { + $server_port = ${$data}{$key_name}; + } + case "info_string" { + $info_string = ${$data}{$key_name}; + } + case "session_downstream_volume" { + $down = ${$data}{$key_name}; + } + case "session_upstream_volume" { + $up = ${$data}{$key_name}; + } + + } + } + # создаём файл и открываем его на запись + if ($fileName ne "") { + #print "$fileName\n"; + open(fileOut,">> $fileName") or die "cannot open $fileName: $!"; + + + # формируем результат и выводим в файл и в консоль если указана опция --verbose + $outString = $date_time."\t".$subscriber_id."\t".$client_ip.":".$client_port."\t".$server_ip.":".$server_port."\t".$up."/".$down."\t".$protocol_signature."\t".$info_string; + print fileOut $outString."\n"; + if ( $opts{'verbose'} ) { print "\n"; } + close fileOut; + } +} + +