#!/usr/bin/perl -w

# query_zynos_ras.pl - queries zyxel based devices running zynos for one or more parameter values
#                      useful in the case that the value can not be gathered through snmp.
#
# Copyright 2010 Thomas S. Iversen (zensonic@zensonic.dk)
#
# Version 1.0 - 2010.12.26 - Initial version


use strict;
use Expect;

my $args=$#ARGV + 1;

die "Usage: $0 <hostname|ip> <port> <password> <zynos cmd> <regexp> [<regexp>]*\nIe     $0 192.168.1.1 23023 secret \"wan adsl linedata near\" \"noise margin downstream:\"" if($args < 5);
my $hostname=$ARGV[0];
my $port=$ARGV[1];
my $password=$ARGV[2];
my $cmd=$ARGV[3];
my $exit_cmd="exit";
my $prompt="ras> ";
my $timeout=20;

my $exp = new Expect;
$exp = Expect->spawn("telnet $hostname $port") or die "Cannot spawn";

# Turn of echo to stdout
$exp->log_stdout(0);

# login - Expect password prompt, give password.
$exp->expect($timeout, 'Password: ');
$exp->send("$password\n");

# Then expect command prompt, send the data gather command.
# expect new prompt and collect data with exp->before();

$exp->expect($timeout, $prompt);
$exp->send("$cmd\n");
$exp->expect($timeout, $prompt);
my $data=$exp->before();

# at the new prompt send exit_cmd and close
$exp->send("$exit_cmd\n");
$exp->soft_close();

# filter data

my $value;
my $regexp;
my $first_part;
my $out="";

for(my $i=4;$i<$args;$i++) {
	$value="nan";
	$regexp=$ARGV[$i];	
	$first_part=(split(/ /,$regexp))[0];
	$value=$1 if($data=~/$regexp ([0-9]*)/i);
	$out .= "$first_part:$value ";
}

# output to cacti
print $out . "\n";
