Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : SNMP Functions

SNMP Functions

Introduction

Requirements

In order to use the SNMP functions on Unix you need to install the NET-SNMP package. On Windows these functions are only available on NT and not on Win95/98.

Installation

Important: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h or acconfig.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:

#define NO_ZEROLENGTH_COMMUNITY 1

Now compile PHP --with-snmp[=DIR].

If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the --enable-ucd-snmp-hack switch which will work around the misfeature.

The Windows distribution contains support files for SNMP in the mibs directory. This directory should be moved to DRIVE:\usr\mibs, where DRIVE must be replaced with the driveletter where PHP is installed on, e.g.c:\usr\mibs.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

SNMP_OID_OUTPUT_FULL (integer)
As of 5.2.0
SNMP_OID_OUTPUT_NUMERIC (integer)
As of 5.2.0
SNMP_VALUE_LIBRARY (integer)
SNMP_VALUE_PLAIN (integer)
SNMP_VALUE_OBJECT (integer)
SNMP_BIT_STR (integer)
SNMP_OCTET_STR (integer)
SNMP_OPAQUE (integer)
SNMP_NULL (integer)
SNMP_OBJECT_ID (integer)
SNMP_IPADDRESS (integer)
SNMP_COUNTER (integer)
SNMP_UNSIGNED (integer)
SNMP_TIMETICKS (integer)
SNMP_UINTEGER (integer)
SNMP_INTEGER (integer)
SNMP_COUNTER64 (integer)

Table of Contents

snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting
snmp_get_valueretrieval — Return the method how the SNMP values will be returned
snmp_read_mib — Reads and parses a MIB file into the active MIB tree
snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer
snmp_set_oid_numeric_print — Return all objects including their respective object id within the specified one
snmp_set_oid_output_format — Set the OID output format
snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
snmpget — Fetch an SNMP object
snmpgetnext — Fetch a SNMP object
snmprealwalk — Return all objects including their respective object ID within the specified one
snmpset — Set an SNMP object
snmpwalk — Fetch all the SNMP objects from an agent
snmpwalkoid — Query for a tree of information about a network entity

Code Examples / Notes » ref.snmp

cesarmata2000

With that, i can show the mac of my machine, sorry de english...
<?php
//Bug #36196   SNMP_VALUE_PLAIN
snmp_set_valueretrieval(0);
$mac = snmpget("192.168.0.1",'public',".1.3.6.1.2.1.2.2.1.6.x");
snmp_set_valueretrieval(1);
$mac = str_replace('""',"&nbsp;",$mac);
$mac = str_replace('Hex: ',"",$mac);
$mac = str_replace(' ',":",trim($mac));
print $mac;
?>
P.D.: the .x of the OID, is de index of de Interfaz...
Viva Venezuela y el Software Libre.... =CMM=


jeroen simonetti

The listed functions here use snmp version 1. If you wish to use version 2c or 3, use the following functions:
snmp v2c functions:
snmp2_get (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_getnext (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_real_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_set (string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]])
snmp v3 functions:
snmp3_get (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)
snmp3_getnext (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string pri)
snmp3_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_p)
snmp3_real_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string p)
snmp3_set (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)


thug

