The SNMP class

(PHP 5 >= 5.4.0, PHP 7)

简介

Represents SNMP session.

类摘要

SNMP {
/* 属性 */
public int $max_oids ;
public int $valueretrieval ;
public bool $quick_print ;
public bool $enum_print ;
public int $oid_output_format ;
public bool $oid_increasing_check ;
public int $exceptions_enabled ;
public array $info ;
/* 方法 */
public __construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )
public close ( void ) : bool
public get ( mixed $object_id [, bool $preserve_keys = FALSE ] ) : mixed
public getErrno ( void ) : int
public getError ( void ) : string
public getnext ( mixed $object_id ) : mixed
public set ( mixed $object_id , mixed $type , mixed $value ) : bool
public setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] ) : bool
public walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] ) : array
/* 常量 */
const integer ERRNO_NOERROR = 0 ;
const integer ERRNO_GENERIC = 2 ;
const integer ERRNO_TIMEOUT = 4 ;
const integer ERRNO_ERROR_IN_REPLY = 8 ;
const integer ERRNO_OID_NOT_INCREASING = 16 ;
const integer ERRNO_OID_PARSING_ERROR = 32 ;
const integer ERRNO_MULTIPLE_SET_QUERIES = 64 ;
const integer ERRNO_ANY = 126 ;
const integer VERSION_1 = 0 ;
const integer VERSION_2C = 1 ;
const integer VERSION_2c = 1 ;
const integer VERSION_3 = 3 ;
}

属性

max_oids

Maximum OID per GET/SET/GETBULK request

valueretrieval

Controls the method how the SNMP values will be returned

SNMP_VALUE_LIBRARYThe return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAINThe return values will be the plain value without the SNMP type hint.
SNMP_VALUE_OBJECT The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set
quick_print

Value of quick_print within the NET-SNMP library

Sets the value of quick_print within the NET-SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.

enum_print

Controls the way enum values are printed

Parameter toggles if walk/get etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

oid_output_format

Controls OID output format

OID .1.3.6.1.2.1.1.3.0 representation for various oid_output_format values
SNMP_OID_OUTPUT_FULL.iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC.1.3.6.1.2.1.1.3.0
SNMP_OID_OUTPUT_MODULEDISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIXsysUpTimeInstance
SNMP_OID_OUTPUT_UCDsystem.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONEUndefined
oid_increasing_check

Controls disabling check for increasing OID while walking OID tree

Some SNMP agents are known for returning OIDs out of order but can complete the walk anyway. Other agents return OIDs that are out of order and can cause SNMP::walk() to loop indefinitely until memory limit will be reached. PHP SNMP library by default performs OID increasing check and stops walking on OID tree when it detects possible loop with issuing warning about non-increasing OID faced. Set oid_increasing_check to FALSE to disable this check.

exceptions_enabled

Controls which failures will raise SNMPException instead of warning. Use bitwise OR'ed SNMP::ERRNO_* constants. By default all SNMP exceptions are disabled.

info

Read-only property with remote agent configuration: hostname, port, default timeout, default retries count

预定义常量

SNMP Error Types

SNMP::ERRNO_NOERROR

No SNMP-specific error occurred.

SNMP::ERRNO_GENERIC

A generic SNMP error occurred.

SNMP::ERRNO_TIMEOUT

Request to SNMP agent timed out.

SNMP::ERRNO_ERROR_IN_REPLY

SNMP agent returned an error in reply.

SNMP::ERRNO_OID_NOT_INCREASING

SNMP agent faced OID cycling reporning non-increasing OID while executing (BULK)WALK command. This indicates bogus remote SNMP agent.

SNMP::ERRNO_OID_PARSING_ERROR

Library failed while parsing OID (and/or type for SET command). No queries has been made.

SNMP::ERRNO_MULTIPLE_SET_QUERIES

Library will use multiple queries for SET operation requested. That means that operation will be performed in a non-transaction manner and second or subsequent chunks may fail if a type or value failure will be faced.

SNMP::ERRNO_ANY

All SNMP::ERRNO_* codes bitwise OR'ed.

SNMP Protocol Versions

SNMP::VERSION_1

SNMP::VERSION_2C, SNMP::VERSION_2c

SNMP::VERSION_3

Table of Contents

User Contributed Notes

madjev1990 at gmail dot com 04-Mar-2016 10:13
Part of my diploma thesis was to create web interface to command device via SNMP. So I create my own level of abstraction over SNMP class:

