-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathNetDB.pm
3511 lines (2947 loc) · 118 KB
/
NetDB.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#########################################################################
# NetDB.pm - Network Tracking Database Interface/Update Module
# Author: Jonathan Yantis <[email protected]>
# Copyright (C) 2014 Jonathan Yantis
#########################################################################
#
# Module contains all the SQL statements and update logic to
# insert data in to NetDB. Initially, this data comes from
# the arp table and is updated from utilities like updatenetdb.pl.
# Data can be queried from netdb.
#
# Populating Database:
# netdbscraper.pl updates the CSV files on disk, and updatenetdb.pl
# interfaces with this module to insert the data in the database.
# See that file first and what methods it calls to import certain
# types of data.
#
# Important Requirements:
# - All MAC addresses should be in the format xxxx.xxxx.xxxx
# - Database server must be mysql and database must exist, use
# createnetdb.sql to initialize a new database
# - Several CPAN modules are required, see use statements below
# - Mac table lookup requires a configured oui.txt file
# - Configured from $config_file, make sure file exists and is correct
#
# API:
# All external scripts should use $dbh from connectDB[ro|rw]() as
# first argument
#
# Debugging:
# Set $DEBUG=1 for insert debugging, 2 for full debugging on all
# transactions. Also consider setting $dbh->{PrintError} = 1;
# in ConnectDB methods.
#
## Configuration File Example (Append to /etc/netdb.conf):
#dbname = netdb # DB must be created using createnetdb.sql first
#dbhost = localhost # Host MySQL is running on
#dbuser = netdbadmin # R/W User
#dbpass = yourpasswd # R/W Password
#dbuserRO = netdbuser # Read Only User - Can use the same dbuser and pass or restrict to SELECT only user
#dbpassRO = yourpasswd
#
# File from IEEE containing MAC vendor codes, recommended to schedule a cron job to update
# cron entry: 00 5 15 * * root wget http://standards.ieee.org/regauth/oui/oui.txt -O /scripts/data/oui.txt
#ouifile = /scripts/data/oui.txt
#
# NetDB Library Error log
#error_log = /var/log/netdb/netdb.error
#
##########################################################################
# Versions:
#
# v1.0 - 4/18/2008 - Initial Library Written
# v1.1 - 4/25/2008 - Numerour additions, mostly search options
# Created the switchports table to track movement of
# mac addresses.
# v1.2 - 7/1/2008 - Added the superswitch view for more detailed
# switch reports.
# v1.3 - 12/30/2008 - Added switchstatus table to database and
# methods to update the table. This is used for switch
# reports to get information on all ports on a switch.
# v1.4 - 02/04/2009 - r75-78 - Added getVlanSwitchStatus to get
# all ports configured for a vlan and any associated
# mac addresses. Also added sortBySwitch.
# v1.5 - 02/11/2009 - r87 - Added description to intstatus table
# v1.6 - 06/25/2009 - r145 - Implemented NAC registration import
# and export methods.
# v1.7 - 07/24/2009 - Rewrote date handling code and fixed bugs.
# Throttled DateTime requests to improve performance.
#
##########################################################################
# Simple Data Structure Example:
#
# # IP and mac are almost always required
# my @netdb = ( { ip => '128.23.1.1', mac => '1111.2222.3333' },
# { ip => '128.23.1.1', mac => '1111.2222.3333' },
# );
#
# my $netdb_ref = getQuery( \@netdb ); # pass as a reference
# @netdb = @$netdb_ref; # Dereference
#
# For bulk updates, subs access ref to array of %netdb refs
#
# See updatenetdb.pl load methods and netdb.pl print methods
# for examples of how to handle the data structure.
#
##########################################################################
# Database Structure:
# See createnetdb.sql, it is actively maintained and can be used
# to start the database over from scratch. If you make ANY edits
# to the database structure, make sure to update the file with
# your changes in case the database needs to be recreated from
# scratch
#
##########################################################################
# License:
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details:
# http://www.gnu.org/licenses/gpl.txt
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
###########################################################################
package NetDB;
use List::MoreUtils; # for any()
use English qw( -no_match_vars );
use AppConfig;
use Carp;
use DBI;
use DateTime;
use DateTime::Duration;
use DateTime::Format::MySQL;
use Data::UUID; # Generate transaction ids
use Net::IP;
use Net::DNS;
use Net::DNS::Resolver;
use NetAddr::IP;
use Net::MAC::Vendor;
require Exporter;
use strict;
use warnings;
# no nonsense
no warnings 'uninitialized';
our @ISA = qw(Exporter);
our @EXPORT = qw( connectDBrw connectDBro insertIPMAC bulkInsertIPMAC bulkUpdateStatic getMAC getMACList
getSwitchports getSwitchReport getNeverSeen getLastSeen getMACsfromIP getMACsfromIPList
getIPsfromMAC getNamefromIPMAC bulkUpdateMac getVendorCode getNewMacs getVlanReport sortByPort
insertTransaction getTransaction getTHistory sortByIP insertVlanChange bulkUpdateSwitchStatus
getDBStats getVlanSwitchStatus sortBySwitch deleteMacs deleteArp deleteSwitch getVersion
convertMacFormat insertNACReg bulkInsertNACReg getNACReg getNACUser getNACUserMAC
getShortMAC getDeleteStats getUnusedPorts getDisabled insertDisabled deleteDisabled
getCiscoMac getIEEEMac getDashMac sortIPList nameToIP IPToName setNetDBDebug
deleteWifi bulkInsertND updateNACRole updateDescription updatePortVLAN
getSwitchportDesc dropSwitch renameSwitch
);
# Module Version
my $VERSION = "1.13";
##########################################################################################
# NetDB Customized Settings
##########################################################################################
# Configuration is primarily read from $config_file in /etc/netdb.conf
# Configuration file to read from
my $config_file = "/etc/netdb.conf";
# DEBUG: Set to 1 for inserts, dates etc, 2 for full debug
my $DEBUG = 0; # Logs to stdout and to $errlog
my $printDBIErrors = 1; # We try to catch all errors, but this may be useful for development
my $maxDateTimes = 5000; # Maximum number of DB updates before getting a new DateTime
my $maxSwitchAge = 7; # Remove old switches after this many days
my $disable_v6_DNS = 0;
############################################################################################
# End Customized Settings
############################################################################################
my $dbname; # DB Name
my $dbhost; # DB Host
my $dbuser; # DB Read/Write User
my $dbpass; # R/W Password
my $dbuserRO; # DB Read Only User
my $dbpassRO; # DB RO Password
my $useDBTransactions = 1; # Required for proper error handling
# Required log file to write all errors to, must be writable
my $errlog;
# optional mac vendor file, highly recommended to keep this up to date
# cron entry: 00 5 15 * * root wget http://standards.ieee.org/regauth/oui/oui.txt -O /scripts/data/oui.txt
my $ouidb;
# Misc Vars
my $success = 1;
my $mac_format = "cisco";
my $update_interval = 15; # Default update time from cron, should be configured in netdb.conf
my ( $dbh, $no_switchstatus, $errmsg, $disable_DNS, $regex );
# Search over 5 years by default
my $search_dt = DateTime->now();
$search_dt->subtract( years => '5' );
#######################################################################################
######################################################
# SQL Query Handlers Localized below in prepareSQL() #
######################################################
# Statics in the table ip that have never had a mac address associated
my $selectNeverSeen_h;
# Selects statics that have been seen in a certain time range
my $selectLastSeen_h;
# Used for building selectLastSeen_h ip,mac pairs
my $selectSeen_h;
# Get all IPs that a mac address has had
my $SELECTipmacWHEREmac_h;
# Get all macs that an IP has had
my $SELECTipmacWHEREip_h;
# Get all ipmac entries that a hostname wildcard had
my $SELECTipmacWHEREname_h;
my $SELECTipmacWHEREvlan_h;
my $SELECTvlanstatusWHEREvlan_h;
my $SELECTsupermacWHEREvendor_h;
my $SELECTsupermacWHEREfirstmac_h;
# SQL Insert/Update/Query Handlers
# User Access Transactions
my $insertTransaction_h;
my $insertTransaction_h_string = "INSERT INTO transactions (id,ip,username,querytype,queryvalue,querydays,time) VALUES (?,?,?,?,?,?,?)";
my $selectTransaction_h;
my $selectTHistory_h;
# Switchports Table
my $selectSwitchports_h;
my $selectSwitchports_h_string = "SELECT * FROM switchports WHERE mac=? AND switch=? AND port=? ORDER BY lastseen";
my $updateSwitchports_h;
my $updateSwitchports_h_string = "UPDATE switchports SET lastseen=?,type=?,minutes=?,uptime=?,s_vlan=?,s_ip=?,s_name=?,s_speed=? WHERE mac=? AND switch=? AND port=?";
my $insertSwitchports_h;
my $insertSwitchports_h_string = "INSERT INTO switchports (mac,switch,port,type,minutes,uptime,s_vlan,s_ip,s_name,s_speed,firstseen,lastseen) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
#
my $selectSwitchportsWHEREmac_h;
my $selectSwitchportsWHEREmac_h_string = "SELECT * FROM switchports WHERE mac=? ORDER BY lastseen";
my $selectSwitchportsWHEREswitchport_h;
my $selectSwitchportsWHEREswitch_h;
# Switch Status Table
my $selectSwitchStatus_h;
my $selectSwitchStatus_h_string = "SELECT * FROM switchstatus WHERE switch=? AND port=?";
my $updateSwitchStatus_h;
my $updateSwitchStatus_h_string = "UPDATE switchstatus SET vlan=?,status=?,speed=?,duplex=?,description=?,lastseen=?,lastup=?," .
"p_minutes=?,p_uptime=? WHERE switch=? AND port=?";
my $insertSwitchStatus_h;
my $insertSwitchStatus_h_string = "INSERT INTO switchstatus (switch,port,vlan,status,speed,duplex,description,lastseen,lastup,p_minutes,p_uptime) " .
"VALUES (?,?,?,?,?,?,?,?,?,?,?)";
my $selectSwitchStatusWHEREswitch_h;
my $selectSwitchStatusWHEREswitch_h_string = "SELECT * FROM switchstatus WHERE switch like ?";
# Superswitch Table
my $selectSuperswitch_h;
my $selectSuperswitchWHEREmac_h;
my $selectSuperswitchWHEREswitch_h;
# Search superswitch for description
my $selectSuperswitchWHEREdesc_h;
# Insert in to ipmac tables, foreign key constraints on ip(ip),mac(mac)
my $selectIPMACPair_h;
my $selectIPMACPair_h_string = "SELECT * FROM ipmac WHERE ip=? AND mac=?";
my $updateIPMACPair_h;
my $updateIPMACPair_h_string = "UPDATE ipmac SET name=?,lastseen=?,ip_minutes=?,ip_uptime=?,vlan=?,vrf=?,router=? WHERE ip=? AND mac=?";
my $insertIPMACPair_h;
my $insertIPMACPair_h_string = "INSERT INTO ipmac (ip,mac,name,firstseen,lastseen,ip_minutes,ip_uptime,vlan,vrf,router) VALUES (?,?,?,?,?,?,?,?,?,?)";
# Insert in to IP Table
my $selectIP_h;
my $selectIP_h_string = "SELECT * FROM ip WHERE ip=?";
my $updateIP_h;
my $updateIP_h_string = "UPDATE ip SET static=?,lastmac=? WHERE ip=?";
my $insertIP_h;
my $insertIP_h_string = "INSERT INTO ip (ip,static,lastmac) VALUES (?,?,?)";
my $resetIPStatic_h;
my $resetIPStatic_h_string = "UPDATE ip SET static=0";
# MAC Table
my $selectMAC_h;
my $selectMAC_h_string = "SELECT * FROM mac WHERE mac=?";
my $selectSuperMAC_h;
my $selectSuperMAC_h_string = "SELECT * FROM supermac WHERE mac=?";
my $selectShortMAC_h;
# ipmac mac table update routines
my $updateMAC_h;
my $updateMAC_h_string = "UPDATE mac SET lastip=?,vendor=?,lastseen=?,lastipseen=? WHERE mac=?";
my $insertMAC_h;
my $insertMAC_h_string = "INSERT INTO mac (mac,lastip,vendor,firstseen,lastseen,lastipseen) VALUES (?,?,?,?,?,?)";
# Insert switchport info in to mac table
my $updateMACSwitchport_h;
my $updateMACSwitchport_h_string = "UPDATE mac SET lastswitch=?, lastport=?, vendor=?, mac_nd=?, lastseen=? WHERE mac=?";
my $insertMACSwitchport_h;
my $insertMACSwitchport_h_string = "INSERT INTO mac (mac,lastswitch,lastport,vendor,mac_nd,firstseen,lastseen) VALUES (?,?,?,?,?,?,?)";
# Neighbor Discovery Data
my $selectND_h;
my $selectND_h_string = "SELECT * FROM neighbor WHERE switch=? AND port=?";
my $insertND_h;
my $insertND_h_string = "INSERT INTO neighbor (switch,port,n_host,n_ip,n_desc,n_model,n_port,n_protocol,n_lastseen) VALUES (?,?,?,?,?,?,?,?,?)";
my $updateND_h;
my $updateND_h_string = "UPDATE neighbor SET n_host=?, n_ip=?, n_desc=?, n_model=?, n_port=?, n_protocol=?, n_lastseen=? WHERE switch=? AND port=?";
# nacreg data
my $selectNACReg_h;
my $selectNACReg_h_string = "SELECT * from nacreg WHERE mac=?";
my $selectNACUser_h;
my $selectNACUserMAC_h;
my $updateNACReg_h;
my $updateNACReg_h_string = "UPDATE nacreg SET time=?, firstName=?, lastName=?, userID=?, email=?, phone=?, type=?, entity=?, critical=?, role=?, title=?, status=?, pod=?, dbid=? WHERE mac=?";
my $insertNACReg_h;
my $insertNACReg_h_string = "INSERT INTO nacreg (mac,time,firstName,lastName,userID,email,phone,type,entity,critical,role,title,status,pod,dbid) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
# Disabled Table Data
my $selectDisabled_h;
my $selectDisabled_h_string = "SELECT * FROM disabled where mac=?";
my $insertDisabled_h;
my $insertDisabled_h_string = "INSERT INTO disabled (mac,distype,disuser,disdata,discase,disdate,severity) VALUES (?,?,?,?,?,?,?)";
my $deleteDisabled_h;
my $deleteDisabled_h_string = "DELETE FROM disabled where mac=?";
# Printer VLAN
my $insertVLANCHANGE_h;
my $insertVLANCHANGE_h_string = "INSERT INTO vlanchange (switch,port,vlan,username,ip,changetype,time) VALUES (?,?,?,?,?,?,?)";
my $selectVLANCHANGE_h;
my $selectVLANCHANGE_h_string = "SELECT * FROM vlanchange WHERE switch=?,port=?,changetype=?";
# Delete Methods
my $selectDeleteMacs_h;
my $deleteMacs_h;
my $selectDeleteArp_h;
my $deleteArp_h;
my $selectDeleteSwitch_h;
my $deleteSwitch_h;
my $selectDeleteWifi_h;
my $deleteWifi_h;
#########################
# DB Connection Methods #
#########################
# Establish connection to database, must connect to pass in to other functions
sub connectDBrw {
# Alternate Config File Option
my $alt_config = shift;
$config_file = $alt_config if $alt_config;
&parseConfig();
print "DEBUG: Connecting to Database as RW User\n" if $DEBUG>1;
my $dbh = DBI->connect("dbi:mysql:$dbname:$dbhost", "$dbuser", "$dbpass");
if ( $dbh ) {
$dbh->{PrintError} = $printDBIErrors;
# DB Version Check, die if failure
checkDBVersion( $dbh );
return $dbh;
}
else {
logErrorMessage( "$DBI::errstr" );
croak "$DBI::errstr\n";
}
}
# Establish user level access to the database, read-only access
sub connectDBro {
# Alternate Config File Option
my $alt_config = shift;
$config_file = $alt_config if $alt_config;
&parseConfig();
print "DEBUG: Connecting to Database as RO User\n" if $DEBUG>1;
my $dbh = DBI->connect("dbi:mysql:$dbname:$dbhost", "$dbuserRO", "$dbpassRO");
if ( $dbh ) {
$dbh->{PrintError} = $printDBIErrors;
# DB Version Check, die if failure
checkDBVersion( $dbh );
# Return Handler
return $dbh;
}
else {
logErrorMessage( "$DBI::errstr" );
croak "$DBI::errstr\n";
}
}
# Set the debug level from the command line -debug (updatenetdb.pl)
sub setNetDBDebug {
my $cli_debug = shift;
# Match CLI debug levels to library debug level
processDebug( $cli_debug );
print "NetDB Library Debug Level: $DEBUG\n";
}
sub getVersion {
return $VERSION;
}
########################
# Database Get Methods #
########################
#---------------------------------------------------------------------------------------------
# Get MAC table entry where MAC
# Input: ($dbh,$mac)
# dbh: database handle
# mac: MAC addresse
# Output:
# netdb refrence: the resulting table produced by the MAC lookup
#--------------------------------------------------------------------------------------------
sub getMAC {
$dbh = shift;
my $mac = shift;
my @macAdder = $mac;
if ( !$mac || !$dbh ) {
croak ("Must supply mac, check your input");
}
return getMACList($dbh,\@macAdder);
} # END sub getMAC
#---------------------------------------------------------------------------------------------
# Get MAC table entry where for list of MACs
# Input: ($dbh,$mac_ref)
# dbh: database handle
# mac reference: refrence to an array of MAC addresses
# Output: ($netdb_ref)
# netdb refrence: the resulting table produced by the MAC lookups
#---------------------------------------------------------------------------------------------
sub getMACList {
$dbh = shift;
my $mac_ref = shift;
my @MACs = @$mac_ref;
my $counter = 0;
my @netdbBulk;
if ( !$dbh ) {
croak ("|ERROR|: No database handle, check your input");
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
foreach my $mac (@MACs){
$mac = getCiscoMac($mac);
next if ( !$mac );
$selectSuperMAC_h->execute( $mac );
while ( my $row = $selectSuperMAC_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
} # END while through queries
} # END foreach loop though each mac address
my $netdb_ref = shortenV6( \@netdbBulk );
return $netdb_ref;
} # END sub getMACList
#---------------------------------------------------------------------------------------------
# Get mac table entries where short mac
# Format of mac: xx:xx (last 4) or xx:xx* or *xx:xx
#---------------------------------------------------------------------------------------------
sub getShortMAC {
$dbh = shift;
my $mac = shift;
my $counter = 0;
my $hours = shift;
my $search;
my $type = "end";
my @netdbBulk;
# Determine where wildcard is
# Search first part of mac address (xx:xx:xx*)
if ( $mac =~ /\*$/ ) {
# Strip out characters and put mac in partial cisco format
$mac =~ s/(\*|\:)//g;
$mac =~ s/(\w{4})/$1\./g;
chop( $mac ) if $mac =~ /\.$/;
$search = "$mac\%";
}
# Search the end of mac address (*xx:xx:xx)
else {
# Reverse String for processing
$mac = reverse( $mac );
# Strip out characters and put mac in partial cisco format
$mac =~ s/(\*|\:)//g;
$mac =~ s/(\w{4})/$1\./g;
# Reverse Again
$mac = reverse( $mac );
$search = "\%$mac";
}
print "Debug: search short mac: $search\n" if $DEBUG;
if ( !$search || !$dbh ) {
croak ("Must supply short mac, check your input: $search");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
$selectShortMAC_h->execute( "$search" );
while ( my $row = $selectShortMAC_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Get switchports on a mac entry
#---------------------------------------------------------------------------------------------
sub getSwitchports {
$dbh = shift;
my $mac = shift;
my $hours = shift;
my $row;
my $counter = 0;
my @netdbBulk;
$mac = getCiscoMac($mac);
if ( !$mac || !$dbh ) {
croak ("Must supply mac, check your input");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h || $hours ) {
prepareSQL();
}
$selectSuperswitchWHEREmac_h->execute( $mac );
while ( $row = $selectSuperswitchWHEREmac_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
$netdb_ref = fixupSwitchports( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Get a switch report on a switch name and optionally a port after the comma
#---------------------------------------------------------------------------------------------
sub getSwitchReport {
$dbh = shift;
my $switch = shift;
my $hours = shift;
my $port;
my $row;
my $counter = 0;
my @netdbBulk;
# Split off port if it exists
($switch, $port) = split( /\,/, $switch);
# If no port, use wildcard
if ( !$port ) {
$port = "\%";
}
else {
$port = "$port";
}
# Allow wildcard (*) for switch names
$switch =~ s/\*$/\%/; $switch =~ s/^\*/\%/; $switch =~ s/\*//g;
if ( !$switch || !$dbh ) {
croak ("Must supply switch, check your input");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
$selectSuperswitchWHEREswitch_h->execute( $switch, $port );
while ( $row = $selectSuperswitchWHEREswitch_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
$netdb_ref = fixupSwitchports( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Get all switchports that have a description that matches %$search%
#---------------------------------------------------------------------------------------------
sub getSwitchportDesc {
$dbh = shift;
my $search = shift;
my $hours = shift;
my $row;
my $counter = 0;
my @netdbBulk;
if ( !$search || !$dbh ) {
croak ("Must supply description search term, check your input");
}
chomp( $search );
$search = "\%$search\%";
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
$selectSuperswitchWHEREdesc_h->execute( $search );
while ( $row = $selectSuperswitchWHEREdesc_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
$netdb_ref = fixupSwitchports( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Hostname Search on ipmac
#---------------------------------------------------------------------------------------------
sub getNamefromIPMAC {
$dbh = shift;
my $name = shift;
my $hours = shift;
my $row;
my $counter = 0;
my @netdbBulk;
if ( !$name || !$dbh ) {
croak ("Must supply hostname, check your input");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
# Don't full-text search hostnames unless requested
# Big performance increases with large ARP tables
if ( $regex ) {
# Allow (*) as wildcard at the beginning and end of line
$name =~ s/\*$/\%/; $name =~ s/^\*/\%/; $name =~ s/\*//g;
$SELECTipmacWHEREname_h->execute( $name );
}
else {
$SELECTipmacWHEREname_h->execute( "\%$name\%" );
}
while ( $row = $SELECTipmacWHEREname_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Get all macs at IP address
# Input: ($dbh,$ip,$hours)
# dbh: database handle
# ip: an IP addresses
# hours: how far back to look for the information
# Output: ($netdb_ref)
# netdb refrence: the resulting table produced by the IP lookup
#---------------------------------------------------------------------------------------------
sub getMACsfromIP {
$dbh = shift;
my $ip = shift;
my $hours = shift;
my @ipAdder = $ip;
if ( !$ip || !$dbh ) {
croak ("Must supply a valid IPv4 or IPv6 address, or partial IP eg. 10.10. check your input");
}
return getMACsfromIPList ( $dbh, \@ipAdder, $hours);
} # END sub getMACsfromIP
#---------------------------------------------------------------------------------------------
# Get all macs from a list of IP address
# Input: ($dbh,$ip,$hours)
# dbh: database handle
# ip reference: refrence to an array of IP addresses
# hours: how far back to look for the information
# Output: ($netdb_ref)
# netdb refrence: the resulting table produced by the IP lookups
#---------------------------------------------------------------------------------------------
sub getMACsfromIPList {
$dbh = shift;
my $ip = shift;
my $hours = shift;
my @IPs = @$ip;
my $row;
my $counter = 0;
my @netdbBulk;
if ( !$dbh ) {
croak ("|ERROR|: No database handle, check your input, check your input");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
foreach my $ip (@IPs){
next if ( !$ip );
# Support wildcard ip queries
my $ipchk = new Net::IP($ip);
# Valid IP check
if ( $ipchk ) {
# IPv6 Address, get long format and strip colons
if ( $ip =~ /:/ ) {
$ip = $ipchk->ip();
$ip =~ s/://g;
}
}
# Partial IP, eg. 10.10.
elsif ( $ip =~ /^(\d+)(\.\d+){1}/ ) {
$ip = "$ip%";
}
else {
$ip = undef;
}
$SELECTipmacWHEREip_h->execute( $ip );
while ( $row = $SELECTipmacWHEREip_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
return $netdb_ref;
} # END sub getMACsfromIPList
#---------------------------------------------------------------------------------------------
# Get all IP address at MAC
#---------------------------------------------------------------------------------------------
sub getIPsfromMAC {
$dbh = shift;
my $mac = shift;
my $hours = shift;
my $row;
my $counter = 0;
my @netdbBulk;
$mac = getCiscoMac($mac);
if ( !$mac || !$dbh ) {
croak ("Must supply mac address, check your input");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
prepareSQL(); # Reinitialize time stamps
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
$SELECTipmacWHEREmac_h->execute( $mac );
while ( $row = $SELECTipmacWHEREmac_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Get ipmac entries where vlan=
#---------------------------------------------------------------------------------------------
sub getVlanReport {
$dbh = shift;
my $vlan = shift;
my $hours = shift;
my $row;
my $counter = 0;
my @netdbBulk;
if ( !$vlan || !$dbh ) {
croak ("Must supply vlan, check your input");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
$SELECTipmacWHEREvlan_h->execute( $vlan );
while ( $row = $SELECTipmacWHEREvlan_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Get superstatus table where vlan
#---------------------------------------------------------------------------------------------
sub getVlanSwitchStatus {
$dbh = shift;
my $vlan = shift;
my $hours = shift;
my $row;
my $counter = 0;
my @netdbBulk;
if ( !$vlan || !$dbh ) {
croak ("Must supply vlan, check your input");
}
# Initialize Search hours before setting up queries
if ( $hours ) {
$search_dt = getDate( $hours );
}
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
$SELECTvlanstatusWHEREvlan_h->execute( $vlan );
while ( $row = $SELECTvlanstatusWHEREvlan_h->fetchrow_hashref() ) {
if ( $row ) {
$netdbBulk[$counter] = $row;
$counter++;
}
}
my $netdb_ref = shortenV6( \@netdbBulk );
return $netdb_ref;
}
#---------------------------------------------------------------------------------------------
# Get new mac address on the network in the past $hours
#---------------------------------------------------------------------------------------------
sub getNewMacs {
$dbh = shift;
my $hours = shift;
my $row;
my $counter = 0;
my @netdbBulk;
if ( !$hours || !$dbh ) {
croak ("Must supply timeframe, check your input");
}
# Initialize Search hours before setting up queries
$search_dt = getDate( $hours );
# Initialize queries if necessary
if ( !$selectIP_h ) {
prepareSQL();
}
$SELECTsupermacWHEREfirstmac_h->execute();
while ( $row = $SELECTsupermacWHEREfirstmac_h->fetchrow_hashref() ) {