check_junos.pl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. #!/usr/bin/perl
  2. #############################################################################
  3. # (c) 2001, 2003 Juniper Networks, Inc. #
  4. # (c) 2011 Sebastian "tokkee" Harl <sh@teamix.net> #
  5. # and team(ix) GmbH, Nuernberg, Germany #
  6. # #
  7. # This file is part of "team(ix) Monitoring Plugins" #
  8. # URL: http://oss.teamix.org/projects/monitoringplugins/ #
  9. # #
  10. # All rights reserved. #
  11. # Redistribution and use in source and binary forms, with or without #
  12. # modification, are permitted provided that the following conditions #
  13. # are met: #
  14. # 1. Redistributions of source code must retain the above copyright #
  15. # notice, this list of conditions and the following disclaimer. #
  16. # 2. Redistributions in binary form must reproduce the above copyright #
  17. # notice, this list of conditions and the following disclaimer in the #
  18. # documentation and/or other materials provided with the distribution. #
  19. # 3. The name of the copyright owner may not be used to endorse or #
  20. # promote products derived from this software without specific prior #
  21. # written permission. #
  22. # #
  23. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR #
  24. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #
  25. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #
  26. # DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, #
  27. # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES #
  28. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #
  29. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) #
  30. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, #
  31. # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING #
  32. # IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
  33. # POSSIBILITY OF SUCH DAMAGE. #
  34. #############################################################################
  35. use strict;
  36. use warnings;
  37. use utf8;
  38. use POSIX qw( :termios_h );
  39. use Nagios::Plugin;
  40. use JUNOS::Device;
  41. binmode STDOUT, ":utf8";
  42. my $valid_checks = "interfaces|chassis_environment";
  43. # TODO:
  44. # * chassis_routing_engine: show chassis routing-engine (-> number and status)
  45. #
  46. # * storage: show system storage
  47. my $plugin = Nagios::Plugin->new(
  48. plugin => 'check_junos',
  49. shortname => 'check_junos',
  50. version => '0.1',
  51. url => 'http://oss.teamix.org/projects/monitoringplugins',
  52. blurb => 'Monitor Juniper™ Switches.',
  53. usage =>
  54. "Usage: %s [-v|--verbose] [-H <host>] [-p <port>] [-t <timeout]
  55. [-U <user>] [-P <password] check-tuple [...]",
  56. license =>
  57. "This nagios plugin is free software, and comes with ABSOLUTELY NO WARRANTY.
  58. It may be used, redistributed and/or modified under the terms of the 3-Clause
  59. BSD License (see http://opensource.org/licenses/BSD-3-Clause).",
  60. extra => "
  61. This plugin connects to a Juniper™ Switch device and checks various of its
  62. components.
  63. A check-tuple consists of the name of the check and, optionally, a \"target\"
  64. which more closely specifies which characteristics should be checked, and
  65. warning and critical thresholds:
  66. checkname[,target[,warning[,critical]]]
  67. The following checks are available:
  68. * interfaces: Status of interfaces. If a target is specified, only the
  69. specified interface is taken into account.
  70. If an aggregated interface is encountered, the physical interfaces will
  71. be checked as well.
  72. * chassis_environment: Check the status of verious system components
  73. (as provided by 'show chassis environment').
  74. Warning and critical thresholds may be specified in the format documented at
  75. http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT.",
  76. );
  77. # Predefined arguments (by Nagios::Plugin)
  78. my @predefined_args = qw(
  79. usage
  80. help
  81. version
  82. extra-opts
  83. timeout
  84. verbose
  85. );
  86. my @args = (
  87. {
  88. spec => 'host|H=s',
  89. usage => '-H, --host=HOSTNAME',
  90. desc => 'Hostname/IP of Juniper box to connect to',
  91. default => 'localhost',
  92. },
  93. {
  94. spec => 'port|p=i',
  95. usage => '-p, --port=PORT',
  96. desc => 'Port to connect to',
  97. default => 22,
  98. },
  99. {
  100. spec => 'user|U=s',
  101. usage => '-U, --user=USERNAME',
  102. desc => 'Username to log into box as',
  103. default => 'root',
  104. },
  105. {
  106. spec => 'password|P=s',
  107. usage => '-P, --password=PASSWORD',
  108. desc => 'Password for login username',
  109. default => '<prompt>',
  110. },
  111. );
  112. my %conf = ();
  113. my $junos = undef;
  114. foreach my $arg (@args) {
  115. add_arg($plugin, $arg);
  116. }
  117. $plugin->getopts;
  118. # Initialize this first, so it may be used right away.
  119. $conf{'verbose'} = $plugin->opts->verbose;
  120. foreach my $arg (@args) {
  121. my @c = get_conf($plugin, $arg);
  122. $conf{$c[0]} = $c[1];
  123. }
  124. foreach my $arg (@predefined_args) {
  125. $conf{$arg} = $plugin->opts->$arg;
  126. }
  127. add_checks(\%conf, @ARGV);
  128. if (! $plugin->opts->password) {
  129. my $term = POSIX::Termios->new();
  130. my $lflag;
  131. print "Password: ";
  132. $term->getattr(fileno(STDIN));
  133. $lflag = $term->getlflag;
  134. $term->setlflag($lflag & ~POSIX::ECHO);
  135. $term->setattr(fileno(STDIN), TCSANOW);
  136. $conf{'password'} = <STDIN>;
  137. chomp($conf{'password'});
  138. $term->setlflag($lflag | POSIX::ECHO);
  139. print "\n";
  140. }
  141. verbose(1, "Connecting to host $conf{'host'} as user $conf{'user'}.");
  142. $junos = JUNOS::Device->new(
  143. hostname => $conf{'host'},
  144. login => $conf{'user'},
  145. password => $conf{'password'},
  146. access => 'ssh',
  147. 'ssh-compress' => 0);
  148. if (! ref $junos) {
  149. $plugin->die("ERROR: failed to connect to " . $conf{'host'} . "!");
  150. }
  151. foreach my $check (@{$conf{'checks'}}) {
  152. my $code;
  153. my $value;
  154. my @targets = ();
  155. if (defined $check->{'target'}) {
  156. @targets = @{$check->{'target'}};
  157. }
  158. $plugin->set_thresholds(
  159. warning => $check->{'warning'},
  160. critical => $check->{'critical'},
  161. );
  162. if ($check->{'name'} eq 'interfaces') {
  163. my $opts = {
  164. with_description => 0,
  165. };
  166. if (grep { m/^\@with_description$/; } @targets) {
  167. $opts->{'with_description'} = 1;
  168. @targets = grep { ! m/^\@with_description$/; } @targets;
  169. }
  170. my @interfaces = get_interfaces($junos, $opts, @targets);;
  171. my $down_count = 0;
  172. my @down_ifaces = ();
  173. my $phys_down_count = 0;
  174. my @phys_down_ifaces = ();
  175. my $have_lag_ifaces = 0;
  176. foreach my $iface (@interfaces) {
  177. my $name = get_iface_name($iface);
  178. my $status = check_interface($iface, $opts, @targets);
  179. if ($status == 0) {
  180. ++$down_count;
  181. push @down_ifaces, $name;
  182. }
  183. if ($status <= 0) {
  184. # disabled or down
  185. next;
  186. }
  187. if ($name !~ m/^ae/) {
  188. next;
  189. }
  190. $have_lag_ifaces = 1;
  191. my @markers = get_liface_marker(get_iface_first_logical($iface));
  192. if (! @markers) {
  193. next;
  194. }
  195. foreach my $marker (@markers) {
  196. my $phy_name = get_iface_name($marker);
  197. $phy_name =~ s/\.\d+$//;
  198. verbose(3, "Quering physical interface '$phy_name' "
  199. . "for $name.");
  200. my @phy_interfaces = get_interfaces($junos, {}, $phy_name);
  201. foreach my $phy_iface (@phy_interfaces) {
  202. if (check_interface($phy_iface, {}, $phy_name) == 0) {
  203. ++$phys_down_count;
  204. push @phys_down_ifaces, "$name -> $phy_name";
  205. }
  206. }
  207. }
  208. }
  209. if ($down_count > 0) {
  210. $plugin->add_message(CRITICAL, $down_count
  211. . " interfaces down (" . join(", ", @down_ifaces) . ")");
  212. }
  213. if ($phys_down_count > 0) {
  214. $plugin->add_message(WARNING, $phys_down_count
  215. . " LAG member interfaces down ("
  216. . join(", ", @phys_down_ifaces) . ")");
  217. }
  218. if ((! $down_count) && (! $phys_down_count)) {
  219. if (! scalar(@targets)) {
  220. $plugin->add_message(OK, "all interfaces up"
  221. . ($have_lag_ifaces
  222. ? " (including all LAG member interfaces)" : ""));
  223. }
  224. else {
  225. $plugin->add_message(OK, "interface"
  226. . (scalar(@targets) == 1 ? " " : "s ")
  227. . join(", ", @targets) . " up"
  228. . ($have_lag_ifaces
  229. ? " (including all LAG member interfaces)" : ""));
  230. }
  231. }
  232. }
  233. elsif ($check->{'name'} eq 'chassis_environment') {
  234. my $res = send_query($junos, 'get_environment_information');
  235. my %status_map = (
  236. OK => OK,
  237. Testing => UNKNOWN,
  238. Check => UNKNOWN,
  239. Failed => CRITICAL,
  240. Absent => CRITICAL,
  241. );
  242. my $items_count = 0;
  243. my $items_ok = 0;
  244. my $class = "";
  245. foreach my $item (get_object_by_spec($res, 'environment-item')) {
  246. my $name = get_object_value_by_spec($item, 'name');
  247. if (scalar(@targets) && (! grep { m/^$name$/ } @targets)) {
  248. next;
  249. }
  250. if (get_object_value_by_spec($item, 'class')) {
  251. $class = get_object_value_by_spec($item, 'class');
  252. }
  253. my $status = get_object_value_by_spec($item, 'status');
  254. if ($status eq "Absent") {
  255. if (! scalar(@targets)) {
  256. next;
  257. }
  258. # else: check this component
  259. }
  260. my $state = UNKNOWN;
  261. if (defined $status_map{$status}) {
  262. $state = $status_map{$status};
  263. }
  264. ++$items_count;
  265. if ($state == OK) {
  266. ++$items_ok;
  267. }
  268. else {
  269. $plugin->add_message($state, $class . " $name: status " .
  270. $status);
  271. }
  272. }
  273. if (! $items_count) {
  274. $plugin->add_message(UNKNOWN, "no components found");
  275. }
  276. elsif ($items_count == $items_ok) {
  277. $plugin->add_message(OK, "$items_ok components OK");
  278. }
  279. else {
  280. $plugin->add_message(WARNING,
  281. "$items_ok / $items_count components OK");
  282. }
  283. }
  284. }
  285. my ($code, $msg) = $plugin->check_messages(join => ', ');
  286. $junos->disconnect();
  287. $plugin->nagios_exit($code, $msg);
  288. sub send_query
  289. {
  290. my $device = shift;
  291. my $query = shift;
  292. my $queryargs = shift;
  293. my $res;
  294. my $err;
  295. verbose(3, "Sending query '$query' "
  296. . join(", ", map { "$_ => $queryargs->{$_}" } keys %$queryargs)
  297. . " to router.");
  298. if (ref $queryargs) {
  299. $res = $device->$query(%$queryargs);
  300. } else {
  301. $res = $device->$query();
  302. }
  303. if (! ref $res) {
  304. return "ERROR: Failed to execute query '$query'";
  305. }
  306. $err = $res->getFirstError();
  307. if ($err) {
  308. return "ERROR: " . $err->{message};
  309. }
  310. return $res;
  311. }
  312. sub check_interface {
  313. my $iface = shift;
  314. my $opts = shift || {};
  315. my @targets = @_;
  316. my $name = get_iface_name($iface);
  317. my $admin_status = get_iface_admin_status($iface);
  318. if ($admin_status !~ m/^up$/) {
  319. if ((grep { $name =~ m/^$_$/; } @targets)
  320. || ($opts->{'with_description'} &&
  321. get_iface_description($iface))) {
  322. $plugin->add_message(CRITICAL,
  323. "$name is not enabled");
  324. return -1;
  325. }
  326. return 1;
  327. }
  328. if (get_iface_status($iface) !~ m/^up$/i) {
  329. return 0;
  330. }
  331. $plugin->add_perfdata(
  332. label => "'$name-input-bytes'",
  333. value => get_iface_traffic($iface, "input"),
  334. min => 0,
  335. max => undef,
  336. uom => 'B',
  337. threshold => undef,
  338. );
  339. $plugin->add_perfdata(
  340. label => "'$name-output-bytes'",
  341. value => get_iface_traffic($iface, "output"),
  342. min => 0,
  343. max => undef,
  344. uom => 'B',
  345. threshold => undef,
  346. );
  347. return 1;
  348. }
  349. sub get_interfaces
  350. {
  351. my $device = shift;
  352. my $opts = shift || {};
  353. my @targets = @_;
  354. my @ifaces = ();
  355. my @ret = ();
  356. my $cmd = 'get_interface_information';
  357. my $res;
  358. my $args = { detail => 1 };
  359. if ((scalar(@targets) == 1) && (! $opts->{'with_description'})) {
  360. $args->{'interface_name'} = $targets[0];
  361. }
  362. $res = send_query($device, $cmd, $args);
  363. if (! ref $res) {
  364. $plugin->die($res);
  365. }
  366. @ifaces = $res->getElementsByTagName('physical-interface');
  367. @targets = map { s/\*/\.\*/g; s/\?/\./g; $_; } @targets;
  368. if (scalar(@targets)) {
  369. @ret = grep {
  370. my $i = $_;
  371. grep { get_iface_name($i) =~ m/^$_$/ } @targets;
  372. } @ifaces;
  373. }
  374. elsif (! $opts->{'with_description'}) {
  375. @ret = @ifaces;
  376. }
  377. if ($opts->{'with_description'}) {
  378. foreach my $iface (@ifaces) {
  379. my $name = get_iface_name($iface);
  380. if (get_iface_description($iface)
  381. && (! grep { m/^$name$/; } @targets)) {
  382. push @ret, $iface;
  383. }
  384. }
  385. }
  386. if ($conf{'verbose'} >= 3) {
  387. my @i = map { get_iface_name($_) . " => " . get_iface_status($_) }
  388. @ret;
  389. verbose(3, "Interfaces: " . join(", ", @i));
  390. }
  391. return @ret;
  392. }
  393. sub get_obj_element
  394. {
  395. my $obj = shift;
  396. my $elem = shift;
  397. $elem = $obj->getElementsByTagName($elem);
  398. if ((! $elem) || (! $elem->item(0))) {
  399. return;
  400. }
  401. return $elem->item(0)->getFirstChild->getNodeValue;
  402. }
  403. sub get_object_value
  404. {
  405. my $res = shift;
  406. if (! $res) {
  407. return;
  408. }
  409. if (ref($res) eq "XML::DOM::NodeList") {
  410. $res = $res->item(0);
  411. }
  412. return $res->getFirstChild->getNodeValue;
  413. }
  414. sub get_object_by_spec
  415. {
  416. my $res = shift;
  417. my $spec = shift;
  418. if (! $res) {
  419. return;
  420. }
  421. if (! $spec) {
  422. return $res;
  423. }
  424. if (! ref($spec)) {
  425. $spec = [ $spec ];
  426. }
  427. my $iter = $res;
  428. for (my $i = 0; $i < scalar(@$spec) - 1; ++$i) {
  429. my $tmp = $iter->getElementsByTagName($spec->[$i]);
  430. if ((! $tmp) || (! $tmp->item(0))) {
  431. return;
  432. }
  433. $iter = $tmp->item(0);
  434. }
  435. if (wantarray) {
  436. my @ret = $iter->getElementsByTagName($spec->[scalar(@$spec) - 1]);
  437. return @ret;
  438. }
  439. else {
  440. my $ret = $iter->getElementsByTagName($spec->[scalar(@$spec) - 1]);
  441. if ((! $ret) || (! $ret->item(0))) {
  442. return;
  443. }
  444. return $ret->item(0);
  445. }
  446. }
  447. sub get_object_value_by_spec
  448. {
  449. my $res = get_object_by_spec(@_);
  450. return get_object_value($res);
  451. }
  452. sub get_iface_name
  453. {
  454. my $iface = shift;
  455. return get_obj_element($iface, 'name');
  456. }
  457. sub get_iface_description
  458. {
  459. my $iface = shift;
  460. return get_obj_element($iface, 'description');
  461. }
  462. sub get_iface_status
  463. {
  464. my $iface = shift;
  465. return get_obj_element($iface, 'oper-status');
  466. }
  467. sub get_iface_admin_status
  468. {
  469. my $iface = shift;
  470. return get_obj_element($iface, 'admin-status');
  471. }
  472. sub get_iface_traffic
  473. {
  474. my $iface = shift;
  475. my $type = shift;
  476. my $stats = get_obj_element($iface, 'traffic-statistics');
  477. return get_obj_element($iface, "$type-bytes");
  478. }
  479. sub get_iface_first_logical
  480. {
  481. my $iface = shift;
  482. return $iface->getElementsByTagName('logical-interface')->item(0);
  483. }
  484. sub get_liface_marker
  485. {
  486. my $liface = shift;
  487. my $lag_stats = $liface->getElementsByTagName('lag-traffic-statistics')->item(0);
  488. if (! $lag_stats) {
  489. print STDERR "Cannot get marker for non-LACP interfaces yet!\n";
  490. return;
  491. }
  492. my @markers = $lag_stats->getElementsByTagName('lag-marker');
  493. return @markers;
  494. }
  495. sub add_arg
  496. {
  497. my $plugin = shift;
  498. my $arg = shift;
  499. my $spec = $arg->{'spec'};
  500. my $help = $arg->{'usage'};
  501. if (defined $arg->{'desc'}) {
  502. my @desc;
  503. if (ref($arg->{'desc'})) {
  504. @desc = @{$arg->{'desc'}};
  505. }
  506. else {
  507. @desc = ( $arg->{'desc'} );
  508. }
  509. foreach my $d (@desc) {
  510. $help .= "\n $d";
  511. }
  512. if (defined $arg->{'default'}) {
  513. $help .= " (default: $arg->{'default'})";
  514. }
  515. }
  516. elsif (defined $arg->{'default'}) {
  517. $help .= "\n (default: $arg->{'default'})";
  518. }
  519. $plugin->add_arg(
  520. spec => $spec,
  521. help => $help,
  522. );
  523. }
  524. sub get_conf
  525. {
  526. my $plugin = shift;
  527. my $arg = shift;
  528. my ($name, undef) = split(m/\|/, $arg->{'spec'});
  529. my $value = $plugin->opts->$name || $arg->{'default'};
  530. if ($name eq 'password') {
  531. verbose(3, "conf: password => "
  532. . (($value eq '<prompt>') ? '<prompt>' : '<hidden>'));
  533. }
  534. else {
  535. verbose(3, "conf: $name => $value");
  536. }
  537. return ($name => $value);
  538. }
  539. sub add_single_check
  540. {
  541. my $conf = shift;
  542. my @check = split(m/,/, shift);
  543. my %c = ();
  544. if ($check[0] !~ m/\b(?:$valid_checks)\b/) {
  545. return "ERROR: invalid check '$check[0]'";
  546. }
  547. $c{'name'} = $check[0];
  548. $c{'target'} = undef;
  549. if (defined($check[1])) {
  550. $c{'target'} = [ split(m/\+/, $check[1]) ];
  551. }
  552. $c{'warning'} = $check[2];
  553. $c{'critical'} = $check[3];
  554. # check for valid thresholds
  555. # set_threshold() will die if any threshold is not valid
  556. $plugin->set_thresholds(
  557. warning => $c{'warning'},
  558. critical => $c{'critical'},
  559. ) || $plugin->die("ERROR: Invalid thresholds: "
  560. . "warning => $c{'warning'}, critical => $c{'critical'}");
  561. push @{$conf->{'checks'}}, \%c;
  562. }
  563. sub add_checks
  564. {
  565. my $conf = shift;
  566. my @checks = @_;
  567. my $err_str = "ERROR:";
  568. if (scalar(@checks) == 0) {
  569. $conf->{'checks'}[0] = {
  570. name => 'chassis_environment',
  571. target => [],
  572. warning => undef,
  573. critical => undef,
  574. };
  575. return 1;
  576. }
  577. $conf->{'checks'} = [];
  578. foreach my $check (@checks) {
  579. my $e;
  580. $e = add_single_check($conf, $check);
  581. if ($e =~ m/^ERROR: (.*)$/) {
  582. $err_str .= " $1,";
  583. }
  584. }
  585. if ($err_str ne "ERROR:") {
  586. $err_str =~ s/,$//;
  587. $plugin->die($err_str);
  588. }
  589. }
  590. sub verbose
  591. {
  592. my $level = shift;
  593. my @msgs = @_;
  594. if ($level > $conf{'verbose'}) {
  595. return;
  596. }
  597. foreach my $msg (@msgs) {
  598. print "V$level: $msg\n";
  599. }
  600. }