Browse Source

Add a generic import script to import physical switches.

Joe Clarke 8 years ago
parent
commit
b3327abaf4
1 changed files with 66 additions and 0 deletions
  1. 66 0
      scripts/import_assets.pl

+ 66 - 0
scripts/import_assets.pl

@@ -0,0 +1,66 @@
+#!/usr/bin/perl
+
+use strict;
+use DBI;
+use vars qw($PID $DB_USER $DB_PASS);
+require 'dbi.ph';
+
+sub trim($) {
+        my ($str) = shift;
+
+        $str //= '';
+
+        $str =~ s/^\s+//g;
+        $str =~ s/\s+$//g;
+
+        return $str;
+}
+
+if (scalar @ARGV != 1) {
+        print "usage: $0 <input file>\n";
+        exit(1);
+}
+
+my $dsn = "DBI:mysql:database=noc";
+
+my $dbh = DBI->connect($dsn, $DB_USER, $DB_PASS, {PrintError => 0})
+    or die "ERROR: Failed to connect to the database.";
+
+open(IN, $ARGV[0])
+    or die "ERROR: Failed to open $ARGV[0] for reading.";
+
+my @contents = <IN>;
+close(IN);
+for (my $i = 1 ; $i < scalar(@contents) ; $i++) {
+        my $line = $contents[$i];
+        chomp $line;
+        my ($serial, $pid, $mac, $ports) = split(/,/, $line);
+        $mac    = trim($mac);
+        $serial = trim($serial);
+        $pid    = trim($pid);
+        $ports  = trim($ports);
+        if ($mac ne '') {
+                my @mac_parts = ($mac =~ /../g);
+                $mac = lc(join(':', @mac_parts));
+        }
+
+        if ($serial ne '') {
+                my $query =
+                    'REPLACE INTO DEVICE_MAP (serial_number, pid, mac, max_ports) VALUES (?, ?, ?, ?)';
+                my $sth = $dbh->prepare($query);
+                $serial = uc $serial;
+                if (!$sth) {
+                        print STDERR "Failed to insert switch record: "
+                            . $dbh->errstr . "\n";
+                        next;
+                }
+
+                my @params = ($serial, $pid, $mac, $ports);
+                my $res = $sth->execute(@params);
+                if (!$res) {
+                        print STDERR "Failed to insert switch record: "
+                            . $dbh->errstr . "\n";
+                        next;
+                }
+        }
+}