PHP 8.3.21 Released!

La clase SNMP

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

Introducción

Representa una sesión SNMP.

Sinopsis de la Clase

class SNMP {
/* Constantes */
public const int VERSION_1;
public const int VERSION_2c;
public const int VERSION_2C;
public const int VERSION_3;
public const int ERRNO_NOERROR;
public const int ERRNO_ANY;
public const int ERRNO_GENERIC;
public const int ERRNO_TIMEOUT;
/* Propiedades */
public readonly array $info;
public ?int $max_oids;
/* Métodos */
public __construct(
    int $version,
    string $hostname,
    string $community,
    int $timeout = -1,
    int $retries = -1
)
public close(): bool
public get(array|string $objectId, bool $preserveKeys = false): mixed
public getErrno(): int
public getError(): string
public getnext(array|string $objectId): mixed
public set(array|string $objectId, array|string $type, array|string $value): bool
public setSecurity(
    string $securityLevel,
    string $authProtocol = "",
    string $authPassphrase = "",
    string $privacyProtocol = "",
    string $privacyPassphrase = "",
    string $contextName = "",
    string $contextEngineId = ""
): bool
public walk(
    array|string $objectId,
    bool $suffixAsKey = false,
    int $maxRepetitions = -1,
    int $nonRepeaters = -1
): array|false
}

Propiedades

max_oids

Número máximo de OID por solicitud GET/SET/GETBULK

valueretrieval

Controla la forma en que se devolverán los valores SNMP

SNMP_VALUE_LIBRARY Los valores se devolverán de la misma forma que la biblioteca Net-SNMP.
SNMP_VALUE_PLAIN Los valores se devolverán en valor pleno, sin la información de tipo SNMP.
SNMP_VALUE_OBJECT Los valores se devolverán en forma de objetos con las propiedades "value" y "type", donde el tipo podrá ser una constante SNMP_OCTET_STR, SNMP_COUNTER etc... La forma en que se devuelve la "value" se basa en la constante definida: SNMP_VALUE_LIBRARY o SNMP_VALUE_PLAIN.
quick_print

Valor del parámetro quick_print en la biblioteca NET-SNMP

Define el valor del parámetro quick_print en la biblioteca NET-SNMP. Cuando está definido (1), la biblioteca SNMP devolverá valores rápidamente imprimibles. Esto significa únicamente que los valores serán impresos. Cuando el parámetro quick_print no está definido (por defecto), la biblioteca NET-SNMP imprimirá información adicional incluyendo el tipo de la valor (i.e. IpAddress o OID). Además, si quick_print no está activado, la biblioteca imprimirá los valores hexadecimales para todas las cadenas que contengan hasta 3 caracteres.

enum_print

Controla la forma en que se imprimen los valores enum.

Permite indicar a walk/get etc. si deben buscar automáticamente los valores enum en el MIIB y devolverlos además de sus cadenas legibles por humanos.

oid_output_format

Controla el formato de salida OID

Representación OID .1.3.6.1.2.1.1.3.0 para diversos valores de oid_output_format
SNMP_OID_OUTPUT_FULLLa forma completa, como "iso.org.dod...."
SNMP_OID_OUTPUT_NUMERICLa forma numérica, como ".1.3.6.1.4.1.8072.3.2.10"
SNMP_OID_OUTPUT_MODULELa forma corta, como "NET-SNMP-TC::linux"
SNMP_OID_OUTPUT_SUFFIXTBD
SNMP_OID_OUTPUT_UCDTBD
SNMP_OID_OUTPUT_NONETBD
oid_increasing_check

Controla la verificación de la desactivación para el aumento de la OID durante el recorrido del árbol OID

Algunos agentes SNMP son conocidos por devolver OIDs en el orden incorrecto, pero pueden continuar el recorrido. Otros agentes devuelven OIDs en el orden incorrecto y pueden conducir al método SNMP::walk() en un bucle infinito hasta que se alcance el límite de memoria. La biblioteca PHP SNMP, por defecto, realiza la verificación del aumento de la OID y detiene el recorrido del árbol OID cuando detecta una posible bucle emitiendo una alerta. Defina la variable oid_increasing_check a false para desactivar esta verificación.

exceptions_enabled

Controla qué excepción SNMPException será emitida en lugar de las alertas. Utilizar el operador OR de las constantes SNMP::ERRNO_*. Por defecto, todas las excepciones SNMP están desactivadas.

info

Propiedad de solo lectura que contiene la configuración del agente remoto: nombre de host, puerto, tiempo de espera por defecto, número de recuperación por defecto

Constantes predefinidas

Tipos de errores SNMP

SNMP::ERRNO_NOERROR

No ha ocurrido ningún error específico SNMP.

SNMP::ERRNO_GENERIC

Ha ocurrido un error SNMP genérico.

SNMP::ERRNO_TIMEOUT

Solicitud al agente SNMP alcanza el tiempo de espera.

SNMP::ERRNO_ERROR_IN_REPLY

El agente SNMP devuelve un error en la respuesta.

SNMP::ERRNO_OID_NOT_INCREASING

El agente SNMP no incrementa más el OID durante la ejecución del comando WALK (BULK). Esto indica que hay un problema con el agente SNMP.

SNMP::ERRNO_OID_PARSING_ERROR

La biblioteca falla al analizar el OID (y/o el tipo para el comando SET). No se realiza ninguna solicitud.

SNMP::ERRNO_MULTIPLE_SET_QUERIES

La biblioteca utilizará varias solicitudes para la operación SET solicitada. Esto significa que la operación se realizará de forma no transaccional y que los fragmentos siguientes podrán fallar si se proporciona un tipo o valor incorrecto.

SNMP::ERRNO_ANY

Todos los códigos operador OR de las constantes SNMP::ERRNO_*.

Tabla de contenidos

add a note

User Contributed Notes 2 notes

up
0
swannie at swannie dot net
4 years ago
Hopefully this helps someone else out because this was driving be bonkers for a good two hours. It looks like valueretrieval and enum_print work together in a way that I wasn't expecting, and after re-reading may be by design but I'm not sure. If you can't get enums to print, this might be why.

<?php
$snmp
= new SNMP(SNMP::VERSION_2C,'192.168.1.9','test');
$snmp->oid_output_format = SNMP_OID_OUTPUT_SUFFIX;
$snmp->valueretrieval = SNMP_VALUE_PLAIN;
$snmp->enum_print = 0;
echo
$snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
$snmp->enum_print = 1;
echo
$snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
$snmp->quick_print = 1;
echo
$snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
$snmp->valueretrieval = SNMP_VALUE_LIBRARY;
echo
$snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
$snmp->enum_print = 0;
echo
$snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
?>

Output:
1
1
1
1
up
up
-1
madjev1990 at gmail dot com
9 years ago
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();
?>
To Top