]> git.sesse.net Git - nms/blob - include/nms.pm
Merge.
[nms] / include / nms.pm
1 #! /usr/bin/perl
2 use strict;
3 use warnings;
4 use DBI;
5 use Net::Telnet;
6 package nms;
7
8
9 use base 'Exporter';
10 our @EXPORT = qw(switch_connect switch_exec);
11
12 BEGIN {
13         require "config.pm";
14         eval {
15                 require "config.local.pm";
16         };
17 }
18
19 sub db_connect {
20         my $dbh = DBI->connect("dbi:Pg:" .
21                                 "dbname=" . $nms::config::db_name .
22                                 ";host=" . $nms::config::db_host,
23                                 $nms::config::db_username,
24                                 $nms::config::db_password)
25                 or die "Couldn't connect to database";
26         return $dbh;    
27 }
28
29 sub switch_connect($) {
30         my ($ip) = @_;
31
32         my $conn = new Net::Telnet(     Timeout => $nms::config::telnet_timeout,
33 #                                       Dump_Log => '/tmp/dumplog-queue',
34                                         Errmode => 'return',
35 #                                       Prompt => '/ES-3023>/');
36                                         Prompt => '/(ES-3024|e\d{1,2}\-\dsw)>/i');
37         my $ret = $conn->open(  Host => $ip);
38         if (!$ret || $ret != 1) {
39                 return (undef);
40         }
41         # XXX: Just send the password as text, I did not figure out how to
42         # handle authentication with only password through $conn->login().
43         #$conn->login(»·Prompt => '/password[: ]*$/i',
44         #               Name => $password,
45         #               Password => $password);
46         $conn->cmd($nms::config::zyxel_password);
47         # Get rid of banner
48         $conn->get;
49         return ($conn);
50 }
51
52 # Send a command to switch and return the data recvied from the switch
53 sub switch_exec {
54         my ($cmd, $conn, $print) = @_;
55
56         # Send the command and get data from switch
57         my @data;
58         if (defined($print)) {
59                 $conn->print($cmd);
60                 return;
61         } else {
62                 @data = $conn->cmd($cmd);
63         }
64         my @lines = ();
65         foreach my $line (@data) {
66                 # Remove escape-7 sequence
67                 $line =~ s/\x1b\x37//g;
68                 push (@lines, $line);
69         }
70
71         return @lines;
72 }
73
74 1;