Just a quick note on PHP SNMP instalation on Windows machines (IIS 5.x / Win2k SP2 etc...)
I had installed PHP into C:\PHP.. (standard stuff eh?)
Whilst I had followed the instructions for the installation of SNMP (put php_snmp.dll in extension_dir, uncomment entry in php.ini and all mib files located on the same drive where php was installed  (in this case c:\usr\mibs right?) I still ran into trouble like "Cannot find module (IP-MIB): At line 0 in (none)..." appearing on the bottom of every php that page I was viewing which existed on a drive other than C:\ drive...
It seams that the mibs dir (and content thereof) have to be located on every volume where a php file will be executed from.
For example :-
If you have a php file as "C:\INETPUB\WWWROOT\snmp1.php" then the coresponding "C:\USR\MIBS\*.*" has to be present (as mentioned in the install.txt).
Now here comes the catch...
If you have a "D:\INETPUB\PHPROOT\snmp1.php" file, then a copy of the mib files have to be in "D:\USR\MIBS\*.*" as well (the same mib files that are on the C:\ drive and same basic location <drive>:\USR\MIBS).
(Or in short : Copy the C:\USR dir (inc mibs dir) to *every* drive you intend to have .php files accessed from.  Done!)
Hope this helps other PHParians.
Keep up the *Great* work!!!


http://mike.eire.ca

It seems obvious enough in retrospect, but it doesn't say it anywhere in the (rather poor) SNMP functions documentation.
You can use a non-standard port number in the hostname string.
<?php
$data=snmprealwalk('localhost:261','public',null);
?>


sean boulter

In addition to working on NT as the documentation says, SNMP works on XP if you have the snmp extensions enabled in the ph.ini file, point the ini file to the correct extensions folder, and copy the mibs from the full install package to c:\usr\mibs.

peterd

I've found that when using SNMP on Windows (2000 Pro) the drive the mib files have to be located on actually depends on where you subsequently call PHP from.
For example:
(Assume PHP is installed in c:\\php and the mibs are installed in c:\\usr\\mibs and you have a script c:\\test.php)
Open a command prompt at c:\\
Calling c:\\php\\cli\\php.exe c:\\test.php will work fine.
Change directory to d:\\
Execute c:\\php\\cli\\php.exe c:\\test.php will now cause an error about not finding mib files.
If you now copy the mibs to d:\\usr\\mibs and run the above command again, it will now work fine.
Effectively the drive the mibs has to be on is the same as the drive of the current working directory when you call PHP.
This isn't very useful at all, so after some digging around there seems to be an environment variable (MIBDIRS) you can set specifying where the MIBs are to be found.
After setting MIBDIRS=c:\\php\\mibs in the environment and placing the mibs there, everything seemed to work fine.
Note: If you need SNMP whilst using apache you may have to use the PassEnv command with MIBDIRS in your apache config, I haven't tried this yet.


amit_gupta

I was struggling to compile PHP 4.3.8/PHP-5 with net-snmp-5.1 RPMS .  It was continously showing errors during make. Later I first complied and installed net-snmp-5.1  on fedora system. With this compiled Net-snmp , I could install PHP 4.3.8/php5 successfully. So if you are also getting error during make command during installation of PHP, first compile net-snmp instaead of using its RPM.
Amit Gupta


tim

I had a problem getting mib errors on my php5 and IIS install.  Ended up adding an environmental variable to the Win2k box and that fixed it.  Had to add MIBDIRS=C:\PHP\extras\mibs
After I added this and booted the server I was no longer getting the errors.


mcotner

Hi all,
I had a need for mass polling of many devices and bulkgets were very desirable.  It turns out the change was simpler than I thought.
One word of warning, however.  The version is set in such a way that if I were to keep the changes to a minimum all operations that weren't v3 needed to be set to v2c.  This isn't a problem for us because we have no v1 specific devices.  If you're polling any v1 ONLY agents then you will have issues with this patch.  
Here's the patch.  I hope this helps.
Just save it to /tmp/patch
cd ext/snmp/
patch snmp.c /tmp/patch
'njoy,
Mark
--- snmp.c 2003-08-07 12:44:11.000000000 -0400
+++ /tmp/snmp.c 2004-02-24 22:03:22.000000000 -0500
@@ -405,7 +405,11 @@
RETURN_FALSE;
}
} else if (st >= 2) {
- pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
+            int reps = 20, non_reps = 0;
+
+ pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
+            pdu->non_repeaters = non_reps;
+            pdu->max_repetitions = reps;    /* fill the packet */
snmp_add_null_var(pdu, name, name_length);
}

@@ -471,7 +475,7 @@
goto retry;
}
} else if (st >= 2) {
- if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GETNEXT)) != NULL) {
+ if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GETBULK)) != NULL) {
goto retry;
}
}
@@ -579,7 +583,7 @@

