vlansync.in 1.92 KB
Newer Older
1 2 3 4 5 6 7
#!/usr/local/bin/perl -w
#
# vlansync - Synchronize the switch vlans to what's in the vlans table
#            by removing extra vlans/ports, and adding missing ones
#

my $TBROOT = "@prefix@";
8 9

use English;
10 11 12 13 14

$ENV{'PATH'} = '@prefix@/sbin:@prefix@/bin:/bin';

my $debug = 0;

15 16 17 18 19 20 21 22 23
my @extras = ();
my %missing = ();
my $force = 0;
my $args = ":".join(":",@ARGV).":";

if ($args =~ /:-h/) {
  die("Usage:\nvlansync [-h[elp]] [-f[orce]]\n".
      "vlansync will add any missing VLANs from the database to the switch.\n".
      "The -f[orce] option will delete any extra vlans from the switch.\n");
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
# Keep this disabled until its safe (after merging dbtoir branch)
#if ($args =~ /:-f/) { $force = 1; }

open(DIFF,"vlandiff |");

my $table = 0;
my $switch = 0;

sub num { $a <=> $b } # for sorting numerically...

while (<DIFF>) {
  chomp;
  if ( /table/ ) { $table = 1; $switch = 0; next; }
  if ( /switch/ ) { $table = 0; $switch = 1; next; }
  if ( $table ) {
    my ($id, $memb) = split("\t");
    $missing{$id} = $memb;
    print "Missing $id: $memb\n" if $debug > 1;
  }
  if ( $switch) {
    if ( /^\#(\d+): /) {
      push(@extras, $1);
      print "Extra: $1\n" if $debug > 1;
    } else { die("Couldn't find VLAN number in '$_'\n"); }
50 51 52
  }
}

53
@extras = sort num @extras;
54

55 56 57 58
if ($debug) {
  print "Found missing:\n";
  foreach $id (sort num keys %missing) {
    print "$id: $missing{$id}\n";
59
  }
60
  print "Found extras: @extras\n";
61 62
}

63 64 65 66
if ($force && $#extras > 0 ) {
  print "Removing extra VLANs: @extras\n";
  system("snmpit -r @extras");
}
67

68
if ( (scalar keys %missing) == 0) { exit(0); }
69

70 71 72 73 74 75 76
print "Creating missing vlans:\n";
my $tmpfile = "/tmp/vlansync-$PID";
open(TMP,">$tmpfile") || die("Couldn't open $tmpfile for writing: $!\n");
print TMP "start vlan\n";
foreach $id (sort num keys %missing) {
  print "$id $missing{$id}\n";
  print TMP "$id $missing{$id}\n";
77
}
78 79
print TMP "end vlan\n";
close TMP;
80

81 82 83
system("snmpit -f $tmpfile");

system("rm -f $tmpfile");
84

85
exit(0);