0

I have got a machine (Debian based) with some temperature sensors attached to it, and i would like to query them over snmp, from one script. I can work with one sensor ok, but i am struggling when i plug another one in.

What I am trying to do is loop through each device, and give each one an id, then use this ID as part of the OID, then give it a value.

I've never worked with snmp before, and my perl is not great so any help would be much appreciated. Below is my code:

#!/usr/bin/perl

use NetSNMP::agent (':all');
use NetSNMP::ASN qw(ASN_OCTET_STR ASN_INTEGER);

$BASE_OID=".1.3.6.1.4.1.41050";
$dev_id=1;
$string_value;
$integer_value;

sub pimon_handler {
  my ($handler, $registration_info, $request_info, $requests) = @_;
  my $request;
  my $oid_key;

  for($request = $requests; $request; $request = $request->next()) {

    $oid_key=$BASE_OID . '.' . $dev_id;
    my $oid = $request->getOID();
    if ($request_info->getMode() == MODE_GET) {
      if ($oid == new NetSNMP::OID($oid_key . '.0')) {
        $request->setValue(ASN_OCTET_STR, $string_value);
      }
      elsif ($oid == new NetSNMP::OID($oid_key . '.1')) {
        $request->setValue(ASN_INTEGER, $integer_value);
      }
    } elsif ($request_info->getMode() == MODE_GETNEXT) {
      if ($oid == new NetSNMP::OID($oid_key . '.0')) {
        $request->setOID($oid_key . '.1');
        $request->setValue(ASN_INTEGER, $integer_value);
      }
      elsif ($oid < new NetSNMP::OID($oid_key . '.0')) {
        $request->setOID($oid_key . '.0');
        $request->setValue(ASN_OCTET_STR, $string_value);
      }
    }
  }
}

#location of where we are going to find the 1wire devices
@sensors = `cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slaves`;
chomp(@sensors);

#loop through the sensors we find
foreach $line(@sensors) {

        #work out the temp we have got. Need to change this for other sensor types
        $output = `cat /sys/bus/w1/devices/$line/w1_slave`;
        $output =~ /t=(?<temp>\d+)/;
        $integer_value = sprintf "%.0f",$+{temp} / 1000;
        $string_value = $line;

        my $agent = new NetSNMP::agent();
        $agent->register("Pimon$looptest", $BASE_OID . '.' . $dev_id,
                 \&pimon_handler);

        print "Dev $dev_id temp $line temp is $integer_value\n";
        $dev_id ++;
}
beakersoft
  • 2,316
  • 6
  • 30
  • 40

1 Answers1

0

Are you getting any errors or output?

I suspect that your problem lies in and around your reading the data file by shelling-out to cat instead of opening the file and looping over the linewise contents.

Try dumping the value of @sensors. if it is a single entry array, with the only element containing your entire file, then simply switch @sensors to be scalar. then split $sensors into an array and loop over that.

my $sensors = `read something`
chomp $sensors;
my @sensors = split(/\n/, $sensors);

foreach $line (@sensors) { ...

Len Jaffe
  • 3,442
  • 1
  • 21
  • 28