fetch_new_arp.pl 15 KB

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