source: trunk/klask @ 79

Last change on this file since 79 was 79, checked in by g7moreau, 13 years ago
  • Add verbose option to updatesw
  • Property svn:executable set to *
  • Property svn:keywords set to Date Author Id Rev
File size: 62.2 KB
Line 
1#!/usr/bin/perl -w
2#
3# Copyright (C) 2005-2008 Gabriel Moreau.
4#
5# $Id: klask 79 2011-03-29 15:37:45Z g7moreau $
6
7use strict;
8use warnings;
9use version; our $VERSION = qv('0.5.5');
10
11use Readonly;
12use FileHandle;
13use Net::SNMP;
14#use YAML;
15use YAML::Syck;
16use Net::Netmask;
17use Net::CIDR::Lite;
18use NetAddr::IP;
19use Getopt::Long qw(GetOptions GetOptionsFromArray);;
20use Socket;
21
22# apt-get install snmp fping libnet-cidr-lite-perl libnet-netmask-perl libnet-snmp-perl libnetaddr-ip-perl libyaml-perl
23# libcrypt-des-perl libcrypt-hcesha-perl libdigest-hmac-perl
24# arping net-tools fping bind9-host arpwatch
25
26my $KLASK_VAR      = '/var/cache/klask';
27my $KLASK_CFG_FILE = '/etc/klask.conf';
28my $KLASK_DB_FILE  = "$KLASK_VAR/klaskdb";
29my $KLASK_SW_FILE  = "$KLASK_VAR/switchdb";
30
31test_running_environnement();
32
33my $KLASK_CFG = YAML::Syck::LoadFile("$KLASK_CFG_FILE");
34
35my %DEFAULT = %{ $KLASK_CFG->{default} };
36my @SWITCH  = @{ $KLASK_CFG->{switch}  };
37
38my %switch_level = ();
39my %SWITCH_DB    = ();
40LEVEL_OF_EACH_SWITCH:
41for my $sw (@SWITCH){
42   $switch_level{$sw->{hostname}} = $sw->{level} || $DEFAULT{switch_level}  || 2;
43   $SWITCH_DB{$sw->{hostname}} = $sw;
44   }
45@SWITCH = reverse sort { $switch_level{$a->{hostname}} <=> $switch_level{$b->{hostname}} } @{$KLASK_CFG->{switch}};
46
47my %SWITCH_PORT_COUNT = ();
48
49my %CMD_DB = (
50   help       => \&cmd_help,
51   version    => \&cmd_version,
52   exportdb   => \&cmd_exportdb,
53   updatedb   => \&cmd_updatedb,
54   searchdb   => \&cmd_searchdb,
55   removedb   => \&cmd_removedb,
56   cleandb   => \&cmd_cleandb,
57   search     => \&cmd_search,
58   enable     => \&cmd_enable,
59   disable    => \&cmd_disable,
60   status     => \&cmd_status,
61   updatesw   => \&cmd_updatesw,
62   exportsw   => \&cmd_exportsw,
63   iplocation => \&cmd_iplocation,
64   'ip-free'  => \&cmd_ip_free,
65   'search-mac-on-switch' => \&cmd_search_mac_on_switch,
66   );
67
68Readonly my %INTERNAL_PORT_MAP => (
69   0 => 'A',
70   1 => 'B',
71   2 => 'C',
72   3 => 'D',
73   4 => 'E',
74   5 => 'F',
75   6 => 'G',
76   7 => 'H',
77   );
78Readonly my %INTERNAL_PORT_MAP_REV => reverse %INTERNAL_PORT_MAP;
79
80Readonly my %SWITCH_KIND => (
81   J3299A => { model => 'HP224M',     match => 'HP J3299A ProCurve Switch 224M'  },
82   J4120A => { model => 'HP1600M',    match => 'HP J4120A ProCurve Switch 1600M' },
83   J9029A => { model => 'HP1800-8G',  match => 'PROCURVE J9029A'                 },
84   J9449A => { model => 'HP1810-8G',  match => 'HP ProCurve 1810G - 8 GE'        },
85   J4093A => { model => 'HP2424M',    match => 'HP J4093A ProCurve Switch 2424M' },
86   J9279A => { model => 'HP2510G-24', match => 'ProCurve J9279A Switch 2510G-24' },
87   J9280A => { model => 'HP2510G-48', match => 'ProCurve J9280A Switch 2510G-48' },
88   J4813A => { model => 'HP2524',     match => 'HP J4813A ProCurve Switch 2524'  },
89   J4900A => { model => 'HP2626A',    match => 'HP J4900A ProCurve Switch 2626'  },
90   J4900B => { model => 'HP2626B',    match => 'J4900B.+?Switch 2626'            },# ProCurve J4900B Switch 2626 # HP J4900B ProCurve Switch 2626
91   J4899B => { model => 'HP2650',     match => 'ProCurve J4899B Switch 2650'     },
92   J9021A => { model => 'HP2810-24G', match => 'ProCurve J9021A Switch 2810-24G' },
93   J9022A => { model => 'HP2810-48G', match => 'ProCurve J9022A Switch 2810-48G' },
94   J4903A => { model => 'HP2824',     match => 'J4903A.+?Switch 2824,'           },
95   J4110A => { model => 'HP8000M',    match => 'HP J4110A ProCurve Switch 8000M' },
96   BS350T => { model => 'BS350T',     match => 'BayStack 350T HW'                },
97   );
98
99Readonly my %OID_NUMBER => (
100   sysDescription  => '1.3.6.1.2.1.1.1.0',
101   sysName         => '1.3.6.1.2.1.1.5.0',
102   sysContact      => '1.3.6.1.2.1.1.4.0',
103   sysLocation     => '1.3.6.1.2.1.1.6.0',
104   );
105
106Readonly my $RE_MAC_ADDRESS  => qr{ [0-9,A-Z]{2} : [0-9,A-Z]{2} : [0-9,A-Z]{2} : [0-9,A-Z]{2} : [0-9,A-Z]{2} : [0-9,A-Z]{2} }xms;
107Readonly my $RE_IPv4_ADDRESS => qr{ [0-9]{1,3} \. [0-9]{1,3} \. [0-9]{1,3} \. [0-9]{1,3} }xms;
108
109
110################
111# principal
112################
113
114my $cmd = shift @ARGV || 'help';
115if (defined $CMD_DB{$cmd}) {
116   $CMD_DB{$cmd}->(@ARGV);
117   }
118else {
119   print {*STDERR} "klask: command $cmd not found\n\n";
120   $CMD_DB{help}->();
121   exit 1;
122   }
123
124exit;
125
126sub test_running_environnement {
127   die "Configuration file $KLASK_CFG_FILE does not exists. Klask need it !\n" if not -e "$KLASK_CFG_FILE";
128   die "Var folder $KLASK_VAR does not exists. Klask need it !\n"              if not -d "$KLASK_VAR";
129   return;
130   }
131
132sub test_switchdb_environnement {
133   die "Switch database $KLASK_SW_FILE does not exists. Launch updatesw before this command !\n" if not -e "$KLASK_SW_FILE";
134   return;
135   }
136
137sub test_maindb_environnement {
138   die "Main database $KLASK_DB_FILE does not exists. Launch updatedb before this command !\n" if not -e "$KLASK_DB_FILE";
139   return;
140   }
141
142###
143# fast ping dont l'objectif est de remplir la table arp de la machine
144sub fastping {
145   # Launch this command without waiting...
146   system "fping -c 1 @_ >/dev/null 2>&1 &";
147   return;
148   }
149
150sub shell_command {
151   my $cmd = shift;
152
153   my $fh     = new FileHandle;
154   my $result = '';
155   open $fh, q{-|}, "$cmd" or die "Can't exec $cmd\n";
156   $result .= <$fh>;
157   close $fh;
158   chomp $result;
159   return $result;
160   }
161
162###
163# donne l'@ ip, dns, arp en fonction du dns OU de l'ip
164sub resolve_ip_arp_host {
165   my $param_ip_or_host = shift;
166   my $interface = shift || q{*};
167   my $type      = shift || q{fast};
168
169   my %ret = (
170      hostname_fq  => 'unknow',
171      ipv4_address => '0.0.0.0',
172      mac_address  => 'unknow',
173      );
174
175#   my $cmdarping  = `arping -c 1 -w 1 -rR $param 2>/dev/null`;
176#   if ( not $param_ip_or_host =~ m/^\d+ \. \d+ \. \d+ \. \d+$/xms ) {
177#      $param_ip_or_host =~ s/ \. .* //xms;
178#      }
179
180   #my $dns_resolver =  Net::DNS::Resolver->new;
181   #my $dns_answer = $dns_resolver->query($param_ip_or_host);
182   #if ($dns_answer) {
183   #   $ret{ipv4_address} = $dns_answer->address;
184   #   }
185
186   # perl -MSocket -E 'say inet_ntoa(scalar gethostbyname("tech7meylan.hmg.inpg.fr"))'
187   my $packed_ip = scalar gethostbyname($param_ip_or_host);
188   return %ret if not defined $packed_ip;
189   $ret{ipv4_address} = inet_ntoa($packed_ip);
190
191   # perl -MSocket -E 'say scalar gethostbyaddr(inet_aton("194.254.66.240"), AF_INET)'
192   my $hostname_fq = scalar gethostbyaddr($packed_ip, AF_INET);
193#   return %ret if not defined $hostname_fq;
194   $ret{hostname_fq} = $hostname_fq if defined $hostname_fq;
195
196#print "DEBUG : $param_ip_or_host --  $ret{ipv4_address} --   $hostname_fq \n";
197
198   # controler que arpwatch tourne !
199   # resultat de la commande arpwatch
200   # /var/lib/arpwatch/arp.dat
201   # 0:13:d3:e1:92:d0        192.168.24.109  1163681980      theo8sv109
202   # my $cmd = "grep  -e '".'\b'."$param_ip_or_host".'\b'."' /var/lib/arpwatch/arp.dat | sort +2rn | head -1";
203   # my $cmd = "grep  -he '".'\b'."$param_ip_or_host".'\b'."' /var/lib/arpwatch/*.dat | sort +2rn | head -1";
204
205### BOGUE ICI
206### FAIRE LE GREP SUR L'IP !
207
208   # my $cmd = q{grep  -he '\b} . $param_ip_or_host . q{\b' } . "/var/lib/arpwatch/$interface.dat | sort -rn -k 3,3 | head -1";
209   my $cmd = q{grep  -he '\b} . $ret{ipv4_address} . q{\b' } . "/var/lib/arpwatch/$interface.dat | sort -rn -k 3,3 | head -1";
210   my $cmd_arpwatch = shell_command $cmd;
211   my ($arp, $ip, $timestamp, $host) = split m/ \s+ /xms, $cmd_arpwatch;
212
213#   $ret{ipv4_address} = $ip        if $ip;
214   $ret{mac_address}  = $arp       if $arp;
215   $ret{timestamp}    = $timestamp if $timestamp;
216
217   my $nowtimestamp = time;
218
219   if ( $type eq 'fast' and ( not defined $timestamp or $timestamp < ( $nowtimestamp - 1.1 * 3600 ) ) ) {
220      $ret{mac_address} = 'unknow';
221      return %ret;
222      }
223
224   # resultat de la commande arp
225   # tech7meylan.hmg.inpg.fr (194.254.66.240) at 00:14:22:45:28:A9 [ether] on eth0
226   # sw2-batF0-legi.hmg.priv (192.168.22.112) at 00:30:c1:76:9c:01 [ether] on eth0.37
227   my $cmd_arp  = shell_command "arp -a $param_ip_or_host";
228   if ( $cmd_arp =~ m{ (\S*) \s \( ( $RE_IPv4_ADDRESS ) \) \s at \s ( $RE_MAC_ADDRESS ) }xms ) {
229      ( $ret{hostname_fq}, $ret{ipv4_address}, $ret{mac_address} )  = ($1, $2, $3);
230      }
231
232   # resultat de la commande host si le parametre est ip
233   # 250.66.254.194.in-addr.arpa domain name pointer legihp2100.hmg.inpg.fr.
234#   my $cmd_host = shell_command "host $param_ip_or_host";
235#   if ( $cmd_host =~ m/domain \s name \s pointer \s (\S+) \.$/xms ) {
236#      $ret{hostname_fq} = $1;
237#      }
238
239   # resultat de la commande host si parametre est hostname
240   # tech7meylan.hmg.inpg.fr has address 194.254.66.240
241#   if ( $cmd_host =~ m/(\S*) \s has \s address \s ( $RE_IPv4_ADDRESS )$/xms ) {
242#      ( $ret{hostname_fq}, $ret{ipv4_address} ) = ($1, $2);
243#      }
244
245   # Connerie !
246   # Inverse les IP !!
247   # if ( $cmd_host =~ m/ \b ( $RE_IPv4_ADDRESS ) \. in-addr \. arpa \s/xms ) {
248   #    $ret{ipv4_address} = $1;
249   #    }
250   #$ret{hostname_fq}  = $param_ip_or_host if not defined $1 and $ret{hostname_fq} eq 'unknow';
251
252   if ($ret{mac_address} ne 'unknow') {
253      my @paquets = ();
254      foreach ( split m/ : /xms, $ret{mac_address} ) {
255         my @chars = split m//xms, uc "00$_";
256         push @paquets, "$chars[-2]$chars[-1]";
257         }
258      $ret{mac_address} = join q{:}, @paquets;
259      }
260
261   return %ret;
262   }
263
264# Find Surname of a switch
265sub get_switch_model {
266   my $sw_snmp_description = shift || 'unknow';
267
268   for my $sw_kind (keys %SWITCH_KIND) {
269      next if not $sw_snmp_description =~ m/$SWITCH_KIND{$sw_kind}->{match}/ms; # option xms break search, why ?
270
271      return $SWITCH_KIND{$sw_kind}->{model};
272      }
273
274   return $sw_snmp_description;
275   }
276
277###
278# va rechercher le nom des switchs pour savoir qui est qui
279sub init_switch_names {
280   my $verbose = shift;
281
282   printf "%-25s                %-25s %s\n",'Switch','Description','Type';
283   print "-------------------------------------------------------------------------\n" if $verbose;
284
285   INIT_EACH_SWITCH:
286   for my $sw (@SWITCH) {
287      my %session = ( -hostname   => $sw->{hostname} );
288         $session{-version} = $sw->{version}   || 1;
289         $session{-port}    = $sw->{snmpport}  || $DEFAULT{snmpport}  || 161;
290         if (exists $sw->{version} and $sw->{version} eq '3') {
291            $session{-username} = $sw->{username} || 'snmpadmin';
292            }
293         else {
294            $session{-community} = $sw->{community} || $DEFAULT{community} || 'public';
295            }
296
297      $sw->{local_session} = \%session;
298
299      my ($session, $error) = Net::SNMP->session( %{$sw->{local_session}} );
300      print "$error \n" if $error;
301
302      my $result = $session->get_request(
303         -varbindlist => [
304            $OID_NUMBER{sysDescription},
305            $OID_NUMBER{sysName},
306            $OID_NUMBER{sysContact},
307            $OID_NUMBER{sysLocation},
308            ]
309         );
310      $sw->{description} = $result->{$OID_NUMBER{sysName}} || $sw->{hostname};
311      $sw->{model} = get_switch_model( $result->{$OID_NUMBER{sysDescription}});
312      #$sw->{location} = $result->{"1.3.6.1.2.1.1.6.0"} || $sw->{hostname};
313      #$sw->{contact} = $result->{"1.3.6.1.2.1.1.4.0"} || $sw->{hostname};
314      $session->close;
315
316      # Ligne à virer car on récupère maintenant le modèle du switch
317      my ($desc, $type) = split m/ : /xms, $sw->{description}, 2;
318      printf "%-25s 0--------->>>> %-25s %s\n", $sw->{hostname}, $desc, $sw->{model} if $verbose;
319      }
320
321   print "\n" if $verbose;
322   return;
323   }
324
325###
326# convertit l'hexa (uniquement 2 chiffres) en decimal
327sub hex_to_dec {
328   #00:0F:1F:43:E4:2B
329   my $car = '00' . uc shift;
330
331   return '00' if $car eq '00UNKNOW';
332   my %table = (
333      '0'=>'0',  '1'=>'1',  '2'=>'2',  '3'=>'3',  '4'=>'4',
334      '5'=>'5',  '6'=>'6',  '7'=>'7',  '8'=>'8',  '9'=>'9',
335      'A'=>'10', 'B'=>'11', 'C'=>'12', 'D'=>'13', 'E'=>'14', 'F'=>'15',
336      );
337   my @chars = split m//xms, $car;
338   return $table{$chars[-2]}*16 + $table{$chars[-1]};
339   }
340
341###
342# convertit l'@ arp en decimal
343sub arp_hex_to_dec {
344   #00:0F:1F:43:E4:2B
345   my $arp = shift;
346
347   my @paquets = split m/ : /xms, $arp;
348   my $return = q{};
349   foreach(@paquets) {
350      $return .= q{.} . hex_to_dec($_);
351      }
352   return $return;
353   }
354
355###
356# va rechercher le port et le switch sur lequel est la machine
357sub find_switch_port {
358   my $arp             = shift;
359   my $switch_proposal = shift || q{};
360
361   my %ret;
362   $ret{switch_description} = 'unknow';
363   $ret{switch_port} = '0';
364
365   return %ret if $arp eq 'unknow';;
366
367   my @switch_search = @SWITCH;
368   if ($switch_proposal ne q{}) {
369      for my $sw (@SWITCH) {
370         next if $sw->{hostname} ne $switch_proposal;
371         unshift @switch_search, $sw;
372         last;
373         }
374      }
375
376   my $research = '1.3.6.1.2.1.17.4.3.1.2' . arp_hex_to_dec($arp);
377
378   LOOP_ON_SWITCH:
379   for my $sw (@switch_search) {
380      my ($session, $error) = Net::SNMP->session( %{$sw->{local_session}} );
381      print "$error \n" if $error;
382
383      my $result = $session->get_request(
384         -varbindlist => [$research]
385         );
386      if (not defined $result or $result->{$research} eq 'noSuchInstance') {
387         $session->close;
388         next LOOP_ON_SWITCH;
389         }
390
391         my $swport = $result->{$research};
392         $session->close;
393
394         # IMPORTANT !!
395         # ceci empeche la detection sur certains port ...
396         # en effet les switch sont relies entre eux par un cable reseau et du coup
397         # tous les arp de toutes les machines sont presentes sur ces ports (ceux choisis ici sont les miens)
398         # cette partie est a ameliore, voir a configurer dans l'entete
399         # 21->24 45->48
400#         my $flag = 0;
401         SWITCH_PORT_IGNORE:
402         foreach my $p (@{$sw->{portignore}}) {
403            next SWITCH_PORT_IGNORE if $swport ne get_numerical_port($sw->{model},$p);
404#            $flag = 1;
405            next LOOP_ON_SWITCH;
406            }
407#         if ($flag == 0) {
408            $ret{switch_hostname}    = $sw->{hostname};
409            $ret{switch_description} = $sw->{description};
410            $ret{switch_port}        = get_human_readable_port($sw->{model}, $swport); # $swport;
411
412            last LOOP_ON_SWITCH;
413#            }
414#         }
415#      $session->close;
416      }
417   return %ret;
418   }
419
420###
421# va rechercher les port et les switch sur lequel est la machine
422sub find_all_switch_port {
423   my $arp = shift;
424
425   my $ret = {};
426
427   return $ret if $arp eq 'unknow';
428
429   for my $sw (@SWITCH) {
430      $SWITCH_PORT_COUNT{$sw->{hostname}} = {} if not exists $SWITCH_PORT_COUNT{$sw->{hostname}};
431      }
432
433   my $research = '1.3.6.1.2.1.17.4.3.1.2' . arp_hex_to_dec($arp);
434   LOOP_ON_ALL_SWITCH:
435   for my $sw (@SWITCH) {
436      my ($session, $error) = Net::SNMP->session( %{$sw->{local_session}} );
437      print "$error \n" if $error;
438
439      my $result = $session->get_request(
440         -varbindlist => [$research]
441         );
442
443      if(defined $result and $result->{$research} ne 'noSuchInstance'){
444         my $swport = $result->{$research};
445
446#print "DEBUG $arp  $swport --  $sw->{hostname} \n";
447#         if ( $sw->{hostname} eq 'sw10-batE1-3s.hmg.priv' and $swport == 19 ) { $swport = 20; print "DEBUG $swport --  $sw->{hostname} \n";}
448#         if ( $sw->{hostname} eq 'sw8-batE1-3s.hmg.priv'  and $swport == 23 ) { $swport = 24; print "DEBUG $swport --  $sw->{hostname} \n";}
449#         if ( $sw->{hostname} eq 'sw10-batE1-3s.hmg.priv' ) {  print "DEBUG $swport --  $sw->{hostname} \n";}
450#         if ( $sw->{hostname} eq 'sw8-batE1-3s.hmg.priv'  ) {  print "DEBUG $swport --  $sw->{hostname} \n";}
451
452         $ret->{$sw->{hostname}} = {};
453         $ret->{$sw->{hostname}}{hostname}    = $sw->{hostname};
454         $ret->{$sw->{hostname}}{description} = $sw->{description};
455         $ret->{$sw->{hostname}}{port}        = get_human_readable_port($sw->{model}, $swport);
456
457         $SWITCH_PORT_COUNT{$sw->{hostname}}->{$swport}++;
458         }
459
460      $session->close;
461      }
462   return $ret;
463   }
464
465sub get_list_network {
466
467   return keys %{$KLASK_CFG->{network}};
468   }
469
470sub get_current_interface {
471   my $network = shift;
472
473   return $KLASK_CFG->{network}{$network}{interface};
474   }
475
476###
477# liste l'ensemble des adresses ip d'un réseau
478sub get_list_ip {
479   my @network = @_;
480
481   my $cidrlist = Net::CIDR::Lite->new;
482
483   for my $net (@network) {
484      my @line  = @{$KLASK_CFG->{network}{$net}{'ip-subnet'}};
485      for my $cmd (@line) {
486         for my $method (keys %{$cmd}){
487            $cidrlist->add_any($cmd->{$method}) if $method eq 'add';
488            }
489         }
490      }
491
492   my @res = ();
493
494   for my $cidr ($cidrlist->list()) {
495      my $net = new NetAddr::IP $cidr;
496      for my $ip (@{$net}) {
497         $ip =~ s{ /32 }{}xms;
498         push @res,  $ip;
499         }
500      }
501
502   return @res;
503   }
504
505# liste l'ensemble des routeurs du réseau
506sub get_list_main_router {
507   my @network = @_;
508
509   my @res = ();
510
511   for my $net (@network) {
512      push @res, $KLASK_CFG->{network}{$net}{'main-router'};
513      }
514
515   return @res;
516   }
517
518sub get_human_readable_port {
519   my $sw_model = shift;
520   my $sw_port  = shift;
521
522   if ($sw_model eq 'HP8000M') {
523
524      my $reste = (($sw_port - 1) % 8) + 1;
525      my $major = int (($sw_port - 1) / 8);
526      return "$INTERNAL_PORT_MAP{$major}$reste";
527      }
528
529   if ($sw_model eq 'HP2424M') {
530      if ($sw_port > 24) {
531         
532         my $reste = $sw_port - 24;
533         return "A$reste";
534         }
535      }
536
537   if ($sw_model eq 'HP1600M') {
538      if ($sw_port > 16) {
539         
540         my $reste = $sw_port - 16;
541         return "A$reste";
542         }
543      }
544
545   return $sw_port;
546   }
547
548sub get_numerical_port {
549   my $sw_model = shift;
550   my $sw_port  = shift;
551
552   if ($sw_model eq 'HP8000M') {
553
554      my $letter = substr $sw_port, 0, 1;
555      my $reste =  substr $sw_port, 1;
556
557      return $INTERNAL_PORT_MAP_REV{$letter} * 8 + $reste;
558      }
559
560   if ($sw_model eq 'HP2424M') {
561      if ($sw_port =~ m/^A/xms ) {
562
563         my $reste =  substr $sw_port, 1;
564
565         return 24 + $reste;
566         }
567      }
568
569   if ($sw_model eq 'HP1600M') {
570      if ($sw_port =~ m/^A/xms ) {
571
572         my $reste =  substr $sw_port, 1;
573
574         return 16 + $reste;
575         }
576      }
577
578   return $sw_port;
579   }
580
581################
582# Les commandes
583################
584
585sub cmd_help {
586
587print <<'END';
588klask - ports manager and finder for switch
589
590 klask updatedb
591 klask exportdb --format [txt|html]
592 klask removedb computer*
593 klask cleandb  --day number_of_day --verbose
594
595 klask updatesw
596 klask exportsw --format [txt|dot]
597
598 klask searchdb computer
599 klask search   computer
600 klask search-mac-on-switch switch mac_addr
601
602 klask ip-free --day number_of_day --format [txt|html] [vlan_name]
603
604 klask enable  switch port
605 klask disable switch port
606 klask status  switch port
607END
608   return;
609   }
610
611sub cmd_version {
612
613print <<'END';
614Klask - ports manager and finder for switch
615Copyright (C) 2005-2008 Gabriel Moreau
616
617END
618   print ' $Rev: 79 $'."\n";
619   print ' $Date: 2011-03-29 15:37:45 +0000 (Tue, 29 Mar 2011) $'."\n";
620   print ' $Id: klask 79 2011-03-29 15:37:45Z g7moreau $'."\n";
621   return;
622   }
623
624sub cmd_search {
625   my @computer = @_;
626
627   init_switch_names();    #nomme les switchs
628   fastping(@computer);
629   for my $clientname (@computer) {
630      my %resol_arp = resolve_ip_arp_host($clientname);          #resolution arp
631      my %where     = find_switch_port($resol_arp{mac_address}); #retrouve l'emplacement
632      printf '%-22s %2i %-30s %-15s %18s', $where{switch_description}, $where{switch_port}, $resol_arp{hostname_fq}, $resol_arp{ipv4_address}, $resol_arp{mac_address}."\n"
633         unless $where{switch_description} eq 'unknow' and $resol_arp{hostname_fq} eq 'unknow' and $resol_arp{mac_address} eq 'unknow';
634      }
635   return;
636   }
637
638sub cmd_searchdb {
639   my @computer = @_;
640
641   fastping(@computer);
642   my $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE");
643
644   LOOP_ON_COMPUTER:
645   for my $clientname (@computer) {
646      my %resol_arp = resolve_ip_arp_host($clientname);      #resolution arp
647      my $ip = $resol_arp{ipv4_address};
648
649      next LOOP_ON_COMPUTER unless exists $computerdb->{$ip};
650
651      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $computerdb->{$ip}{timestamp};
652      $year += 1900;
653      $mon++;
654      my $date = sprintf '%04i-%02i-%02i %02i:%02i', $year, $mon, $mday, $hour, $min;
655
656      printf "%-22s %2s %-30s %-15s %-18s %s\n",
657         $computerdb->{$ip}{switch_name},
658         $computerdb->{$ip}{switch_port},
659         $computerdb->{$ip}{hostname_fq},
660         $ip,
661         $computerdb->{$ip}{mac_address},
662         $date;
663      }
664   return;
665   }
666
667sub cmd_updatedb {
668   my @network = @_;
669      @network = get_list_network() if not @network;
670
671   test_switchdb_environnement();
672
673   my $computerdb = {};
674      $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE") if -e "$KLASK_DB_FILE";
675   my $timestamp = time;
676
677   my %computer_not_detected = ();
678   my $timestamp_last_week = $timestamp - (3600 * 24 * 7);
679
680   my $number_of_computer = get_list_ip(@network); # + 1;
681   my $size_of_database   = keys %{$computerdb};
682      $size_of_database   = 1 if $size_of_database == 0;
683   my $i = 0;
684   my $detected_computer = 0;
685
686   init_switch_names('yes');    #nomme les switchs
687
688   { # Remplis le champs portignore des ports d'inter-connection pour chaque switch
689   my $switch_connection = YAML::Syck::LoadFile("$KLASK_SW_FILE");
690   my %db_switch_output_port       = %{$switch_connection->{output_port}};
691   my %db_switch_connected_on_port = %{$switch_connection->{connected_on_port}};
692   my %db_switch_chained_port = ();
693   for my $swport (keys %db_switch_connected_on_port) {
694      my ($sw_connect,$port_connect) = split m/ : /xms, $swport;
695      $db_switch_chained_port{$sw_connect} .= "$port_connect:";
696      }
697   for my $sw (@SWITCH){
698      push @{$sw->{portignore}}, $db_switch_output_port{$sw->{hostname}}  if exists $db_switch_output_port{$sw->{hostname}};
699      if ( exists $db_switch_chained_port{$sw->{hostname}} ) {
700         chop $db_switch_chained_port{$sw->{hostname}};
701         push @{$sw->{portignore}}, split m/ : /xms, $db_switch_chained_port{$sw->{hostname}};
702         }
703#      print "$sw->{hostname} ++ @{$sw->{portignore}}\n";
704      }
705   }
706
707   my %router_mac_ip = ();
708   DETECT_ALL_ROUTER:
709#   for my $one_router ('194.254.66.254') {
710   for my $one_router ( get_list_main_router(@network) ) {
711      my %resol_arp = resolve_ip_arp_host($one_router);
712      $router_mac_ip{ $resol_arp{mac_address} } = $resol_arp{ipv4_address};
713      }
714
715   ALL_NETWORK:
716   for my $net (@network) {
717
718      my @computer = get_list_ip($net);
719      my $current_interface = get_current_interface($net);
720
721      fastping(@computer);
722
723      LOOP_ON_COMPUTER:
724      for my $one_computer (@computer) {
725         $i++;
726
727         my $total_percent = int (($i*100)/$number_of_computer);
728
729         my $localtime = time - $timestamp;
730         my ($sec,$min) = localtime $localtime;
731
732         my $time_elapse = 0;
733            $time_elapse = $localtime * ( 100 - $total_percent) / $total_percent if $total_percent != 0;
734         my ($sec_elapse,$min_elapse) = localtime $time_elapse;
735
736         printf "\rComputer scanned: %4i/%i (%2i%%)",  $i,                 $number_of_computer, $total_percent;
737#         printf ", Computer detected: %4i/%i (%2i%%)", $detected_computer, $size_of_database,   int(($detected_computer*100)/$size_of_database);
738         printf ', detected: %4i/%i (%2i%%)', $detected_computer, $size_of_database,   int(($detected_computer*100)/$size_of_database);
739         printf ' [Time: %02i:%02i / %02i:%02i]', int($localtime/60), $localtime % 60, int($time_elapse/60), $time_elapse % 60;
740#         printf '  [%02i:%02i/%02i:%02i]', int($localtime/60), $localtime % 60, int($time_elapse/60), $time_elapse % 60;
741         printf ' %-14s', $one_computer;
742
743         my %resol_arp = resolve_ip_arp_host($one_computer,$current_interface);
744
745         # do not search on router connection (why ?)
746         if ( exists $router_mac_ip{$resol_arp{mac_address}}) {
747            $computer_not_detected{$one_computer} = $current_interface;
748            next LOOP_ON_COMPUTER;
749            }
750
751         # do not search on switch inter-connection
752         if (exists $switch_level{$resol_arp{hostname_fq}}) {
753            $computer_not_detected{$one_computer} = $current_interface;
754            next LOOP_ON_COMPUTER;
755            }
756
757         my $switch_proposal = q{};
758         if (exists $computerdb->{$resol_arp{ipv4_address}} and exists $computerdb->{$resol_arp{ipv4_address}}{switch_hostname}) {
759            $switch_proposal = $computerdb->{$resol_arp{ipv4_address}}{switch_hostname};
760            }
761
762         # do not have a mac address
763         if ($resol_arp{mac_address} eq 'unknow' or (exists $resol_arp{timestamps} and $resol_arp{timestamps} < ($timestamp - 3 * 3600))) {
764            $computer_not_detected{$one_computer} = $current_interface;
765            next LOOP_ON_COMPUTER;
766            }
767
768         my %where = find_switch_port($resol_arp{mac_address},$switch_proposal);
769
770         #192.168.24.156:
771         #  arp: 00:0B:DB:D5:F6:65
772         #  hostname: pcroyon.hmg.priv
773         #  port: 5
774         #  switch: sw-batH-legi:hp2524
775         #  timestamp: 1164355525
776
777         # do not have a mac address
778#         if ($resol_arp{mac_address} eq 'unknow') {
779#            $computer_not_detected{$one_computer} = $current_interface;
780#            next LOOP_ON_COMPUTER;
781#            }
782
783         # detected on a switch
784         if ($where{switch_description} ne 'unknow') {
785            $detected_computer++;
786            $computerdb->{$resol_arp{ipv4_address}} = {
787               hostname_fq        => $resol_arp{hostname_fq},
788               mac_address        => $resol_arp{mac_address},
789               switch_hostname    => $where{switch_hostname},
790               switch_description => $where{switch_description},
791               switch_port        => $where{switch_port},
792               timestamp          => $timestamp,
793               network            => $net,
794               };
795            next LOOP_ON_COMPUTER;
796            }
797
798         # new in the database but where it is ?
799         if (not exists $computerdb->{$resol_arp{ipv4_address}}) {
800            $detected_computer++;
801            $computerdb->{$resol_arp{ipv4_address}} = {
802               hostname_fq        => $resol_arp{hostname_fq},
803               mac_address        => $resol_arp{mac_address},
804               switch_hostname    => $where{switch_hostname},
805               switch_description => $where{switch_description},
806               switch_port        => $where{switch_port},
807               timestamp          => $resol_arp{timestamp},
808               network            => $net,
809               };
810            }
811
812         # mise a jour du nom de la machine si modification dans le dns
813         $computerdb->{$resol_arp{ipv4_address}}{hostname_fq} = $resol_arp{hostname_fq};
814
815         # mise à jour de la date de détection si détection plus récente par arpwatch
816         $computerdb->{$resol_arp{ipv4_address}}{timestamp}   = $resol_arp{timestamp} if exists $resol_arp{timestamp} and $computerdb->{$resol_arp{ipv4_address}}{timestamp} < $resol_arp{timestamp};
817
818         # relance un arping sur la machine si celle-ci n'a pas été détectée depuis plus d'une semaine
819#         push @computer_not_detected, $resol_arp{ipv4_address} if $computerdb->{$resol_arp{ipv4_address}}{timestamp} < $timestamp_last_week;
820         $computer_not_detected{$resol_arp{ipv4_address}} = $current_interface if $computerdb->{$resol_arp{ipv4_address}}{timestamp} < $timestamp_last_week;
821
822         }
823      }
824
825   # final end of line at the end of the loop
826   printf "\n";
827
828   my $dirdb = $KLASK_DB_FILE;
829      $dirdb =~ s{ / [^/]* $}{}xms;
830   mkdir "$dirdb", 0755 unless -d "$dirdb";
831   YAML::Syck::DumpFile("$KLASK_DB_FILE", $computerdb);
832
833   for my $one_computer (keys %computer_not_detected) {
834      my $interface = $computer_not_detected{$one_computer};
835      system "arping -c 1 -w 1 -rR -i $interface $one_computer &>/dev/null";
836#      print  "arping -c 1 -w 1 -rR -i $interface $one_computer 2>/dev/null\n";
837      }
838   return;
839   }
840
841sub cmd_removedb {
842   my @computer = @_;
843
844   test_maindb_environnement();
845
846   my $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE");
847
848   LOOP_ON_COMPUTER:
849   for my $one_computer (@computer) {
850
851      if ( $one_computer =~ m/^ $RE_IPv4_ADDRESS $/xms
852            and exists $computerdb->{$one_computer} ) {
853         delete $computerdb->{$one_computer};
854         next;
855         }
856
857      my %resol_arp = resolve_ip_arp_host($one_computer);
858
859      delete $computerdb->{$resol_arp{ipv4_address}} if exists $computerdb->{$resol_arp{ipv4_address}};
860      }
861
862   my $dirdb = $KLASK_DB_FILE;
863      $dirdb =~ s{ / [^/]* $}{}xms;
864   mkdir "$dirdb", 0755 unless -d "$dirdb";
865   YAML::Syck::DumpFile("$KLASK_DB_FILE", $computerdb);
866   return;
867   }
868
869sub cmd_cleandb {
870   my @options = @_;
871
872   my $days_to_clean = 15;
873   my $verbose;
874   my $database_has_changed;
875
876   my $ret = GetOptionsFromArray(\@options,
877      'day|d=i'   => \$days_to_clean,
878      'verbose|v' => \$verbose,
879      );
880
881   my @vlan_name = get_list_network();
882
883   my $computerdb = {};
884      $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE") if -e "$KLASK_DB_FILE";
885   my $timestamp = time;
886
887   my $timestamp_barrier = 3600 * 24 * $days_to_clean;
888
889   ALL_VLAN:
890   for my $vlan (@vlan_name) {
891
892      my @ip_list   = get_list_ip($vlan);
893      my %mactimedb = ();
894     
895      LOOP_ON_IP_ADDRESS:
896      for my $ip (@ip_list) {
897
898         next LOOP_ON_IP_ADDRESS if
899            not exists $computerdb->{$ip};
900           
901            #&& $computerdb->{$ip}{timestamp} > $timestamp_barrier;
902         my $ip_timestamp = $computerdb->{$ip}{timestamp};
903         my $ip_mac       = $computerdb->{$ip}{mac_address};
904         
905         $mactimedb{$ip_mac} ||= [ $ip, $ip_timestamp ];
906         
907         if ( $mactimedb{$ip_mac}->[1] - $ip_timestamp > $timestamp_barrier ) {
908            print "remove ip $ip\n" if $verbose;
909            delete $computerdb->{$ip};
910            $database_has_changed++;
911            }
912
913         if ( $ip_timestamp - $mactimedb{$ip_mac}->[1] > $timestamp_barrier ) {
914            print "remove ip ".$mactimedb{$ip_mac}->[0]."\n" if $verbose;
915            delete $computerdb->{$mactimedb{$ip_mac}->[0]};
916            $database_has_changed++;
917            }
918
919         if ( $ip_timestamp > $mactimedb{$ip_mac}->[1]) {
920            $mactimedb{$ip_mac} = [ $ip, $ip_timestamp ];
921            }
922         }
923      }
924
925   if ( $database_has_changed ) {
926      my $dirdb = $KLASK_DB_FILE;
927         $dirdb =~ s{ / [^/]* $}{}xms;
928      mkdir "$dirdb", 0755 unless -d "$dirdb";
929      YAML::Syck::DumpFile("$KLASK_DB_FILE", $computerdb);
930      }
931   return;
932   }
933
934sub cmd_exportdb {
935   my @ARGV   = @_;
936
937   my $format = 'txt';
938
939   my $ret = GetOptions(
940      'format|f=s'  => \$format,
941      );
942
943   my %possible_format = (
944      txt  => \&cmd_exportdb_txt,
945      html => \&cmd_exportdb_html,
946      );
947
948   $format = 'txt' if not defined $possible_format{$format};
949
950   $possible_format{$format}->(@ARGV);
951   return;
952   }
953
954sub cmd_exportdb_txt {
955   test_maindb_environnement();
956
957   my $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE");
958
959   printf "%-26s %-4s            %-40s %-15s %-18s %-16s %s\n", qw(Switch Port Hostname-FQ IPv4-Address MAC-Address Date VLAN);
960   print "--------------------------------------------------------------------------------------------------------------------------------------------\n";
961
962   LOOP_ON_IP_ADDRESS:
963   foreach my $ip (Net::Netmask::sort_by_ip_address(keys %{$computerdb})) {
964
965#      next LOOP_ON_IP_ADDRESS if $computerdb->{$ip}{hostname_fq} eq 'unknow';
966
967      # to be improve in the future
968      next LOOP_ON_IP_ADDRESS if $computerdb->{$ip}{hostname_fq} eq ($computerdb->{$ip}{switch_hostname} || $computerdb->{$ip}{switch_description}); # switch on himself !
969
970# dans le futur
971#      next if $computerdb->{$ip}{hostname_fq} eq 'unknow';
972
973      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $computerdb->{$ip}{timestamp};
974      $year += 1900;
975      $mon++;
976      my $date = sprintf '%04i-%02i-%02i %02i:%02i', $year, $mon, $mday, $hour, $min;
977
978      printf "%-27s  %2s  <-------  %-40s %-15s %-18s %-16s %s\n",
979         $computerdb->{$ip}{switch_hostname} || $computerdb->{$ip}{switch_description},
980         $computerdb->{$ip}{switch_port},
981         $computerdb->{$ip}{hostname_fq},
982         $ip,
983         $computerdb->{$ip}{mac_address},
984         $date,
985         $computerdb->{$ip}{network} || '';
986      }
987   return;
988   }
989
990sub cmd_exportdb_html {
991   test_maindb_environnement();
992
993   my $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE");
994
995#<link rel="stylesheet" type="text/css" href="style-klask.css" />
996#<script src="sorttable-klask.js"></script>
997
998   print <<'END_HTML';
999<table class="sortable" summary="Klask Host Database">
1000 <caption>Klask Host Database</caption>
1001 <thead>
1002  <tr>
1003   <th scope="col" class="klask-header-left">Switch</th>
1004   <th scope="col" class="sorttable_nosort">Port</th>
1005   <th scope="col" class="sorttable_nosort">Link</th>
1006   <th scope="col" class="sorttable_alpha">Hostname-FQ</th>
1007   <th scope="col" class="hklask-ipv4">IPv4-Address</th>
1008   <th scope="col" class="sorttable_alpha">MAC-Address</th>
1009   <th scope="col" class="sorttable_alpha">VLAN</th>
1010   <th scope="col" class="klask-header-right">Date</th>
1011  </tr>
1012 </thead>
1013 <tfoot>
1014  <tr>
1015   <th scope="col" class="klask-footer-left">Switch</th>
1016   <th scope="col" class="fklask-port">Port</th>
1017   <th scope="col" class="fklask-link">Link</th>
1018   <th scope="col" class="fklask-hostname">Hostname-FQ</th>
1019   <th scope="col" class="fklask-ipv4">IPv4-Address</th>
1020   <th scope="col" class="fklask-mac">MAC-Address</th>
1021   <th scope="col" class="fklask-vlan">VLAN</th>
1022   <th scope="col" class="klask-footer-right">Date</th>
1023  </tr>
1024 </tfoot>
1025 <tbody>
1026END_HTML
1027
1028   my %mac_count = ();
1029   LOOP_ON_IP_ADDRESS:
1030   foreach my $ip (keys %{$computerdb}) {
1031
1032      # to be improve in the future
1033      next LOOP_ON_IP_ADDRESS if $computerdb->{$ip}{hostname_fq} eq ($computerdb->{$ip}{switch_hostname} || $computerdb->{$ip}{switch_description}); # switch on himself !
1034
1035      $mac_count{$computerdb->{$ip}{mac_address}}++;
1036      }
1037
1038   my $typerow = 'even';
1039
1040   LOOP_ON_IP_ADDRESS:
1041   foreach my $ip (Net::Netmask::sort_by_ip_address(keys %{$computerdb})) {
1042
1043      # to be improve in the future
1044      next LOOP_ON_IP_ADDRESS if $computerdb->{$ip}{hostname_fq} eq ($computerdb->{$ip}{switch_hostname} || $computerdb->{$ip}{switch_description}); # switch on himself !
1045
1046      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $computerdb->{$ip}{timestamp};
1047      $year += 1900;
1048      $mon++;
1049      my $date = sprintf '%04i-%02i-%02i %02i:%02i', $year, $mon, $mday, $hour, $min;
1050
1051#      $odd_or_even++;
1052#      my $typerow = $odd_or_even % 2 ? 'odd' : 'even';
1053      $typerow = $typerow eq 'even' ? 'odd' : 'even';
1054
1055      my $switch_hostname = $computerdb->{$ip}{switch_hostname} || $computerdb->{$ip}{switch_description} || 'unkown';
1056      chomp $switch_hostname;
1057      my $switch_hostname_sort = sprintf '%s %3s' ,$switch_hostname, $computerdb->{$ip}{switch_port};
1058
1059      my $ip_sort = sprintf '%03i%03i%03i%03i', split m/ \. /xms, $ip;
1060
1061      my $mac_sort = sprintf '%04i-%s', 9999 - $mac_count{$computerdb->{$ip}{mac_address}}, $computerdb->{$ip}{mac_address};
1062
1063      $computerdb->{$ip}{hostname_fq} = 'unknow' if $computerdb->{$ip}{hostname_fq} =~ m/^ \d+ \. \d+ \. \d+ \. \d+ $/xms;
1064      my ( $host_short ) = split m/ \. /xms, $computerdb->{$ip}{hostname_fq};
1065
1066      my $vlan = $computerdb->{$ip}{network} || '';
1067
1068      print <<"END_HTML";
1069  <tr class="$typerow">
1070   <td sorttable_customkey="$switch_hostname_sort">$switch_hostname</td>
1071   <td class="bklask-port">$computerdb->{$ip}{switch_port}</td>
1072   <td><-------</td>
1073   <td sorttable_customkey="$host_short">$computerdb->{$ip}{hostname_fq}</td>
1074   <td sorttable_customkey="$ip_sort">$ip</td>
1075   <td sorttable_customkey="$mac_sort">$computerdb->{$ip}{mac_address}</td>
1076   <td>$vlan</td>
1077   <td>$date</td>
1078  </tr>
1079END_HTML
1080      }
1081
1082   my $switch_connection = YAML::Syck::LoadFile("$KLASK_SW_FILE");
1083
1084   my %db_switch_output_port       = %{$switch_connection->{output_port}};
1085   my %db_switch_parent            = %{$switch_connection->{parent}};
1086   my %db_switch_connected_on_port = %{$switch_connection->{connected_on_port}};
1087   my %db_switch                   = %{$switch_connection->{switch_db}};
1088
1089   for my $sw (sort keys %db_switch_output_port) {
1090
1091      my $switch_hostname_sort = sprintf '%s %3s' ,$sw, $db_switch_output_port{$sw};
1092
1093      $typerow = $typerow eq 'even' ? 'odd' : 'even';
1094
1095      if (exists $db_switch_parent{$sw}) {
1096
1097      my $mac_address = $db_switch{$db_switch_parent{$sw}->{switch}}->{mac_address};
1098      my $ipv4_address = $db_switch{$db_switch_parent{$sw}->{switch}}->{ipv4_address};
1099      my $timestamp = $db_switch{$db_switch_parent{$sw}->{switch}}->{timestamp};
1100
1101      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $timestamp;
1102      $year += 1900;
1103      $mon++;
1104      my $date = sprintf '%04i-%02i-%02i %02i:%02i', $year, $mon, $mday, $hour, $min;
1105
1106      my $ip_sort = sprintf '%03i%03i%03i%03i', split m/ \. /xms, $ipv4_address;
1107
1108      my $mac_sort = sprintf '%04i-%s', 9999, $mac_address;
1109
1110      my ( $host_short ) = sprintf '%s %3s' , split(m/ \. /xms, $db_switch_parent{$sw}->{switch}, 1), $db_switch_parent{$sw}->{port};
1111
1112      print <<"END_HTML";
1113  <tr class="$typerow">
1114   <td sorttable_customkey="$switch_hostname_sort">$sw</td>
1115   <td class="bklask-port">$db_switch_output_port{$sw}</>
1116   <td>+--> $db_switch_parent{$sw}->{port}</td>
1117   <td sorttable_customkey="$host_short">$db_switch_parent{$sw}->{switch}</>
1118   <td sorttable_customkey="$ip_sort">$ipv4_address</td>
1119   <td sorttable_customkey="$mac_sort">$mac_address</td>
1120   <td></td>
1121   <td>$date</td>
1122  </tr>
1123END_HTML
1124         }
1125      else {
1126         print <<"END_HTML";
1127  <tr class="$typerow">
1128   <td sorttable_customkey="$switch_hostname_sort">$sw</td>
1129   <td class="bklask-port">$db_switch_output_port{$sw}</>
1130   <td>+--></td>
1131   <td sorttable_customkey="router">router</>
1132   <td sorttable_customkey="999999999999"></td>
1133   <td sorttable_customkey="99999"></td>
1134   <td></td>
1135   <td></td>
1136  </tr>
1137END_HTML
1138         }
1139      }
1140
1141   for my $swport (sort keys %db_switch_connected_on_port) {
1142      my ($sw_connect,$port_connect) = split m/ : /xms, $swport;
1143      for my $sw (keys %{$db_switch_connected_on_port{$swport}}) {
1144
1145         my $switch_hostname_sort = sprintf '%s %3s' ,$sw_connect, $port_connect;
1146
1147      my $mac_address = $db_switch{$sw}->{mac_address};
1148      my $ipv4_address = $db_switch{$sw}->{ipv4_address};
1149      my $timestamp = $db_switch{$sw}->{timestamp};
1150
1151      my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $timestamp;
1152      $year += 1900;
1153      $mon++;
1154      my $date = sprintf '%04i-%02i-%02i %02i:%02i', $year,$mon,$mday,$hour,$min;
1155
1156      my $ip_sort = sprintf '%03i%03i%03i%03i', split m/ \. /xms, $ipv4_address;
1157
1158      my $mac_sort = sprintf '%04i-%s', 9999, $mac_address;
1159
1160      $typerow = $typerow eq 'even' ? 'odd' : 'even';
1161
1162         if (exists $db_switch_output_port{$sw}) {
1163
1164            my ( $host_short ) = sprintf '%s %3s' , split( m/\./xms, $sw, 1), $db_switch_output_port{$sw};
1165
1166            print <<"END_HTML";
1167  <tr class="$typerow">
1168   <td sorttable_customkey="$switch_hostname_sort">$sw_connect</td>
1169   <td class="bklask-port">$port_connect</>
1170   <td>&lt;--+ $db_switch_output_port{$sw}</td>
1171   <td sorttable_customkey="$host_short">$sw</>
1172   <td sorttable_customkey="$ip_sort">$ipv4_address</td>
1173   <td sorttable_customkey="$mac_sort">$mac_address</td>
1174   <td></td>
1175   <td>$date</td>
1176  </tr>
1177END_HTML
1178            }
1179         else {
1180            print <<"END_HTML";
1181  <tr class="$typerow">
1182   <td sorttable_customkey="$switch_hostname_sort">$sw_connect</td>
1183   <td class="bklask-port">$port_connect</>
1184   <td>&lt;--+</td>
1185   <td sorttable_customkey="$sw">$sw</>
1186   <td sorttable_customkey="">$ipv4_address</td>
1187   <td sorttable_customkey="">$mac_address</td>
1188   <td></td>
1189   <td>$date</td>
1190  </tr>
1191END_HTML
1192            }
1193         }
1194      }
1195
1196   print <<'END_HTML';
1197 </tbody>
1198</table>
1199END_HTML
1200   return;
1201   }
1202
1203sub cmd_iplocation {
1204   my $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE");
1205
1206   LOOP_ON_IP_ADDRESS:
1207   foreach my $ip (Net::Netmask::sort_by_ip_address(keys %{$computerdb})) {
1208
1209      next LOOP_ON_IP_ADDRESS if $computerdb->{$ip}{hostname_fq} eq ($computerdb->{$ip}{switch_hostname} || $computerdb->{$ip}{switch_description}); # switch on himself !
1210
1211      my $sw_hostname = $computerdb->{$ip}{switch_hostname} || q{};
1212      next if $sw_hostname eq 'unknow';
1213
1214      my $sw_location = q{};
1215      for my $sw (@SWITCH) {
1216         next if $sw_hostname ne $sw->{hostname};
1217         $sw_location = $sw->{location};
1218         last;
1219         }
1220
1221      printf "%s: \"%s\"\n", $ip, $sw_location if not $sw_location eq q{};
1222      }
1223   return;
1224   }
1225
1226sub cmd_ip_free {
1227   my @vlan_name = @_;
1228
1229   my $days_to_dead = 365 * 2;
1230   my $format = 'txt';
1231
1232   my $ret = GetOptionsFromArray(\@vlan_name,
1233      'day|d=i'      => \$days_to_dead,
1234      'format|f=s'   => \$format,
1235      );
1236
1237   my %possible_format = (
1238      txt  => \&cmd_ip_free_txt,
1239      html => \&cmd_ip_free_html,
1240      );
1241   $format = 'txt' if not defined $possible_format{$format};
1242
1243   @vlan_name = get_list_network() if not @vlan_name;
1244
1245   my $computerdb = {};
1246      $computerdb = YAML::Syck::LoadFile("$KLASK_DB_FILE") if -e "$KLASK_DB_FILE";
1247   my $timestamp = time;
1248
1249   my $timestamp_barrier = $timestamp - (3600 * 24 * $days_to_dead );
1250
1251   my %result_ip = ();
1252
1253   ALL_NETWORK:
1254   for my $vlan (@vlan_name) {
1255
1256      my @ip_list = get_list_ip($vlan);
1257#      my $current_interface = get_current_interface($vlan);
1258     
1259      LOOP_ON_IP_ADDRESS:
1260      for my $ip (@ip_list) {
1261
1262         next LOOP_ON_IP_ADDRESS if
1263            exists $computerdb->{$ip}
1264            && $computerdb->{$ip}{timestamp} > $timestamp_barrier;
1265
1266         my $ip_date_last_detection = '';
1267         if (exists $computerdb->{$ip}) {
1268            my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime $computerdb->{$ip}{timestamp};
1269            $year += 1900;
1270            $mon++;
1271            $ip_date_last_detection = sprintf '%04i-%02i-%02i %02i:%02i', $year, $mon, $mday, $hour, $min;
1272            }
1273
1274         $result_ip{$ip} ||= {};
1275         $result_ip{$ip}->{date_last_detection} = $ip_date_last_detection;
1276
1277         my $packed_ip = scalar gethostbyname($ip);
1278         my $hostname_fq = 'unknown';
1279            $hostname_fq = scalar gethostbyaddr($packed_ip, AF_INET) || 'unknown' if defined $packed_ip;
1280         $result_ip{$ip}->{hostname_fq} = $hostname_fq;
1281         
1282         $result_ip{$ip}->{vlan} = $vlan;
1283         }
1284      }
1285
1286   $possible_format{$format}->(%result_ip);
1287   }
1288
1289sub cmd_ip_free_txt {
1290   my %result_ip = @_;
1291   
1292   printf "%-15s %-40s %-16s %s\n", qw(IPv4-Address Hostname-FQ Date VLAN);
1293   print "-------------------------------------------------------------------------------\n";
1294   LOOP_ON_IP_ADDRESS:
1295   foreach my $ip (Net::Netmask::sort_by_ip_address(keys %result_ip)) {
1296         printf "%-15s %-40s %-16s %s\n", $ip, $result_ip{$ip}->{hostname_fq}, $result_ip{$ip}->{date_last_detection}, $result_ip{$ip}->{vlan};
1297      }
1298   }
1299
1300sub cmd_ip_free_html {
1301   my %result_ip = @_;
1302
1303   print <<'END_HTML';
1304<table class="sortable" summary="Klask Free IP Database">
1305 <caption>Klask Free IP Database</caption>
1306 <thead>
1307  <tr>
1308   <th scope="col" class="klask-header-left">IPv4-Address</th>
1309   <th scope="col" class="sorttable_alpha">Hostname-FQ</th>
1310   <th scope="col" class="sorttable_alpha">VLAN</th>
1311   <th scope="col" class="klask-header-right">Date</th>
1312  </tr>
1313 </thead>
1314 <tfoot>
1315  <tr>
1316   <th scope="col" class="klask-footer-left">IPv4-Address</th>
1317   <th scope="col" class="fklask-hostname">Hostname-FQ</th>
1318   <th scope="col" class="fklask-vlan">VLAN</th>
1319   <th scope="col" class="klask-footer-right">Date</th>
1320  </tr>
1321 </tfoot>
1322 <tbody>
1323END_HTML
1324
1325   my $typerow = 'even';
1326
1327   LOOP_ON_IP_ADDRESS:
1328   foreach my $ip (Net::Netmask::sort_by_ip_address(keys %result_ip)) {
1329
1330      $typerow = $typerow eq 'even' ? 'odd' : 'even';
1331
1332      my $ip_sort = sprintf '%03i%03i%03i%03i', split m/ \. /xms, $ip;
1333      my ( $host_short ) = split m/ \. /xms, $result_ip{$ip}->{hostname_fq};
1334
1335      print <<"END_HTML";
1336  <tr class="$typerow">
1337   <td sorttable_customkey="$ip_sort">$ip</td>
1338   <td sorttable_customkey="$host_short">$result_ip{$ip}->{hostname_fq}</td>
1339   <td>$result_ip{$ip}->{vlan}</td>
1340   <td>$result_ip{$ip}->{date_last_detection}</td>
1341  </tr>
1342END_HTML
1343      }
1344   print <<'END_HTML';
1345 </tbody>
1346</table>
1347END_HTML
1348   }
1349
1350sub cmd_enable {
1351   my $switch = shift;
1352   my $port   = shift;
1353
1354   #snmpset -v 1 -c community X.X.X.X 1.3.6.1.2.1.2.2.1.7.NoPort = 1 (up)
1355   #snmpset -v 1 -c community X.X.X.X 1.3.6.1.2.1.2.2.1.7.NoPort = 2 (down)
1356   system "snmpset -v 1 -c public $switch 1.3.6.1.2.1.2.2.1.7.$port = 1";
1357   return;
1358   }
1359
1360sub cmd_disable {
1361   my $switch = shift;
1362   my $port   = shift;
1363
1364   system "snmpset -v 1 -c public $switch 1.3.6.1.2.1.2.2.1.7.$port = 2";
1365   return;
1366   }
1367
1368sub cmd_status {
1369   my $switch = shift;
1370   my $port   = shift;
1371
1372   system "snmpget -v 1 -c public $switch 1.3.6.1.2.1.2.2.1.7.$port";
1373   return;
1374   }
1375
1376sub cmd_search_mac_on_switch {
1377   my $switch_name = shift || q{};
1378   my $mac_address = shift || q{};
1379
1380   if ($switch_name eq q{} or $mac_address eq q{}) {
1381      die "Usage: klask search-mac-on-switch SWITCH_NAME MAC_ADDRESS\n";
1382      }
1383
1384   if (not defined $SWITCH_DB{$switch_name}) {
1385      die "Switch $switch_name must be defined in klask configuration file\n";
1386      }
1387
1388   my $sw = $SWITCH_DB{$switch_name};
1389   my %session = ( -hostname => $sw->{hostname} );
1390      $session{-version} = $sw->{version}   || 1;
1391      $session{-port}    = $sw->{snmpport}  || $DEFAULT{snmpport}  || 161;
1392   if (exists $sw->{version} and $sw->{version} eq '3') {
1393      $session{-username} = $sw->{username} || 'snmpadmin';
1394      }
1395   else {
1396      $session{-community} = $sw->{community} || $DEFAULT{community} || 'public';
1397      }
1398
1399   my $research = '1.3.6.1.2.1.17.4.3.1.2' . arp_hex_to_dec($mac_address);
1400   print "Klask search OID $research on switch $switch_name\n";
1401
1402   my ($session, $error) = Net::SNMP->session( %session );
1403   print "$error \n" if $error;
1404
1405   my $result = $session->get_request(
1406      -varbindlist => [$research]
1407      );
1408
1409   if (not defined $result or $result->{$research} eq 'noSuchInstance') {
1410      print "Klask do not find MAC $mac_address on switch $switch_name\n";
1411      $session->close;
1412      }
1413
1414   my $swport = $result->{$research};
1415   $session->close;
1416
1417   print "Klask find MAC $mac_address on switch $switch_name port $swport\n";
1418   return;
1419   }
1420
1421sub cmd_updatesw {
1422   my @options = @_;
1423
1424   my $verbose;
1425
1426   my $ret = GetOptionsFromArray(\@options,
1427      'verbose|v' => \$verbose,
1428      );
1429
1430   init_switch_names('yes');    #nomme les switchs
1431   print "\n";
1432
1433   my %where = ();
1434   my %db_switch_output_port = ();
1435   my %db_switch_ip_hostname = ();
1436
1437   DETECT_ALL_ROUTER:
1438#   for my $one_computer ('194.254.66.254') {
1439   for my $one_router ( get_list_main_router(get_list_network()) ) {
1440      my %resol_arp = resolve_ip_arp_host($one_router, q{*}, q{low}); # resolution arp
1441      next DETECT_ALL_ROUTER if $resol_arp{mac_address} eq 'unknow';
1442      $where{$resol_arp{ipv4_address}} = find_all_switch_port($resol_arp{mac_address}); # retrouve les emplacements des routeurs
1443      print "VERBOSE_1: Router detected $resol_arp{ipv4_address} - $resol_arp{mac_address}\n" if $verbose;
1444      }
1445
1446   ALL_ROUTER_IP_ADDRESS:
1447   for my $ip (Net::Netmask::sort_by_ip_address(keys %where)) { # '194.254.66.254')) {
1448
1449      next ALL_ROUTER_IP_ADDRESS if not exists $where{$ip}; # /a priori/ idiot car ne sers à rien...
1450
1451      ALL_SWITCH_CONNECTED:
1452      for my $switch_detected ( keys %{$where{$ip}} ) {
1453
1454         my $switch = $where{$ip}->{$switch_detected};
1455
1456         next ALL_SWITCH_CONNECTED if $switch->{port} eq '0';
1457
1458         $db_switch_output_port{$switch->{hostname}} = $switch->{port};
1459         print "VERBOSE_2: output port $switch->{hostname} : $switch->{port}\n" if $verbose;
1460         }
1461      }
1462
1463   my %db_switch_link_with = ();
1464
1465   my @list_switch_ip = ();
1466   my @list_switch_ipv4 = ();
1467   for my $sw (@SWITCH){
1468      push @list_switch_ip, $sw->{hostname};
1469      }
1470
1471   my $timestamp = time;
1472
1473   ALL_SWITCH:
1474   for my $one_computer (@list_switch_ip) {
1475      my %resol_arp = resolve_ip_arp_host($one_computer, q{*}, q{low}); # arp resolution
1476      next ALL_SWITCH if $resol_arp{mac_address} eq 'unknow';
1477
1478      push @list_switch_ipv4,$resol_arp{ipv4_address};
1479
1480      $where{$resol_arp{ipv4_address}} = find_all_switch_port($resol_arp{mac_address}); # find port on all switch
1481#my @l = ();
1482#for my $c  ( keys %{$where{$resol_arp{ipv4_address}}} ) {
1483#push @l, "$c -+ "; #$where{$resol_arp{ipv4_address}}->{$c}{hostname};
1484#}
1485#print "DEBUG  $one_computer $resol_arp{ipv4_address} $resol_arp{mac_address} --- @l\n";
1486
1487      $db_switch_ip_hostname{$resol_arp{ipv4_address}} = $resol_arp{hostname_fq};
1488
1489      $SWITCH_DB{$one_computer}->{ipv4_address} = $resol_arp{ipv4_address};
1490      $SWITCH_DB{$one_computer}->{mac_address}  = $resol_arp{mac_address};
1491      $SWITCH_DB{$one_computer}->{timestamp}    = $timestamp;
1492      }
1493
1494   ALL_SWITCH_IP_ADDRESS:
1495   for my $ip (Net::Netmask::sort_by_ip_address(@list_switch_ipv4)) {
1496
1497      next ALL_SWITCH_IP_ADDRESS if not exists $where{$ip};
1498
1499      DETECTED_SWITCH:
1500      for my $switch_detected ( keys %{$where{$ip}} ) {
1501
1502         next DETECTED_SWITCH if not exists $SWITCH_PORT_COUNT{ $db_switch_ip_hostname{$ip} };
1503
1504         my $switch = $where{$ip}->{$switch_detected};
1505#print "DEBUG1 :  $db_switch_ip_hostname{$ip} / $switch->{hostname} : $switch->{port}\n" if  $switch->{hostname} =~ m/sw3-batA0-3s/;
1506
1507         next if $switch->{port}     eq '0';
1508         next if $switch->{port}     eq $db_switch_output_port{$switch->{hostname}};
1509         next if $switch->{hostname} eq $db_switch_ip_hostname{$ip}; # $computerdb->{$ip}{hostname};
1510
1511         $db_switch_link_with{ $db_switch_ip_hostname{$ip} } ||= {};
1512         $db_switch_link_with{ $db_switch_ip_hostname{$ip} }->{ $switch->{hostname} } = $switch->{port};
1513         print "VERBOSE_3: $db_switch_ip_hostname{$ip} -> $switch->{hostname} : $switch->{port}\n" if $verbose;
1514#print "DEBUG :  $db_switch_ip_hostname{$ip} / $switch->{hostname} : $switch->{port}\n" if $switch->{hostname} !~ m/sw3-batA0-3s/;
1515         }
1516
1517      }
1518
1519   my %db_switch_connected_on_port = ();
1520   my $maybe_more_than_one_switch_connected = 'yes';
1521
1522   while ($maybe_more_than_one_switch_connected eq 'yes') {
1523      for my $sw (keys %db_switch_link_with) {
1524         for my $connect (keys %{$db_switch_link_with{$sw}}) {
1525
1526            my $port = $db_switch_link_with{$sw}->{$connect};
1527
1528            $db_switch_connected_on_port{"$connect:$port"} ||= {};
1529            $db_switch_connected_on_port{"$connect:$port"}->{$sw}++; # Just to define the key
1530            }
1531         }
1532
1533      $maybe_more_than_one_switch_connected  = 'no';
1534
1535      SWITCH_AND_PORT:
1536      for my $swport (keys %db_switch_connected_on_port) {
1537
1538         next if keys %{$db_switch_connected_on_port{$swport}} == 1;
1539
1540         $maybe_more_than_one_switch_connected = 'yes';
1541
1542         my ($sw_connect,$port_connect) = split m/ : /xms, $swport;
1543         my @sw_on_same_port = keys %{$db_switch_connected_on_port{$swport}};
1544
1545         CONNECTED:
1546         for my $sw_connected (@sw_on_same_port) {
1547
1548            next CONNECTED if not keys %{$db_switch_link_with{$sw_connected}} == 1;
1549
1550            $db_switch_connected_on_port{$swport} = {$sw_connected => 1};
1551
1552            for my $other_sw (@sw_on_same_port) {
1553               next if $other_sw eq $sw_connected;
1554
1555               delete $db_switch_link_with{$other_sw}->{$sw_connect};
1556               }
1557
1558            # We can not do better for this switch for this loop
1559            next SWITCH_AND_PORT;
1560            }
1561         }
1562      }
1563
1564   my %db_switch_parent =();
1565
1566   for my $sw (keys %db_switch_link_with) {
1567      for my $connect (keys %{$db_switch_link_with{$sw}}) {
1568
1569         my $port = $db_switch_link_with{$sw}->{$connect};
1570
1571         $db_switch_connected_on_port{"$connect:$port"} ||= {};
1572         $db_switch_connected_on_port{"$connect:$port"}->{$sw} = $port;
1573
1574         $db_switch_parent{$sw} = {switch => $connect, port => $port};
1575         }
1576      }
1577
1578   print "Switch output port and parent port connection\n";
1579   print "---------------------------------------------\n";
1580   for my $sw (sort keys %db_switch_output_port) {
1581      if (exists $db_switch_parent{$sw}) {
1582         printf "%-27s  %2s  +-->  %2s  %-25s\n", $sw, $db_switch_output_port{$sw}, $db_switch_parent{$sw}->{port}, $db_switch_parent{$sw}->{switch};
1583         }
1584      else {
1585         printf "%-27s  %2s  +-->  router\n", $sw, $db_switch_output_port{$sw};
1586         }
1587      }
1588   print "\n";
1589
1590   print "Switch parent and children port inter-connection\n";
1591   print "------------------------------------------------\n";
1592   for my $swport (sort keys %db_switch_connected_on_port) {
1593      my ($sw_connect,$port_connect) = split m/ : /xms, $swport;
1594      for my $sw (keys %{$db_switch_connected_on_port{$swport}}) {
1595         if (exists $db_switch_output_port{$sw}) {
1596            printf "%-27s  %2s  <--+  %2s  %-25s\n", $sw_connect, $port_connect, $db_switch_output_port{$sw}, $sw;
1597            }
1598         else {
1599            printf "%-27s  %2s  <--+      %-25s\n", $sw_connect, $port_connect, $sw;
1600            }
1601         }
1602      }
1603
1604   my $switch_connection = {
1605      output_port       => \%db_switch_output_port,
1606      parent            => \%db_switch_parent,
1607      connected_on_port => \%db_switch_connected_on_port,
1608      link_with         => \%db_switch_link_with,
1609      switch_db         => \%SWITCH_DB,
1610      };
1611
1612   YAML::Syck::DumpFile("$KLASK_SW_FILE", $switch_connection);
1613   return;
1614   }
1615
1616sub cmd_exportsw {
1617   my @ARGV   = @_;
1618
1619   test_switchdb_environnement();
1620
1621   my $format = 'txt';
1622
1623   my $ret = GetOptions(
1624      'format|f=s'  => \$format,
1625      );
1626
1627   my %possible_format = (
1628      txt => \&cmd_exportsw_txt,
1629      dot => \&cmd_exportsw_dot,
1630      );
1631
1632   $format = 'txt' if not defined $possible_format{$format};
1633
1634   $possible_format{$format}->(@ARGV);
1635   return;
1636   }
1637
1638sub cmd_exportsw_txt {
1639
1640   my $switch_connection = YAML::Syck::LoadFile("$KLASK_SW_FILE");
1641
1642   my %db_switch_output_port       = %{$switch_connection->{output_port}};
1643   my %db_switch_parent            = %{$switch_connection->{parent}};
1644   my %db_switch_connected_on_port = %{$switch_connection->{connected_on_port}};
1645
1646   print "Switch output port and parent port connection\n";
1647   print "---------------------------------------------\n";
1648   for my $sw (sort keys %db_switch_output_port) {
1649      if (exists $db_switch_parent{$sw}) {
1650         printf "%-27s  %2s  +-->  %2s  %-25s\n", $sw, $db_switch_output_port{$sw}, $db_switch_parent{$sw}->{port}, $db_switch_parent{$sw}->{switch};
1651         }
1652      else {
1653         printf "%-27s  %2s  +-->  router\n", $sw, $db_switch_output_port{$sw};
1654         }
1655      }
1656   print "\n";
1657
1658   print "Switch parent and children port inter-connection\n";
1659   print "------------------------------------------------\n";
1660   for my $swport (sort keys %db_switch_connected_on_port) {
1661      my ($sw_connect,$port_connect) = split m/ : /xms, $swport;
1662      for my $sw (keys %{$db_switch_connected_on_port{$swport}}) {
1663         if (exists $db_switch_output_port{$sw}) {
1664            printf "%-27s  %2s  <--+  %2s  %-25s\n", $sw_connect, $port_connect, $db_switch_output_port{$sw}, $sw;
1665            }
1666         else {
1667            printf "%-27s  %2s  <--+      %-25s\n", $sw_connect, $port_connect, $sw;
1668            }
1669         }
1670      }
1671   return;
1672   }
1673
1674sub cmd_exportsw_dot {
1675
1676   my $switch_connection = YAML::Syck::LoadFile("$KLASK_SW_FILE");
1677
1678   my %db_switch_output_port       = %{$switch_connection->{output_port}};
1679   my %db_switch_parent            = %{$switch_connection->{parent}};
1680   my %db_switch_connected_on_port = %{$switch_connection->{connected_on_port}};
1681   my %db_switch_link_with         = %{$switch_connection->{link_with}};
1682   my %db_switch_global            = %{$switch_connection->{switch_db}};
1683
1684   my %db_building= ();
1685   for my $sw (@SWITCH) {
1686      my ($building, $location) = split m/ \/ /xms, $sw->{location}, 2;
1687      $db_building{$building} ||= {};
1688      $db_building{$building}->{$location} ||= {};
1689      $db_building{$building}->{$location}{ $sw->{hostname} } = 'y';
1690      }
1691
1692
1693   print "digraph G {\n";
1694
1695   print "site [label = \"site\", color = black, fillcolor = gold, shape = invhouse, style = filled];\n";
1696   print "internet [label = \"internet\", color = black, fillcolor = cyan, shape = house, style = filled];\n";
1697
1698   my $b=0;
1699   for my $building (keys %db_building) {
1700      $b++;
1701
1702      print "\"building$b\" [label = \"$building\", color = black, fillcolor = gold, style = filled];\n";
1703      print "site -> \"building$b\" [len = 2, color = firebrick];\n";
1704
1705      my $l = 0;
1706      for my $loc (keys %{$db_building{$building}}) {
1707         $l++;
1708
1709         print "\"location$b-$l\" [label = \"$building" . q{/} . join(q{\n}, split(m{ / }xms, $loc)) . "\", color = black, fillcolor = orange, style = filled];\n";
1710#         print "\"location$b-$l\" [label = \"$building / $loc\", color = black, fillcolor = orange, style = filled];\n";
1711         print "\"building$b\" -> \"location$b-$l\" [len = 2, color = firebrick]\n";
1712
1713         for my $sw (keys %{$db_building{$building}->{$loc}}) {
1714
1715            print "\"$sw:$db_switch_output_port{$sw}\" [label = $db_switch_output_port{$sw}, color = black, fillcolor = lightblue,  peripheries = 2, style = filled];\n";
1716
1717            my $swname  = $sw;
1718               $swname .= q{\n-\n} . "$db_switch_global{$sw}->{model}" if exists $db_switch_global{$sw} and exists $db_switch_global{$sw}->{model};
1719            print "\"$sw\" [label = \"$swname\", color = black, fillcolor = palegreen, shape = rect, style = filled];\n";
1720            print "\"location$b-$l\" -> \"$sw\" [len = 2, color = firebrick, arrowtail = dot]\n";
1721            print "\"$sw\" -> \"$sw:$db_switch_output_port{$sw}\" [len=2, style=bold, arrowhead = normal, arrowtail = invdot]\n";
1722
1723
1724            for my $swport (keys %db_switch_connected_on_port) {
1725               my ($sw_connect,$port_connect) = split m/ : /xms, $swport;
1726               next if not $sw_connect eq $sw;
1727               next if $port_connect eq $db_switch_output_port{$sw};
1728               print "\"$sw:$port_connect\" [label = $port_connect, color = black, fillcolor = plum,  peripheries = 1, style = filled];\n";
1729               print "\"$sw:$port_connect\" -> \"$sw\" [len=2, style=bold, arrowhead= normal, arrowtail = inv]\n";
1730              }
1731            }
1732         }
1733      }
1734
1735#   print "Switch output port and parent port connection\n";
1736#   print "---------------------------------------------\n";
1737   for my $sw (sort keys %db_switch_output_port) {
1738      if (exists $db_switch_parent{$sw}) {
1739#         printf "   \"%s:%s\" -> \"%s:%s\"\n", $sw, $db_switch_output_port{$sw}, $db_switch_parent{$sw}->{switch}, $db_switch_parent{$sw}->{port};
1740         }
1741      else {
1742         printf "   \"%s:%s\" -> internet\n", $sw, $db_switch_output_port{$sw};
1743         }
1744      }
1745   print "\n";
1746
1747#   print "Switch parent and children port inter-connection\n";
1748#   print "------------------------------------------------\n";
1749   for my $swport (sort keys %db_switch_connected_on_port) {
1750      my ($sw_connect,$port_connect) = split m/ : /xms, $swport;
1751      for my $sw (keys %{$db_switch_connected_on_port{$swport}}) {
1752         if (exists $db_switch_output_port{$sw}) {
1753            printf "   \"%s:%s\" -> \"%s:%s\" [color = navyblue]\n", $sw, $db_switch_output_port{$sw}, $sw_connect, $port_connect;
1754            }
1755         else {
1756            printf "   \"%s\"   -> \"%s%s\"\n", $sw, $sw_connect, $port_connect;
1757            }
1758         }
1759      }
1760
1761print "}\n";
1762   return;
1763   }
1764
1765
1766__END__
1767
1768=head1 NAME
1769
1770klask - ports manager and finder for switch
1771
1772
1773=head1 USAGE
1774
1775 klask updatedb
1776 klask exportdb --format [txt|html]
1777 klask removedb computer*
1778 klask cleandb  --day number_of_day --verbose
1779
1780 klask updatesw
1781 klask exportsw --format [txt|dot]
1782
1783 klask searchdb computer
1784 klask search   computer
1785 klask search-mac-on-switch switch mac_addr
1786
1787 klask ip-free --day number_of_day --format [txt|html] [vlan_name]
1788
1789 klask enable  switch port
1790 klask disable swith port
1791 klask status  swith port
1792
1793
1794=head1 DESCRIPTION
1795
1796klask is a small tool to find where is a host in a big network. klask mean search in brittany.
1797
1798Klask has now a web site dedicated for it !
1799
1800 http://servforge.legi.inpg.fr/projects/klask
1801
1802
1803=head1 COMMANDS
1804
1805
1806=head2 search
1807
1808This command takes one or more computer in argument. It search a computer on the network and give the port and the switch on which the computer is connected.
1809
1810
1811=head2 enable
1812
1813This command activate a port on a switch by snmp. So you need to give the switch and the port number on the command line.
1814
1815
1816=head2 disable
1817
1818This command deactivate a port on a switch by snmp. So you need to give the switch and the port number on the command line.
1819
1820
1821=head2 status
1822
1823This command return the status of a port number on a switch by snmp. So you need to give the switch name and the port number on the command line.
1824
1825
1826=head2 updatedb
1827
1828This command will scan networks and update a database. To know which are the cmputer scan, you have to configure the file /etc/klask.conf This file is easy to read and write because klask use YAML format and not XML.
1829
1830
1831=head2 exportdb
1832
1833This command print the content of the database. There is actually only one format. It's very easy to have more format, it's just need times...
1834
1835
1836=head2 updatesw
1837
1838This command build a map of your manageable switch on your network. The list of the switch must be given in the file /etc/klask.conf.
1839
1840
1841=head2 exportsw --format [txt|dot]
1842
1843This command print the content of the switch database. There is actually two format. One is just txt for terminal and the other is the dot format from the graphviz environnement.
1844
1845 klask exportsw --format dot > /tmp/map.dot
1846 dot -Tpng /tmp/map.dot > /tmp/map.png
1847
1848
1849
1850=head1 CONFIGURATION
1851
1852Because klask need many parameters, it's not possible actually to use command line parameters. The configuration is done in a /etc/klask.conf YAML file. This format have many advantage over XML, it's easier to read and to write !
1853
1854Here an example, be aware with indent, it's important in YAML, do not use tabulation !
1855
1856 default:
1857   community: public
1858   snmpport: 161
1859
1860 network:
1861   labnet:
1862     ip-subnet:
1863       - add: 192.168.1.0/24
1864       - add: 192.168.2.0/24
1865     interface: eth0
1866     main-router: gw1.labnet.local
1867
1868   schoolnet:
1869     ip-subnet:
1870       - add: 192.168.6.0/24
1871       - add: 192.168.7.0/24
1872     interface: eth0.38
1873     main-router: gw2.schoolnet.local
1874
1875 switch:
1876   - hostname: sw1.klask.local
1877     portignore:
1878       - 1
1879       - 2
1880
1881   - hostname: sw2.klask.local
1882     location: BatK / 2 / K203
1883     type: HP2424
1884     portignore:
1885       - 1
1886       - 2
1887
1888I think it's pretty easy to understand. The default section can be overide in any section, if parameter mean something in theses sections. Network to be scan are define in the network section. You must put a add by network. Maybe i will make a delete line to suppress specific computers. The switch section define your switch. You have to write the port number to ignore, this is important if your switchs are cascade. Juste put the ports numbers between switch.
1889
1890
1891=head1 FILES
1892
1893 /etc/klask.conf
1894 /var/cache/klask/klaskdb
1895 /var/cache/klask/switchdb
1896
1897=head1 SEE ALSO
1898
1899Net::SNMP, Net::Netmask, Net::CIDR::Lite, NetAddr::IP, YAML
1900
1901
1902=head1 VERSION
1903
1904$Id: klask 79 2011-03-29 15:37:45Z g7moreau $
1905
1906
1907=head1 AUTHOR
1908
1909Written by Gabriel Moreau, Grenoble - France
1910
1911
1912=head1 LICENSE AND COPYRIGHT
1913
1914GPL version 2 or later and Perl equivalent
1915
1916Copyright (C) 2005-2009 Gabriel Moreau.
Note: See TracBrowser for help on using the repository browser.