CakeFest 2024: The Official CakePHP Conference

SNMP クラス

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

はじめに

SNMP セッションを表します。

クラス概要

class SNMP {
/* 定数 */
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;
/* プロパティ */
public readonly array $info;
public ?int $max_oids;
/* メソッド */
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
}

プロパティ

max_oids

GET/SET/GETBULK リクエスト単位の最大の OID

valueretrieval

SNMP の値を返す方法

SNMP_VALUE_LIBRARYNet-SNMP ライブラリの返す値を返します。
SNMP_VALUE_PLAINSNMP 型情報を含まないプレーンな値を返します。
SNMP_VALUE_OBJECT オブジェクトを返します。このオブジェクトはプロパティ "value" および "type" を持ち、後者のプロパティの値は SNMP_OCTET_STR, SNMP_COUNTER などの定数となります。 "value" の中身は SNMP_VALUE_LIBRARYSNMP_VALUE_PLAIN のどちらが設定されているかによって変わります。
quick_print

NET-SNMP ライブラリ内の quick_print の値

NET-SNMP ライブラリ内の quick_print の値を指定します。 これを (1 に) 設定すると、SNMP ライブラリは「手早く表示」した値を返します。 つまり、単なる値だけを表示するということです。quick_print を有効にしなければ (デフォルト)、NET-SNMP ライブラリは追加情報 (値の型、たとえば IpAddress や OID) も表示します。 さらに、quick_print が有効でない場合は、三文字以下のすべての文字列に対して追加の十六進値を表示します。

enum_print

enum 値の表示方法

walk や get などが、自動的に MIB 内の enum 値の元をたどって その値も可読形式の文字列にするかどうかを設定します。

oid_output_format

OID の出力フォーマットの制御

oid_output_format の値による、OID .1.3.6.1.2.1.1.3.0 の表示方法の変化
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

OID ツリーを走査中の OID 増加チェックの無効化

SNMP エージェントの中には、 OID を返す順番がおかしくても走査はできるというものがあります。 それ以外のエージェントの場合、OID を返す順番がおかしくなると SNMP::walk() が無限ループになり、 メモリを食いつぶしてしまいます。PHP の SNMP ライブラリは、 デフォルトで OID の増加チェックを行い、もし OID ツリーの走査中に OID が増加しないパターンがあればそこで走査を終了します。 oid_increasing_checkfalse にすると、このチェックが無効になります。

exceptions_enabled

警告ではなく SNMPException を発生させるのがどの失敗なのかを設定します。 Use bitwise OR'ed SNMP::ERRNO_* constants. By default all SNMP exceptions are disabled.

info

読み込み専用のプロパティで、リモートエージェントの設定を表します。 ホスト名やポート、デフォルトのタイムアウト、デフォルトの再試行回数を含みます。

定義済み定数

SNMP エラー型

SNMP::ERRNO_NOERROR

SNMP に関するエラーは発生していません。

SNMP::ERRNO_GENERIC

SNMP のエラーが発生しました。

SNMP::ERRNO_TIMEOUT

SNMP エージェントへのリクエストがタイムアウトしました。

SNMP::ERRNO_ERROR_IN_REPLY

SNMP エージェントがエラーの応答を返しました。

SNMP::ERRNO_OID_NOT_INCREASING

SNMP エージェントが、(BULK)WALK コマンドの実行中に前の OID から増加していない OID に当たりました。 リモート SNMP エージェントが偽物である可能性があります。

SNMP::ERRNO_OID_PARSING_ERROR

OID (や SET コマンドの型) のパースに失敗しました。 クエリは作成されませんでした。

SNMP::ERRNO_MULTIPLE_SET_QUERIES

要求された SET 操作で複数のクエリを使います。 この操作はトランザクション内の操作ではないので、 二番目以降のクエリに型や値の問題があれば失敗するかもしれません。

SNMP::ERRNO_ANY

すべての SNMP::ERRNO_* コードをビット OR したもの。

SNMP プロトコルバージョン

SNMP::VERSION_1

SNMP::VERSION_2C, SNMP::VERSION_2c

SNMP::VERSION_3

目次

  • SNMP::close — SNMP セッションを閉じる
  • SNMP::__construct — リモート SNMP エージェントへのセッションを表す SNMP インスタンスを作成する
  • SNMP::get — SNMP オブジェクトを取得する
  • SNMP::getErrno — 直近のエラーコードを取得する
  • SNMP::getError — 直近のエラーメッセージを取得する
  • SNMP::getnext — 指定したオブジェクト ID に続く SNMP オブジェクトを取得する
  • SNMP::set — SNMP オブジェクトの値を設定する
  • SNMP::setSecurity — セキュリティ関連の SNMPv3 セッションパラメータを設定する
  • SNMP::walk — SNMP オブジェクトのサブツリーを取得する
add a note

User Contributed Notes 2 notes

up
0
swannie at swannie dot net
3 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
8 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