session.peername = hostname;
session.remote_port = remote_port;
- session.version = SNMP_VERSION_1;
+ session.version = SNMP_VERSION_2c;
/*
* FIXME: potential memory leak
* This is a workaround for an "artifact" (Mike Slifcak)


chris

Here's a fresh list of API for SNMPv1, SNMPv2c, and SNMPv3 as of PHP 5.2.4:
SNMPv1
------
string snmpget(string host, string community, string object_id [, int timeout [, int retries]]);
string snmpgetnext(string host, string community, string object_id [, int timeout [, int retries]]);
array snmpwalk(string host, string community, string object_id [, int timeout [, int retries]]);
array snmprealwalk(string host, string community, string object_id [, int timeout [, int retries]]);
bool snmp_get_quick_print(void);
void snmp_set_quick_print(int quick_print);
void snmp_set_enum_print(int enum_print);
void snmp_set_oid_output_format(int oid_format);
int snmpset(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);
SNMPv2c
-------
string snmp2_get(string host, string community, string object_id [, int timeout [, int retries]]);
string snmp2_getnext(string host, string community, string object_id [, int timeout [, int retries]]);
array snmp2_walk(string host, string community, string object_id [, int timeout [, int retries]]);
array snmp2_real_walk(string host, string community, string object_id [, int timeout [, int retries]]);
int snmp2_set(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);
SNMPv3
------
int snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);
int snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);
int snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);
int snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);
int snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id, string type, mixed value [, int timeout [, int retries]]);
General
-------
int snmp_set_valueretrieval(int method);
int snmp_get_valueretrieval();
int snmp_read_mib(string filename);
SNMPv3 options
--------------
SNMPv3 offers a different authentication/authorization scheme than previous versions of SNMP.  To aid in using the API listed above, here is a brief explanation of each of the unique parameters used in the snmp3_* functions.
$sec_name - the "username" used for authentication to the system
$sec_level - the authentication scheme ('noAuthNoPriv', 'authNoPriv', or 'authPriv')
$auth_protocol - the encryption protocol used for authentication ('MD5' [default] or 'SHA')
$auth_passphrase - the encrypted key to use as the authentication challenge
$priv_protocol - the encryption protocol used for protecting the protocol data unit ('DES' [default], 'AES128', 'AES192', or 'AES256')
$priv_passphrase - the key to use for encrypting the protocol data unit
There are good code snippets available on http://forums.cacti.net/about5403.html for more information.


ch

For some devices one needs a string index, i.e.
 activeSessions.activeSession-inputOctets."ABC"
On commandline this is possible with the "-Ir" flag. PHP does not
seem to like it regardless of the quoting. Converting the string index to a numeric OID is quite simple though, it becomes:
 activeSessions.activeSession-inputOctets.3.41.42.43
function getNumericStringIndex($string_idx) {
    $string_idx = substr($string_idx, 1, strlen($string_idx)-2);
    $ret = strlen($string_idx);
    for ($i=0; $i<strlen($string_idx); $i++)
       $ret .= '.'.ord($string_idx[$i]);
    return $ret;
}


1413

For my purposes in PHP coding, I have the following SNMP options set, always.  These aren't documented very well in PHP's docs, but they make dealing with the SNMP results a LOT easier:
<?php
// Return back the numeric OIDs, instead of text strings.
snmp_set_oid_numeric_print(1);
// Get just the values.
snmp_set_quick_print(TRUE);
// For sequence types, return just the numbers, not the string and numbers.
snmp_set_enum_print(TRUE);
// Don't let the SNMP library get cute with value interpretation.  This makes
// MAC addresses return the 6 binary bytes, timeticks to return just the integer
// value, and some other things.
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);  
?>


tom

As of Net-SNMP 5.1.2 the file config.h is now called acconfig.h. This is where you will find and uncomment the line
#define NO_ZEROLENGTH_COMMUNITY 1
as described in the manual above.
I've been looking for the file for about 20 minutes before I located it by the new name.


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker