update page now
Laravel Live Japan

A classe SNMP

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

Introdução

Representa uma sessão SNMP.

Resumo da classe

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;
/* Propriedades */
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
}

Propriedades

max_oids

OID máximo por solicitação GET/SET/GETBULK

valueretrieval

Controla o método como os valores SNMP serão retornados

SNMP_VALUE_LIBRARYOs valores de retorno serão aqueles retornados pela biblioteca Net-SNMP.
SNMP_VALUE_PLAINOs valores de retorno serão o valor simples sem as informações do tipo SNMP.
SNMP_VALUE_OBJECT Os valores de retorno serão objetos com as propriedades "value" e "type", onde esta última é uma das constantes SNMP_OCTET_STR, SNMP_COUNTER etc. A forma como "value" é retornado depende de qual das seguintes opções está definida: SNMP_VALUE_LIBRARY ou SNMP_VALUE_PLAIN.
quick_print

Valor de quick_print na biblioteca NET-SNMP

Define o valor de quick_print na biblioteca NET-SNMP. Quando este parâmetro estiver definido (1), a biblioteca SNMP retornará valores de 'impressão rápida'. Isso significa que apenas o valor será impresso. Quando quick_print não estiver habilitado (padrão), a biblioteca NET-SNMP imprime informações extras, incluindo o tipo do valor (por exemplo, Endereço IP ou OID). Além disso, se quick_print não estiver habilitado, a biblioteca imprime valores hexadecimais adicionais para todas as strings de três caracteres ou menos.

enum_print

Controla a maneira como os valores de enumeração são impressos

Os parâmetros alternam se as funções walk/get etc. devem procurar automaticamente valores de enumeração no MIB e retorná-los junto com sua string legível.

oid_output_format

Controla o formato de saída OID

Representação do OID .1.3.6.1.2.1.1.3.0 para vários valores de oid_output_format
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

Controla a desativação da verificação para aumentar o OID enquanto caminha pela árvore OID

Alguns agentes SNMP são conhecidos por retornar OIDs fora de ordem, mas conseguem completar a caminhada mesmo assim. Outros agentes retornam OIDs que estão fora de ordem e podem fazer com que SNMP::walk() entre em loop indefinidamente até que o limite de memória seja atingido. A biblioteca SNMP do PHP, por padrão, executa a verificação de aumento de OID e interrompe a caminhada na árvore de OIDs quando detecta um possível loop, emitindo um aviso sobre a presença de OIDs não crescentes. Defina oid_increasing_check como false para desabilitar esta verificação.

exceptions_enabled

Controla quais falhas gerarão uma exceção SNMPException em vez de avisos. Use constantes SNMP::ERRNO_* com OR binário. Por padrão, todas as exceções SNMP são desabilitadas.

info

Propriedade somente leitura com configuração de agente remoto: nome do host, porta, tempo limite padrão, contagem de tentativas padrão

Constantes predefinidas

SNMP Error Types

SNMP::ERRNO_NOERROR

Não ocorreu nenhum erro específico de SNMP.

SNMP::ERRNO_GENERIC

Ocorreu um erro genérico SNMP.

SNMP::ERRNO_TIMEOUT

A solicitação ao agente SNMP atingiu o tempo limite.

SNMP::ERRNO_ERROR_IN_REPLY

O agente SNMP retornou um erro na resposta.

SNMP::ERRNO_OID_NOT_INCREASING

O agente SNMP enfrentou um ciclo de OID reportando OID não crescente durante a execução do comando (BULK)WALK. Isso indica um agente SNMP remoto falso.

SNMP::ERRNO_OID_PARSING_ERROR

A biblioteca falhou ao analisar o OID (e/ou tipo para o comando SET). Nenhuma consulta foi realizada.

SNMP::ERRNO_MULTIPLE_SET_QUERIES

A biblioteca utilizará múltiplas consultas para a operação SET solicitada. Isso significa que a operação será realizada de forma não transacional e o segundo bloco ou os blocos subsequentes poderão falhar caso ocorra uma falha de tipo ou valor.

SNMP::ERRNO_ANY

Todos os códigos SNMP::ERRNO_* são combinados com OR binário.

Índice

adicionar nota

Notas de Usuários 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