<?php

/**
 * Snmp library which add one level of abstraction to snmp native library.
 * It adds functionality to work with module PicoIP.With this library you can:
 * 1.Activate/deactive defined pin;
 * 2.Get status of all pins.
 *
 * When make an instance you should pass to the constructor key word which will
 * make the library create an object with necessary properetis and access permissions.
 *
 * Private properties set some of configurations:
 * Host is IP address of the divece which we will command.
 * Two passwords are set for reading and writing.
 * Version of snmp protocol that we will use is version 1.
 *
 * @author Radoslav Madjev
 * @year 2016
 * @version 1.0 beta
 *
 *
 */
class snmp_lib {

    private
$snmpInstance;
    private
$VERSION = SNMP::VERSION_1;
    private
$HOST = '192.168.0.150';
    private
$passwordRead = '000000000000';
    private
$passwordWrite = 'private';
    private
$releys = array(1 => '1.3.6.1.4.1.19865.1.2.1.1.0',
       
2 => '1.3.6.1.4.1.19865.1.2.1.2.0');
    private
$allPorts = array('3' => '1.3.6.1.4.1.19865.1.2.1.33.0',
       
'5' => '1.3.6.1.4.1.19865.1.2.2.33.0');

   
/**
     * Create instance of SNMP native class, based on actions that we will
     * perform.
     *
     * @param string $action
     */
   
public function __construct($action) {
        if (
in_array($action, array('read', 'write'))) {
            if (
strcmp($action, 'read') === 0) {
               
$this->_read();
            } else {
               
$this->_write();
            }
        }
    }

   
/**
     * Create instance with reading permissions.
     */
   
private function _read() {
       
$this->snmpInstance = new SNMP($this->VERSION, $this->HOST, $this->passwordRead);
    }

   
/**
     * Create instance with writing permissions.
     */
   
private function _write() {
       
$this->snmpInstance = new SNMP($this->VERSION, $this->HOST, $this->passwordWrite);
    }

   
/**
     * Close snmp session.
     *
     * @return boolean
     */
   
public function closeSession() {
        return
$this->snmpInstance->close();
    }

   
/**
     * Set integer 1 as value of defined pin.
     */
   
public function activate($relay) {
       
$this->snmpInstance->set($this->releys[$relay], 'i', '1');
    }

   
/**
     * Set integer 0 as value of defined pin.
     */
   
public function deactivate($relay) {
       
$this->snmpInstance->set($this->releys[$relay], 'i', '0');
    }

   
/**
     * Get pin status of all ports of the module.
     *
     * @return array
     */
   
public function getAllPortsStatus() {
       
$allPins = array();
        foreach (
$this->allPorts as $number => $port) {
           
//get active pins as 8-bit integer of defined port
           
$getbits = $this->snmpInstance->get($port);
           
$bits = str_replace('INTEGER: ', '', $getbits);
           
//get pins status
           
$pinsStatus = $this->_getActivePins($bits);
           
$allPins[$number] = $pinsStatus;
        }

        return
$allPins;
    }

   
/**
     * Make bitwise operation which will determine,
     * which are active pins.
     *
     * @param int $bits
     * @return array
     */
   
private function _getActivePins($bits) {

       
$bitMapping = array(
           
1 => 1,
           
2 => 2,
           
3 => 4,
           
4 => 8,
           
5 => 16,
           
6 => 32,
           
7 => 64,
           
8 => 128
       
);

       
$pinsStatus = array();

        foreach (
$bitMapping as $int => $bit) {
            if ((
$bits & $bit) == $bit) {
               
$pinsStatus[$int] = true;
                continue;
            }
           
$pinsStatus[$int] = false;
        }

        return
$pinsStatus;
    }

}

?>

I have one module that receive SNMP request and send a command to relays. Also these are example scripts that use this lib:
Turn on script:
<?php
require_once 'snmp_lib.php';

$snmp = new snmp_lib('write');
$snmp->activate($getRelayNumber);
$snmp->closeSession();
?>

Turn off script:
<?php
require_once 'snmp_lib.php';

$snmp = new snmp_lib('write');
$snmp->deactivate($getRelayNumber);
$snmp->closeSession();
?>

Script that get all ports status:
<?php
require_once 'snmp_lib.php';

$snmp = new snmp_lib('read');
$getActive = $snmp->getAllPortsStatus();
?>