import_assets.pl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/perl
  2. use strict;
  3. use DBI;
  4. use vars qw($PID $DB_USER $DB_PASS);
  5. require 'dbi.ph';
  6. sub trim($) {
  7. my ($str) = shift;
  8. $str //= '';
  9. $str =~ s/^\s+//g;
  10. $str =~ s/\s+$//g;
  11. return $str;
  12. }
  13. if (scalar @ARGV != 1) {
  14. print "usage: $0 <input file>\n";
  15. exit(1);
  16. }
  17. my $dsn = "DBI:mysql:database=noc";
  18. my $dbh = DBI->connect($dsn, $DB_USER, $DB_PASS, {PrintError => 0})
  19. or die "ERROR: Failed to connect to the database.";
  20. open(IN, $ARGV[0])
  21. or die "ERROR: Failed to open $ARGV[0] for reading.";
  22. my @contents = <IN>;
  23. close(IN);
  24. for (my $i = 1 ; $i < scalar(@contents) ; $i++) {
  25. my $line = $contents[$i];
  26. chomp $line;
  27. my ($serial, $pid, $mac, $ports) = split(/,/, $line);
  28. $mac = trim($mac);
  29. $serial = trim($serial);
  30. $pid = trim($pid);
  31. $ports = trim($ports);
  32. if ($mac ne '') {
  33. my @mac_parts = ($mac =~ /../g);
  34. $mac = lc(join(':', @mac_parts));
  35. }
  36. if ($serial ne '') {
  37. my $query =
  38. 'REPLACE INTO DEVICE_MAP (serial_number, pid, mac, max_ports) VALUES (?, ?, ?, ?)';
  39. my $sth = $dbh->prepare($query);
  40. $serial = uc $serial;
  41. if (!$sth) {
  42. print STDERR "Failed to insert switch record: "
  43. . $dbh->errstr . "\n";
  44. next;
  45. }
  46. my @params = ($serial, $pid, $mac, $ports);
  47. my $res = $sth->execute(@params);
  48. if (!$res) {
  49. print STDERR "Failed to insert switch record: "
  50. . $dbh->errstr . "\n";
  51. next;
  52. }
  53. }
  54. }