fetch_new_arp.pl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use English;
  7. use base;
  8. use FindBin '$Bin';
  9. use lib "$Bin/";
  10. use strict;
  11. use DBI;
  12. use Time::Local;
  13. use Net::Patricia;
  14. use Data::Dumper;
  15. use Date::Parse;
  16. use Socket;
  17. use Rstat::config;
  18. use Rstat::main;
  19. use Rstat::net_utils;
  20. use Rstat::snmp;
  21. use Rstat::mysql;
  22. use NetAddr::IP;
  23. use Fcntl qw(:flock);
  24. use Parallel::ForkManager;
  25. open(SELF,"<",$0) or die "Cannot open $0 - $!";
  26. flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
  27. setpriority(0,0,19);
  28. my %mac_history;
  29. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  30. $month += 1;
  31. $year += 1900;
  32. my $fork_count = $cpu_count*5;
  33. #disable fork for debug
  34. #if ($debug) { $fork_count = 0; }
  35. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  36. my $now_day=sprintf "%04d-%02d-%02d",$year,$month,$day;
  37. if (!$arp_discovery) {
  38. db_log_verbose($dbh,'Arp discovery disabled by config');
  39. } else {
  40. db_log_verbose($dbh,'Arp discovery started.');
  41. if ($ARGV[0]) {
  42. db_log_verbose($dbh,'Active check started!');
  43. my $subnets=get_subnets_ref($dbh);
  44. my @fping_cmd=();
  45. foreach my $net (keys %$subnets) {
  46. next if (!$net);
  47. next if (!$subnets->{$net}{discovery});
  48. my $run_cmd="$fping -g $subnets->{$net}{subnet} -B1.0 -c 1 >/dev/null 2>&1";
  49. db_log_debug($dbh,"Checked network $subnets->{$net}{subnet}") if ($debug);
  50. push(@fping_cmd,$run_cmd);
  51. }
  52. $parallel_process_count = $cpu_count*2;
  53. run_in_parallel(@fping_cmd);
  54. }
  55. my @router_ref = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND device_type=2 AND discovery=1 AND snmp_version>0 ORDER by ip" );
  56. my @arp_array=();
  57. my $pm_arp = Parallel::ForkManager->new($fork_count);
  58. # data structure retrieval and handling
  59. $pm_arp -> run_on_finish (
  60. sub {
  61. my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_;
  62. if (defined($data_structure_reference)) {
  63. # children are not forced to send anything
  64. my $result = ${$data_structure_reference};
  65. push(@arp_array,$result);
  66. }
  67. }
  68. );
  69. DATA_LOOP:
  70. foreach my $router (@router_ref) {
  71. my $router_ip=$router->{ip};
  72. my $snmp_version=$router->{snmp_version};
  73. my $community=$router->{community};
  74. if (!HostIsLive($router_ip)) { log_info("Host id: $router->{id} name: $router->{device_name} ip: $router_ip is down! Skip."); next; }
  75. $pm_arp->start() and next DATA_LOOP;
  76. my $arp_table=get_arp_table($router_ip,$community,$snmp_version);
  77. $pm_arp->finish(0, \$arp_table);
  78. }
  79. $pm_arp->wait_all_children;
  80. ########################### end fork's #########################
  81. $dbh=init_db();
  82. #get userid list
  83. my @authlist_ref = get_records_sql($dbh,"SELECT * FROM User_auth WHERE deleted=0 ORDER by ip_int" );
  84. my $users = new Net::Patricia;
  85. my %ip_list;
  86. foreach my $row (@authlist_ref) {
  87. $users->add_string($row->{ip},$row->{id});
  88. $ip_list{$row->{id}}->{id}=$row->{id};
  89. $ip_list{$row->{id}}->{ip}=$row->{ip};
  90. $ip_list{$row->{id}}->{mac}=mac_splitted($row->{mac}) || '';
  91. }
  92. foreach my $arp_table (@arp_array) {
  93. foreach my $ip (keys %$arp_table) {
  94. next if (!$arp_table->{$ip});
  95. my $mac=trim($arp_table->{$ip});
  96. $mac=mac_splitted($mac);
  97. next if (!$mac);
  98. next if ($mac=~/ff:ff:ff:ff:ff:ff/i);
  99. next if ($mac!~/(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/);
  100. my $simple_mac=mac_simplify($mac);
  101. $ip=trim($ip);
  102. my $ip_aton=StrToIp($ip);
  103. $mac_history{$simple_mac}{changed}=0;
  104. $mac_history{$simple_mac}{ip}=$ip;
  105. $mac_history{$simple_mac}{auth_id}=0;
  106. next if (!$office_networks->match_string($ip));
  107. db_log_debug($dbh,"Analyze ip: $ip mac: $mac") if ($debug);
  108. my $auth_id = $users->match_string($ip);
  109. my $cur_auth_id=resurrection_auth($dbh,$ip,$mac,'arp');
  110. $mac_history{$simple_mac}{auth_id}=$cur_auth_id;
  111. if ($auth_id ne $cur_auth_id) { $mac_history{$simple_mac}{changed}=1; }
  112. }
  113. }
  114. db_log_verbose($dbh,'Arp discovery stopped.');
  115. }
  116. #MAC Discavery
  117. if (!$mac_discovery) {
  118. db_log_verbose($dbh,'Mac discovery disabled by config');
  119. } else {
  120. sleep(1);
  121. db_log_verbose($dbh,'Mac discovery started.');
  122. my %connections=();
  123. my @connections_list=get_records_sql($dbh,"SELECT * FROM connections ORDER BY auth_id");
  124. foreach my $connection (@connections_list) {
  125. next if (!$connection);
  126. $connections{$connection->{auth_id}}{port}=$connection->{port_id};
  127. $connections{$connection->{auth_id}}{id}=$connection->{id};
  128. }
  129. my $auth_filter='';
  130. if ($arp_discovery) { $auth_filter=" AND last_found >='".$now_day."' "; }
  131. my $auth_sql="SELECT id,mac FROM User_auth WHERE mac IS NOT NULL AND deleted=0 $auth_filter ORDER BY id ASC";
  132. my @auth_list=get_records_sql($dbh,$auth_sql);
  133. my %auth_table;
  134. foreach my $auth (@auth_list) {
  135. next if (!$auth);
  136. my $auth_mac=mac_simplify($auth->{mac});
  137. $auth_table{oper_table}{$auth_mac}=$auth->{id};
  138. }
  139. $auth_sql="SELECT id,mac FROM User_auth WHERE mac IS NOT NULL AND deleted=0 ORDER BY id ASC";
  140. my @auth_full_list=get_records_sql($dbh,$auth_sql);
  141. foreach my $auth (@auth_full_list) {
  142. next if (!$auth);
  143. my $auth_mac=mac_simplify($auth->{mac});
  144. $auth_table{full_table}{$auth_mac}=$auth->{id};
  145. }
  146. my @unknown_list=get_records_sql($dbh,"SELECT id,mac,port_id,device_id FROM Unknown_mac WHERE mac !='' ORDER BY mac");
  147. my %unknown_table;
  148. foreach my $unknown (@unknown_list) {
  149. next if (!$unknown);
  150. my $unknown_mac=mac_simplify($unknown->{mac});
  151. $unknown_table{$unknown_mac}{unknown_id}=$unknown->{id};
  152. $unknown_table{$unknown_mac}{port_id}=$unknown->{port_id};
  153. $unknown_table{$unknown_mac}{device_id}=$unknown->{device_id};
  154. }
  155. my @device_list = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND discovery=1 AND snmp_version>0" );
  156. my @fdb_array=();
  157. my $pm_fdb = Parallel::ForkManager->new($fork_count);
  158. # data structure retrieval and handling
  159. $pm_fdb -> run_on_finish (
  160. sub {
  161. my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_;
  162. if (defined($data_structure_reference)) { # children are not forced to send anything
  163. my $result = ${$data_structure_reference}; # child passed a string reference
  164. push(@fdb_array,$result);
  165. }
  166. }
  167. );
  168. FDB_LOOP:
  169. foreach my $device (@device_list) {
  170. my $int_list = get_snmp_ifindex($device->{ip},$device->{community},$device->{snmp_version});
  171. if (!$int_list) { log_info("Host id: $device->{id} name: $device->{device_name} ip: $device->{ip} is down! Skip."); next; }
  172. $pm_fdb->start() and next FDB_LOOP;
  173. my $fdb=get_fdb_table($device->{ip},$device->{community},$device->{snmp_version});
  174. my $vlans = get_switch_vlans($device->{ip},$device->{community},$device->{snmp_version});
  175. my $result;
  176. $result->{id}=$device->{id};
  177. $result->{fdb} = $fdb;
  178. $result->{vlans} = $vlans;
  179. $pm_fdb->finish(0, \$result);
  180. }
  181. $pm_fdb->wait_all_children;
  182. my %fdb_ref;
  183. foreach my $fdb_table (@fdb_array){
  184. next if (!$fdb_table);
  185. $fdb_ref{$fdb_table->{id}}{fdb}=$fdb_table->{fdb};
  186. $fdb_ref{$fdb_table->{id}}{vlans}=$fdb_table->{vlans};
  187. }
  188. ################################ end fork's ##############################
  189. $dbh=init_db();
  190. foreach my $device (@device_list) {
  191. my %port_snmp_index=();
  192. my %port_index=();
  193. my %mac_port_count=();
  194. my %mac_address_table=();
  195. my %port_links=();
  196. my $dev_id = $device->{id};
  197. my $dev_name = $device->{device_name};
  198. my $fdb=$fdb_ref{$dev_id}{fdb};
  199. my $vlans=$fdb_ref{$dev_id}{vlans};
  200. next if (!$fdb);
  201. my @device_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=$dev_id");
  202. foreach my $port_data (@device_ports) {
  203. my $vlan = $port_data->{vlan};
  204. if (!$vlan) { $vlan=1; }
  205. my $fdb_port_index=$port_data->{port};
  206. my $port_id = $port_data->{id};
  207. if (!$port_data->{snmp_index}) { $port_data->{snmp_index} = $port_data->{port}; }
  208. if ($device->{fdb_snmp_index}) { $fdb_port_index=$port_data->{snmp_index}; }
  209. my $current_vlan = $vlans->{$fdb_port_index};
  210. if (!$current_vlan) { $current_vlan=1; }
  211. if ($current_vlan != $vlan) {
  212. my $dev_ports;
  213. $dev_ports->{vlan}=$current_vlan;
  214. update_record($dbh,'device_ports',$dev_ports,"id=$port_id");
  215. db_log_verbose($dbh,"Vlan changed at device $dev_name [$port_data->{port}] id: $port_id old: $vlan current: $current_vlan");
  216. }
  217. next if ($port_data->{skip});
  218. #snmp-индекс порта = номеру порта
  219. $port_snmp_index{$port_data->{snmp_index}}=$port_data->{port};
  220. # номер порта = id записи порта в таблице
  221. $port_index{$port_data->{port}}=$port_data->{id};
  222. # номер порта = id записи порта аплинка/даунлинка свича
  223. $port_links{$port_data->{port}}=$port_data->{target_port_id};
  224. $mac_port_count{$port_data->{port}}=0;
  225. }
  226. my $sw_mac;
  227. if ($device->{vendor_id} eq '9') {
  228. #get device mac
  229. my $sw_auth = get_record_sql($dbh,"SELECT mac FROM User_auth WHERE deleted=0 and ip='".$device->{ip}."'");
  230. $sw_mac = mac_simplify($sw_auth->{mac});
  231. $sw_mac =~s/.{2}$//s;
  232. }
  233. foreach my $mac (keys %$fdb) {
  234. #port from fdb table
  235. my $port = $fdb->{$mac};
  236. next if (!$port);
  237. #real port number
  238. if ($device->{fdb_snmp_index}) {
  239. #если mac-таблица привязана к snmp-индексам портов, номер порта ставим в snmp-индекс порта
  240. if (!exists $port_snmp_index{$port}) { next; }
  241. $port=$port_snmp_index{$port};
  242. }
  243. if (!exists $port_index{$port}) { next; }
  244. #mikrotik patch - skip mikrotik device mac
  245. if ($sw_mac and $mac=~/^$sw_mac/i) { next; }
  246. $mac_port_count{$port}++;
  247. #мак = номер порта
  248. $mac_address_table{$mac}=$port;
  249. }
  250. # обновляем число маков на порту
  251. foreach my $port (keys %mac_port_count) {
  252. if (!$port) { next; }
  253. if (!exists $port_index{$port}) { next; }
  254. #skip uplink|downlink
  255. if ($port_links{$port}>0) { next; }
  256. my $dev_ports;
  257. $dev_ports->{last_mac_count}=$mac_port_count{$port};
  258. update_record($dbh,'device_ports',$dev_ports,"device_id=$dev_id and port=$port");
  259. }
  260. foreach my $mac (keys %mac_address_table) {
  261. my $port = $mac_address_table{$mac};
  262. if (!$port) { next; }
  263. if (!exists $port_index{$port}) { next; }
  264. #skip uplink|downlink
  265. if ($port_links{$port}>0) { next; }
  266. my $simple_mac=mac_simplify($mac);
  267. my $mac_splitted=mac_splitted($mac);
  268. $mac_history{$simple_mac}{port_id}=$port_index{$port};
  269. $mac_history{$simple_mac}{dev_id}=$dev_id;
  270. if (!$mac_history{$simple_mac}{changed}) { $mac_history{$simple_mac}{changed}=0; }
  271. my $port_id=$port_index{$port};
  272. if (exists $auth_table{full_table}{$simple_mac} or exists $auth_table{oper_table}{$simple_mac}) {
  273. my $auth_id;
  274. if (exists $auth_table{oper_table}{$simple_mac}) { $auth_id=$auth_table{oper_table}{$simple_mac}; } else {
  275. $auth_id=$auth_table{full_table}{$simple_mac};
  276. if ($debug) {
  277. db_log_debug($dbh,"Mac not found in oper ARP-table. Use old values auth_id: $auth_id [$simple_mac] at device $dev_name [$port]");
  278. }
  279. }
  280. if (exists $connections{$auth_id}) {
  281. if ($port_id == $connections{$auth_id}{port}) {
  282. if (exists $auth_table{oper_table}{$simple_mac}) {
  283. my $auth_rec;
  284. $auth_rec->{last_found}=$now_str;
  285. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  286. }
  287. next;
  288. }
  289. $connections{$auth_id}{port}=$port_id;
  290. $mac_history{$simple_mac}{changed}=1;
  291. $mac_history{$simple_mac}{auth_id}=$auth_id;
  292. db_log_info($dbh,"Found auth_id: $auth_id [$mac_splitted] at device $dev_name [$port]. Update connection");
  293. my $auth_rec;
  294. $auth_rec->{last_found}=$now_str;
  295. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  296. my $conn_rec;
  297. $conn_rec->{port_id}=$port_id;
  298. $conn_rec->{device_id}=$dev_id;
  299. update_record($dbh,'connections',$conn_rec,"auth_id=$auth_id");
  300. } else {
  301. $mac_history{$simple_mac}{changed}=1;
  302. $mac_history{$simple_mac}{auth_id}=$auth_id;
  303. $connections{$auth_id}{port}=$port_id;
  304. db_log_info($dbh,"Found auth_id: $auth_id [$mac_splitted] at device $dev_name [$port]. Create connection.");
  305. my $auth_rec;
  306. $auth_rec->{last_found}=$now_str;
  307. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  308. my $conn_rec;
  309. $conn_rec->{port_id}=$port_id;
  310. $conn_rec->{device_id}=$dev_id;
  311. $conn_rec->{auth_id}=$auth_id;
  312. insert_record($dbh,'connections',$conn_rec);
  313. }
  314. } else {
  315. if (exists $unknown_table{$simple_mac}{unknown_id}) {
  316. next if ($unknown_table{$simple_mac}{port_id} == $port_id and $unknown_table{$simple_mac}{device_id} == $dev_id);
  317. $mac_history{$simple_mac}{changed}=1;
  318. $mac_history{$simple_mac}{auth_id}=0;
  319. db_log_debug($dbh,"Unknown mac $mac_splitted moved to $dev_name [$port]") if ($debug);
  320. my $unknown_rec;
  321. $unknown_rec->{port_id}=$port_id;
  322. $unknown_rec->{device_id}=$dev_id;
  323. update_record($dbh,'Unknown_mac',$unknown_rec,"id=$unknown_table{$simple_mac}{unknown_id}");
  324. } else {
  325. $mac_history{$simple_mac}{changed}=1;
  326. $mac_history{$simple_mac}{auth_id}=0;
  327. db_log_debug($dbh,"Unknown mac $mac_splitted found at $dev_name [$port]") if ($debug);
  328. my $unknown_rec;
  329. $unknown_rec->{port_id}=$port_id;
  330. $unknown_rec->{device_id}=$dev_id;
  331. $unknown_rec->{mac}=$simple_mac;
  332. insert_record($dbh,'Unknown_mac',$unknown_rec);
  333. }
  334. }
  335. }
  336. }
  337. db_log_verbose($dbh,'Mac discovery stopped.');
  338. }
  339. foreach my $mac (keys %mac_history) {
  340. next if (!$mac);
  341. next if (!$mac_history{$mac}->{changed});
  342. my $h_dev_id='';
  343. $h_dev_id=$mac_history{$mac}->{dev_id} if ($mac_history{$mac}->{dev_id});
  344. my $h_port_id='';
  345. $h_port_id=$mac_history{$mac}->{port_id} if ($mac_history{$mac}->{port_id});
  346. my $h_ip='';
  347. $h_ip=$mac_history{$mac}->{ip} if ($mac_history{$mac}->{ip});
  348. my $h_auth_id=$mac_history{$mac}->{auth_id} if ($mac_history{$mac}->{auth_id});
  349. if (!$h_auth_id) { $h_auth_id=0; }
  350. next if (!$h_dev_id);
  351. my $history_rec;
  352. $history_rec->{device_id}=$h_dev_id;
  353. $history_rec->{port_id}=$h_port_id;
  354. $history_rec->{mac}=$mac;
  355. $history_rec->{ip}=$h_ip;
  356. $history_rec->{auth_id}=$h_auth_id;
  357. insert_record($dbh,'mac_history',$history_rec);
  358. }
  359. $dbh->disconnect;
  360. exit 0;