public function __construct($Host, $Community) { //check snmp module if (!@extension_loaded('snmp')) { if (!@dl('snmp.so')) { die('Unable to Load SNMP Module'); } } snmp_set_valueretrieval(SNMP_VALUE_PLAIN); $this->Host = $Host; $this->Community = $Community; $this->RandomNumber = rand(1, 65535); //$this->RandomNumber = rand(); }
/** * Define connection target * * @param string $host * @param int $port * @param string $community */ public function connect($host, $port = 161, $community = "public", $timeout = 2, $retries = 2, $SNMP_VALUE_PLAIN = false) { if (is_null($port)) { $port = self::DEFAULT_PORT; } $this->community = $community; $this->host = $host; $this->port = $port; $this->timeout = !$timeout ? self::DEFAULT_TIMEOUT : $timeout; $this->timeout = $this->timeout * 100000; $this->retries = $retries ? $retries : self::DEFAULT_RETRIES; $this->snmpValuePlain = $SNMP_VALUE_PLAIN; if ($SNMP_VALUE_PLAIN == true) { @snmp_set_valueretrieval(SNMP_VALUE_PLAIN); } else { @snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); } }
function _getpeersfromrouter($config) { if ($config['snmp_community'] == '') { die('no community value set'); } if (!$config['hostname']) { die('no hostname value set'); } snmp_set_oid_numeric_print(1); snmp_set_valueretrieval(SNMP_VALUE_PLAIN); if ($raw_snmp = snmpwalkoid($config['hostname'] . ':' . $config['port'], $config['snmp_community'], $this->base_oid)) { if ($rawfile = fopen($this->cachefile, 'w')) { fputs($rawfile, serialize($raw_snmp)); } else { die('could not write to cache file! ' . $this->cachefile); } } else { die('connection to router failed!'); } }
<?php # Program: Topology-Spanningtree.php # Programmer: Remo Rickli $printable = 1; error_reporting(1); snmp_set_quick_print(1); snmp_set_oid_numeric_print(1); snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); include_once ("inc/header.php"); include_once ("inc/libdev.php"); include_once ("inc/libsnmp.php"); $_GET = sanitize($_GET); $dev = isset($_GET['dev']) ? $_GET['dev'] : ""; $shg = isset($_GET['shg']) ? "checked" : ""; $vln = isset($_GET['vln']) ? $_GET['vln'] : ""; ?> <h1>Spanningtree Tool</h1> <form method="get" action="<?= $self ?>.php" name="stree"> <table class="content"><tr class="<?= $modgroup[$self] ?>1"> <th width="50"><a href="<?= $self ?>.php"><img src="img/32/<?= $selfi ?>.png"></a></th> <th> Device <select size="1" name="dev" onchange="document.stree.vln.value=''"> <option value=""><?= $sellbl ?> -> <?php $link = DbConnect($dbhost,$dbuser,$dbpass,$dbname); $query = GenQuery('devices','s','device,devip,services,snmpversion,readcomm,location,contact,cliport,icon','device','',array('services & 2','snmpversion'),array('=','!='),array('2','0'),array('AND') );
$writetimeout = $writetimeout * 1000000; // Для модели DGS-3100-24TG увеличиваем время ожидания вдвое if ($ModelType == 'DGS-3100-24TG') { $timeout = $timeout * 2; $max_exec_time = $max_exec_time * 2; } // Устанавливаем максимальное время исполнения скрипта ini_set('max_execution_time', $max_exec_time); // Устанавливаем сокращенный вывод для snmp-запросов snmp_set_quick_print(1); // Устанавливаем числовой вывод для snmp-запросов если версия PHP старше 5.2 if (substr(phpversion(), 0, 3) > 5.2) { @snmp_set_enum_print(1); } // Устанавливаем тип вывода для snmp-запросов snmp_set_valueretrieval(0); // По умолчанию ошибок не обнаружено, о чем сообщаем в значении переменной $noerrors = "true"; // Определяем значение версии модуля на случай, если оно не определено в самом модуле $modulever = '0.00'; // Текущая версия скрипта $current_version = '0.99b'; // Подключаем блок c информацией о коммутаторе include 'infosw.php'; // Подключаем основной модуль @(include './modules/' . $module . '_mod.php'); //<--Начало блока:'Формирование верхнего меню со вкладками'-- // Говорим, что по дефолту у нас как минимум 1 колонка (модуль) $col_count = 1; // Считаем, сколько модулей определено всего while (isset(${'menu_item' . $col_count})) {
function snmp_audit($ip, $credentials, $display) { error_reporting(E_ALL); $CI =& get_instance(); $log = new stdClass(); $log->file = 'system'; $log->severity = 7; if ($display == 'y') { $log->display = 'y'; } else { $log->display = 'n'; } if (!extension_loaded('snmp')) { $log->message = 'SNMP PHP function not loaded hence not attempting to run snmp_helper::snmp_audit function'; $log->severity = 5; stdlog($log); unset($log); return false; } else { $log->message = 'SNMP PHP function loaded and attempting to run snmp_helper::snmp_audit function'; stdlog($log); } # we need an ip address if (empty($ip)) { $log->message = 'SNMP command received no ip address'; $log->severity = 5; stdlog($log); unset($log); return false; } elseif (!filter_var($ip, FILTER_VALIDATE_IP)) { $log->message = 'SNMP command received invalid ip address'; $log->severity = 5; stdlog($log); unset($log); return false; } else { $log->message = 'snmp_helper::snmp_audit function received ip ' . $ip; stdlog($log); } if (empty($credentials) or !is_object($credentials)) { $log->message = 'SNMP snmp_helper::snmp_audit received no credentials for ' . $ip; $log->severity = 5; stdlog($log); unset($log); return false; } else { $log->message = 'snmp_helper::snmp_audit function received credentials for ip ' . $ip; stdlog($log); } # new in 1.5 - remove the type from the returned SNMP query. # this affects the snmp_clean function in this file snmp_set_valueretrieval(SNMP_VALUE_PLAIN); snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); $details = new stdClass(); $module = new stdclass(); $return_ips = new stdClass(); $return_ips->item = array(); $details->ip = (string) $ip; $details->manufacturer = ''; $details->serial = ''; $details->model = ''; $details->type = ''; $details->sysDescr = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.1.0"); $details->description = $details->sysDescr; $details->sysContact = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.4.0"); $details->contact = $details->sysContact; $details->sysName = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.5.0"); $details->hostname = $details->sysName; $details->name = $details->sysName; $details->sysLocation = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.6.0"); $details->location = $details->sysLocation; // uptime $details->sysUpTime = intval(my_snmp_get($ip, $credentials, "1.3.6.1.6.3.10.2.1.3.0")) * 100; if (empty($details->sysUpTime)) { $details->sysUpTime = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.3.0"); } if (empty($details->sysUpTime)) { $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.3.0"); if ($i > '' and strpos($i, ")") !== false) { $j = explode(")", $i); $details->uptime = intval(trim($j[1]) * 24 * 60 * 60); } else { $details->uptime = ''; } } // OID $details->sysObjectID = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.2.0"); $details->snmp_oid = $details->sysObjectID; if ($details->snmp_oid > '') { $details->manufacturer = get_oid($details->snmp_oid); if ($details->manufacturer == 'net-snmp') { $details->manufacturer = (string) ''; } } # sometimes we get an OID, but not enough to specify a manufacturer $explode = explode(".", $details->snmp_oid); if (!isset($explode[6])) { $vendor_oid = 0; if (strpos($details->sysDescr, "ZyXEL") !== false) { # we have a Zyxel device $vendor_oid = 890; } } else { $vendor_oid = intval($explode[6]); } if (file_exists(BASEPATH . '../application/helpers/snmp_' . $vendor_oid . '_helper.php')) { $log->message = 'snmp_helper::snmp_audit is loading the snmp helper for ' . $vendor_oid . ' when scanning ' . $ip; stdlog($log); unset($get_oid_details); include 'snmp_' . $vendor_oid . "_helper.php"; $new_details = $get_oid_details($ip, $credentials, $details->snmp_oid); foreach ($new_details as $key => $value) { $details->{$key} = $value; } unset($new_details); } else { $log->message = 'snmp_helper::snmp_audit could not load the snmp helper for ' . $vendor_oid . ' when scanning ' . $ip; $log->severity = 6; stdlog($log); $log->severity = 7; } if (!empty($details->sysDescr) and stripos($details->sysDescr, 'dd-wrt') !== false) { $details->os_group = 'Linux'; $details->os_name = 'DD-WRT'; $details->type = 'router'; } if (!empty($details->sysDescr) and stripos($details->sysDescr, "Darwin Kernel Version 12") !== false) { $details->manufacturer = "Apple Inc"; $details->os_family = 'Apple OSX'; } if (!empty($details->manufacturer) and (stripos($details->manufacturer, 'tplink') !== false or stripos($details->manufacturer, 'tp-link') !== false)) { $details->manufacturer = 'TP-Link Technology Co.,Ltd'; } if (!empty($details->sysDescr) and stripos($details->sysDescr, 'buffalo terastation') !== false) { $details->manufacturer = 'Buffalo'; $details->model = 'TeraStation'; $details->type = 'nas'; } if (!empty($details->sysDescr) and (stripos($details->sysDescr, 'synology') !== false or stripos($details->sysDescr, 'diskstation') !== false)) { $details->manufacturer = 'Synology'; $temp = my_snmp_get($ip, $credentials, "1.3.6.1.4.1.6574.1.5.1.0"); $details->model = trim('DiskStation ' . $temp); $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.4.1.6574.1.5.2.0"); $details->type = 'nas'; $details->os_group = 'Linux'; $details->os_family = 'Synology DSM'; $details->os_name = 'Synology ' . my_snmp_get($ip, $credentials, "1.3.6.1.4.1.6574.1.5.3.0"); } // guess at manufacturer using entity mib if (empty($details->manufacturer)) { $details->manufacturer = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.12.1"); } // guess at model using entity mib if (empty($details->model)) { $details->model = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.13"); } // guess at model using host resources mib if (empty($details->model)) { $details->model = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.25.3.2.1.3.1"); } // serial if (empty($details->serial)) { $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.11"); } if (empty($details->serial)) { $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.11.1"); } if (empty($details->serial)) { $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.11.1.0"); } # generic snmp if (empty($details->serial)) { $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.5.1.1.17.1"); } # below is another generic attempt - works for my NetGear Cable Modem if (empty($details->serial)) { $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.4.1.4491.2.4.1.1.1.3.0"); } $log->message = 'snmp_helper::snmp_audit thinks ' . $ip . ' is a type:' . $details->type . ' model:' . $details->model . ' serial:' . $details->serial; stdlog($log); // subnet if (empty($details->subnet)) { $details->subnet = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.4.20.1.3." . $details->ip); } // mac address if (empty($details->mac_address)) { $interface_number = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.4.20.1.2." . $ip); snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); $details->mac_address = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.2.2.1.6." . $interface_number); snmp_set_valueretrieval(SNMP_VALUE_PLAIN); $details->mac_address = format_mac($details->mac_address); } // last attempt at a MAC - just use whatever's in the first interface MAC if (empty($details->mac_address)) { snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); $details->mac_address = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.2.2.1.6.1"); snmp_set_valueretrieval(SNMP_VALUE_PLAIN); $details->mac_address = format_mac($details->mac_address); } $log->message = 'snmp_helper::snmp_audit MAC Address for ' . $ip . ' is ' . $details->mac_address; stdlog($log); // type if (empty($details->type) or $details->type == 'network printer') { $h = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.25.3.2.1.2.1"); if ($h == '1.3.6.1.2.1.25.3.1.5') { # we have a printer $details->type = 'network printer'; $i = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.13.4.1.10.1"); if (count($i) > 0) { $details->printer_duplex = 'n'; for ($k = 0; $k < count($i); $k++) { if (mb_strpos($i[$k], "Duplex") !== false) { $details->printer_duplex = 'y'; } } } if (empty($details->manufacturer)) { $hex = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.8.2.1.14.1"); if (count($hex) > 0) { if (isset($hex[1])) { if (mb_strpos($hex[1], "Hex-STRING: ") !== false) { $hex[1] = str_replace("Hex-STRING: ", "", $hex[1]); for ($i = 0; $i < strlen($hex[1]); $i++) { $details->manufacturer .= chr(hexdec(substr($hex[1], $i, 2))); } } else { $details->manufacturer = str_replace("STRING: ", "", $hex[1]); $details->manufacturer = str_replace('"', '', $details->manufacturer); } } } } $details->printer_color = 'n'; $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.11.1.1.6.1.2"); if (strpos(strtolower($i), "cartridge") !== false) { # it's likely this is a colour printer $details->printer_color = 'y'; } } else { # If the device is a Switch, the OID 1.3.6.1.2.1.17.1.2.0 is an integer and # OID 1.3.6.1.2.1.4.1.0 should have a value of 2 $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.17.1.2.0"); $j = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.4.1.0"); if ($i == intval($i) and $j == '2') { $details->type = 'switch'; } # If the device is a Router, the OID 1.3.6.1.2.1.4.1.0 should have a value of 1 (already read above) if (empty($details->type)) { if ($i == '1') { $details->type = 'router'; } } # If the device is a Printer, the OID 1.3.6.1.2.1.43.5.1.1.1.1 should have a value #if (!isset($details->type) or $details->type == '') { $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.5.1.1.1.1"); if (strpos(strtolower($i), "counter32") !== false) { $details->type = 'network printer'; // printer duplex $details->printer_duplex = ''; $i = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.13.4.1.10.1"); if (count($i) > 0) { $details->printer_duplex = 'n'; for ($k = 0; $k < count($i); $k++) { if (mb_strpos($i[$k], "Duplex") !== false) { $details->printer_duplex = 'y'; } } } if (empty($details->manufacturer)) { $hex = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.8.2.1.14.1"); if (count($hex) > 0) { if (isset($hex[1])) { if (mb_strpos($hex[1], "Hex-STRING: ") !== false) { $hex[1] = str_replace("Hex-STRING: ", "", $hex[1]); for ($i = 0; $i < strlen($hex[1]); $i++) { $details->manufacturer .= chr(hexdec(substr($hex[1], $i, 2))); } } else { $details->manufacturer = str_replace("STRING: ", "", $hex[1]); $details->manufacturer = str_replace('"', '', $details->manufacturer); } } } } $details->printer_color = 'n'; $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.11.1.1.6.1.2"); if (strpos(strtolower($i), "cartridge") !== false) { # it's likely this is a colour printer $details->printer_color = 'y'; } } } } // modules - NOTE, we call these 'entities' in the web interface $log->message = 'snmp_helper::snmp_audit module retrieval for ' . $ip . ' starting'; stdlog($log); $modules = array(); $modules_list = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.2"); if (isset($modules_list) and is_array($modules_list) and count($modules_list) > 0) { $log->message = 'snmp_helper::snmp_audit module count for ' . $ip . ' is ' . count($modules_list); stdlog($log); $log->message = 'snmp_helper::snmp_audit object_id retrieval for ' . $ip . ' starting'; stdlog($log); $temp_object_id = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.3'); $log->message = 'snmp_helper::snmp_audit contained_in retrieval for ' . $ip . ' starting'; stdlog($log); $temp_contained_in = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.4'); $log->message = 'snmp_helper::snmp_audit class retrieval for ' . $ip . ' starting'; stdlog($log); $temp_class = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.5'); $log->message = 'snmp_helper::snmp_audit hardware_revision retrieval for ' . $ip . ' starting'; stdlog($log); $temp_hardware_revision = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.8'); $log->message = 'snmp_helper::snmp_audit firmware_revision retrieval for ' . $ip . ' starting'; stdlog($log); $temp_firmware_revision = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.9'); $log->message = 'snmp_helper::snmp_audit software_revision retrieval for ' . $ip . ' starting'; stdlog($log); $temp_software_revision = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.10'); $log->message = 'snmp_helper::snmp_audit serial_number retrieval for ' . $ip . ' starting'; stdlog($log); $temp_serial_number = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.11'); $log->message = 'snmp_helper::snmp_audit asset_id retrieval for ' . $ip . ' starting'; stdlog($log); $temp_asset_id = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.15'); $log->message = 'snmp_helper::snmp_audit is_fru retrieval for ' . $ip . ' starting'; stdlog($log); $temp_is_fru = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.16'); foreach ($modules_list as $key => $value) { $log->message = 'snmp_helper::snmp_audit processing module ' . $value . ' for ' . $ip . ' starting'; stdlog($log); $module = new stdClass(); $module->description = $value; $module->module_index = str_replace('.1.3.6.1.2.1.47.1.1.1.1.2.', '', $key); $module->object_ident = $temp_object_id['.1.3.6.1.2.1.47.1.1.1.1.3.' . $module->module_index]; $module->contained_in = $temp_contained_in['.1.3.6.1.2.1.47.1.1.1.1.4.' . $module->module_index]; $module->class = $temp_class['.1.3.6.1.2.1.47.1.1.1.1.5.' . $module->module_index]; $module->hardware_revision = $temp_hardware_revision['.1.3.6.1.2.1.47.1.1.1.1.8.' . $module->module_index]; $module->firmware_revision = $temp_firmware_revision['.1.3.6.1.2.1.47.1.1.1.1.9.' . $module->module_index]; $module->software_revision = $temp_software_revision['.1.3.6.1.2.1.47.1.1.1.1.10.' . $module->module_index]; $module->serial = $temp_serial_number['.1.3.6.1.2.1.47.1.1.1.1.11.' . $module->module_index]; $module->asset_ident = $temp_asset_id['.1.3.6.1.2.1.47.1.1.1.1.15.' . $module->module_index]; $module->is_fru = $temp_is_fru['.1.3.6.1.2.1.47.1.1.1.1.16.' . $module->module_index]; if ((string) $module->is_fru == '1') { $module->is_fru = 'y'; } else { $module->is_fru = 'n'; } $module->class_text = 'unknown'; if ($module->class == '1') { $module->class_text = 'other'; } if ($module->class == '2') { $module->class_text = 'unknown'; } if ($module->class == '3') { $module->class_text = 'chassis'; } if ($module->class == '4') { $module->class_text = 'backplane'; } if ($module->class == '5') { $module->class_text = 'container'; } if ($module->class == '6') { $module->class_text = 'powerSupply'; } if ($module->class == '7') { $module->class_text = 'fan'; } if ($module->class == '8') { $module->class_text = 'sensor'; } if ($module->class == '9') { $module->class_text = 'module'; } if ($module->class == '10') { $module->class_text = 'port'; } if ($module->class == '11') { $module->class_text = 'stack'; } if ($module->class == '12') { $module->class_text = 'cpu'; } $modules[] = $module; } } $log->message = 'snmp_helper::snmp_audit module retrieval for ' . $ip . ' complete'; stdlog($log); // network intereface details $interfaces = array(); $interfaces_filtered = array(); $interfaces = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.1"); $log->message = 'snmp_helper::snmp_audit interface count for ' . $ip . ' is ' . count($interfaces); stdlog($log); if (is_array($interfaces) and count($interfaces) > 0) { $log->message = 'snmp_helper::snmp_audit models retrieval for ' . $ip . ' starting'; stdlog($log); $models = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.2"); $log->message = 'snmp_helper::snmp_audit types retrieval for ' . $ip . ' starting'; stdlog($log); $types = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.3"); $log->message = 'snmp_helper::snmp_audit speeds retrieval for ' . $ip . ' starting'; stdlog($log); $speeds = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.5"); $log->message = 'snmp_helper::snmp_audit mac_addresses retrieval for ' . $ip . ' starting'; stdlog($log); $mac_addresses = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.6"); $log->message = 'snmp_helper::snmp_audit ip_enableds retrieval for ' . $ip . ' starting'; stdlog($log); $ip_enableds = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.8"); $log->message = 'snmp_helper::snmp_audit ip_addresses retrieval for ' . $ip . ' starting'; stdlog($log); $ip_addresses = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.4.20.1.2"); $log->message = 'snmp_helper::snmp_audit ifAdminStatus retrieval for ' . $ip . ' starting'; stdlog($log); $ifAdminStatus = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.7"); $log->message = 'snmp_helper::snmp_audit ifLastChange retrieval for ' . $ip . ' starting'; stdlog($log); $ifLastChange = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.9"); if (isset($details->os_group) and $details->os_group == "VMware") { $log->message = 'snmp_helper::snmp_audit ip_addresses_2 retrieval for ' . $ip . ' starting'; stdlog($log); $ip_addresses_2 = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.4.34.1.3.1.4"); } $log->message = 'snmp_helper::snmp_audit subnets retrieval for ' . $ip . ' starting'; stdlog($log); $subnets = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.4.20.1.3"); $log->message = 'snmp_helper::snmp_audit connection_ids retrieval for ' . $ip . ' starting'; stdlog($log); $connection_ids = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.31.1.1.1.1"); $log->message = 'snmp_helper::snmp_audit aliases retrieval for ' . $ip . ' starting'; stdlog($log); $aliases = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.31.1.1.1.18"); foreach ($interfaces as $key => $value) { $log->message = 'snmp_helper::snmp_audit processing interface ' . $value . ' for ' . $ip . ' starting'; stdlog($log); $interface = new stdclass(); $interface->net_index = $value; snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); $interface->mac = format_mac(my_snmp_get($ip, $credentials, "1.3.6.1.2.1.2.2.1.6." . $interface->net_index)); snmp_set_valueretrieval(SNMP_VALUE_PLAIN); if (!isset($interface->mac)) { $interface->mac = (string) ''; } $interface->model = @$models[".1.3.6.1.2.1.2.2.1.2." . $interface->net_index]; $interface->description = $interface->model; $interface->connection = @$connection_ids[".1.3.6.1.2.1.31.1.1.1.1." . $interface->net_index]; $interface->alias = @$aliases[".1.3.6.1.2.1.31.1.1.1.18." . $interface->net_index]; $interface->type = @interface_type(@$types[".1.3.6.1.2.1.2.2.1.3." . $interface->net_index]); $interface->ip_enabled = @ip_enabled($ip_enableds[".1.3.6.1.2.1.2.2.1.8." . $interface->net_index]); $interface->ifadminstatus = @if_admin_status($ifAdminStatus[".1.3.6.1.2.1.2.2.1.7." . $interface->net_index]); $interface->iflastchange = @$ifLastChange[".1.3.6.1.2.1.2.2.1.9." . $interface->net_index]; $interface->speed = @$speeds[".1.3.6.1.2.1.2.2.1.5." . $interface->net_index]; $interface->manufacturer = ''; $interface->connection_status = ''; $interface->dhcp_enabled = ''; $interface->dhcp_server = ''; $interface->dhcp_lease_obtained = ''; $interface->dhcp_lease_expires = ''; $interface->dns_host_name = ''; $interface->dns_domain = ''; $interface->dns_domain_reg_enabled = ''; $interface->dns_server = ''; if (is_array($ip_addresses) and count($ip_addresses > 0)) { foreach ($ip_addresses as $each_key => $each_value) { if ($each_value == $interface->net_index) { $new_ip = new stdclass(); $new_ip->net_index = $interface->net_index; $new_ip->ip = str_replace(".1.3.6.1.2.1.4.20.1.2.", "", $each_key); $new_ip->mac = $interface->mac; $new_ip->netmask = @$subnets[".1.3.6.1.2.1.4.20.1.3." . $new_ip->ip]; $new_ip->version = '4'; if ($new_ip->ip != '127.0.0.1' and $new_ip->ip != '127.0.1.1') { $return_ips->item[] = $new_ip; } $new_ip = null; } } } if (isset($ip_addresses_2) and is_array($ip_addresses_2) and isset($details->os_group) and $details->os_group == "VMware") { // likely we have a VMware ESX box - get what we can foreach ($ip_addresses_2 as $each_key => $each_value) { $new_ip = new stdClass(); $new_ip->net_index = $each_value; $new_ip->ip = str_replace(".1.3.6.1.2.1.4.34.1.3.1.4.", "", $each_key); $new_ip->netmask = ''; $new_ip->version = '4'; if ($new_ip->net_index == $interface->net_index) { $new_ip->mac = $interface->mac; if ($new_ip->ip != '127.0.0.1' and $new_ip->ip != '127.0.1.1') { $return_ips->item[] = $new_ip; } } $new_ip = null; } } if (isset($details->os_group) and $details->os_group == 'Windows') { if (isset($interface->ip_addresses) and count($interface->ip_addresses) > 0) { if (strpos(strtolower($interface->type), 'loopback') === false) { $interfaces_filtered[] = $interface; } } } else { if (strtolower($interface->type != 'software loopback')) { $interfaces_filtered[] = $interface; } } } } // end of network interfaces // Virtual Guests $guests = array(); if ($vendor_oid == 6876) { if (file_exists(BASEPATH . '../application/helpers/snmp_6876_2_helper.php')) { $log->message = 'snmp_helper::snmp_audit is loading the model helper for VMware virtual guests'; stdlog($log); include 'snmp_6876_2_helper.php'; } } $return_array = array('details' => $details, 'interfaces' => $interfaces_filtered, 'guests' => $guests, 'modules' => $modules, 'ip' => $return_ips); return $return_array; }
/** * Define connection target * * @param string $host * @param int $port * @param string $community */ public function Connect($host, $port=161, $community="public", $timeout = false, $retries = false, $SNMP_VALUE_PLAIN = false) { if (is_null($port)) $port = self::DEFAULT_PORT ; //$this->Connection = "{$host}:{$port}"; $this->Connection = "{$host}"; $this->Community = $community; if (!$timeout) $this->Timeout = (!defined("SNMP_TIMEOUT")) ? self::DEFAULT_TIMEOUT : SNMP_TIMEOUT; else $this->Timeout = $timeout; $this->Timeout = $this->Timeout*100000; $this->Retries = $retries ? $retries : self::DEFAULT_RETRIES; if ($SNMP_VALUE_PLAIN == true) @snmp_set_valueretrieval(SNMP_VALUE_PLAIN); else @snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); }
function net_dev_show($type, $name, $port, $vg_id) { $row = $GLOBALS['monkdb']->query('select * from net_devs where type="' . $type . '" and name="' . $name . '"')->fetch_assoc(); $iprow = $GLOBALS['billdb']->query('select segment from staff where vg_id=' . $vg_id)->fetch_assoc(); if ($row['type'] == 'switch') { if ($row['snmp_version'] == '2c') { snmp_set_valueretrieval(SNMP_VALUE_PLAIN); $ifOperStatus = snmp2_get($row['mgmt_ip'], 'public', 'RFC1213-MIB::ifOperStatus.' . $port); switch ($ifOperStatus) { case '1': echo 'port - <b>up</b><br/>'; break; case '2': echo 'port - <b>down</b><br/>'; break; } $ip_mac_vlan = ip_mac_vlan(long2ip($iprow['segment'])); if ($ip_mac_vlan) { echo 'vlan - <b>' . $ip_mac_vlan['vlan'] . '</b><br/>'; echo 'ip - <b>' . $ip_mac_vlan['ip'] . '</b><br/>'; echo 'mac - <b>' . $ip_mac_vlan['mac'] . '</b><br/>'; } $snmp_mac_table = snmp2_real_walk($row['mgmt_ip'], 'public', '1.3.6.1.2.1.17.7.1.2.2.1.2'); foreach ($snmp_mac_table as $key => $row1) { $arr = explode('2.17.7.1.2.2.1.2.', $key); $arr = explode('.', $arr[1]); if ($row1 == $port) { echo 'SNMP data - <b>' . dechex($arr[1]) . ':' . dechex($arr[2]) . ':' . dechex($arr[3]) . ':' . dechex($arr[4]) . ':' . dechex($arr[5]) . ':' . dechex($arr[6]) . ' , vlan=' . $arr[0] . ' , port=' . $row1 . "</b><br/>\n"; } } } if ($row['snmp_version'] == '1') { snmp_set_valueretrieval(SNMP_VALUE_PLAIN); $ifOperStatus = snmpget($row['mgmt_ip'], 'public', 'IF-MIB::ifOperStatus.' . $port); switch ($ifOperStatus) { case '1': echo 'port - <b>up</b><br/>'; break; case '2': echo 'port - <b>down</b><br/>'; break; } $ip_mac_vlan = ip_mac_vlan(long2ip($iprow['segment'])); if ($ip_mac_vlan) { echo 'vlan - <b>' . $ip_mac_vlan['vlan'] . '</b><br/>'; echo 'ip - <b>' . $ip_mac_vlan['ip'] . '</b><br/>'; echo 'mac - <b>' . $ip_mac_vlan['mac'] . '</b><br/>'; } } } if ($row['type'] == 'dslam') { if ($row['snmp_version'] == '2c') { snmp_set_valueretrieval(SNMP_VALUE_PLAIN); $port = $port + $row['if_index_shift']; $ifOperStatus = snmp2_get($row['mgmt_ip'], 'public', 'IF-MIB::ifOperStatus.' . $port); switch ($ifOperStatus) { case '1': echo 'port - <b>up</b><br/>'; break; case '2': echo 'port - <b>down</b><br/>'; break; } if ($ifOperStatus == '1') { $ip_mac_vlan = ip_mac_vlan(long2ip($iprow['segment'])); if ($ip_mac_vlan) { echo 'vlan - <b>' . $ip_mac_vlan['vlan'] . '</b><br/>'; echo 'ip - <b>' . $ip_mac_vlan['ip'] . '</b><br/>'; echo 'mac - <b>' . $ip_mac_vlan['mac'] . '</b><br/>'; $snmp_mac_table = snmprealwalk($row['mgmt_ip'], 'public', '1.3.6.1.2.1.17.7.1.2.2.1.2'); foreach ($snmp_mac_table as $key => $row1) { $arr = explode('2.17.7.1.2.2.1.2.', $key); $arr = explode('.', $arr[1]); if ($row1 == $port - $row['if_index_shift']) { echo 'SNMP data - <b>' . dechex($arr[1]) . ':' . dechex($arr[2]) . ':' . dechex($arr[3]) . ':' . dechex($arr[4]) . ':' . dechex($arr[5]) . ':' . dechex($arr[6]) . ' , vlan=' . $arr[0] . ' , port=' . $row1 . "</b><br/>\n"; } } echo '<hr/>'; } echo '<br/>'; echo 'ATU-C: Current SNR Margin - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.2.1.4.' . $port) . '</b> db/10<br/>'; echo 'ATU-C: Current attentuation - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.2.1.5.' . $port) . '</b> db/10<br/>'; echo 'ATU-C: Current output power - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.2.1.7.' . $port) . '</b> db/10<br/>'; echo 'ATU-C: Speed - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.2.1.8.' . $port) . '</b> bps<br/>'; echo '<br/>'; echo 'ATU-R: Current SNR Margin - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.3.1.4.' . $port) . '</b> db/10<br/>'; echo 'ATU-R: Current attentuation - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.3.1.5.' . $port) . '</b> db/10<br/>'; echo 'ATU-R: Current output power - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.3.1.7.' . $port) . '</b> db/10<br/>'; echo 'ATU-R: Speed - <b>' . snmp2_get($row['mgmt_ip'], 'public', 'SNMPv2-SMI::transmission.94.1.1.3.1.8.' . $port) . '</b> bps<br/>'; } if ($_SESSION['username'] == 'nalcheg' or $_SESSION['username'] == 'den' or $_SESSION['username'] == 'andrey') { echo '<hr/><b><a href="#" onclick="dslam_port_restart(\'' . $row['mgmt_ip'] . '\',' . $port . ',' . $row['if_index_shift'] . ')">RESTART PORT</a></b>'; } } } }
function cacti_snmp_walk($hostname, $community, $oid, $version, $username, $password, $auth_proto, $priv_pass, $priv_proto, $context, $port = 161, $timeout = 500, $retries = 0, $max_oids = 10, $method = SNMP_VALUE_LIBRARY, $environ = SNMP_POLLER) { global $config, $banned_snmp_strings; $snmp_oid_included = true; $snmp_auth = ''; $snmp_array = array(); $temp_array = array(); /* determine default retries */ if ($retries == 0 || !is_numeric($retries)) { $retries = read_config_option('snmp_retries'); if ($retries == '') { $retries = 3; } } /* do not attempt to poll invalid combinations */ if ($version == 0 || !is_numeric($version) || !is_numeric($max_oids) || !is_numeric($port) || !is_numeric($retries) || !is_numeric($timeout) || $community == '' && $version != 3) { return array(); } $path_snmpbulkwalk = read_config_option('path_snmpbulkwalk'); if (snmp_get_method($version) == SNMP_METHOD_PHP && (!strlen($context) || $version != 3) && ($version == 1 || version_compare(phpversion(), '5.1') >= 0 || !file_exists($path_snmpbulkwalk))) { /* make sure snmp* is verbose so we can see what types of data we are getting back */ /* force php to return numeric oid's */ cacti_oid_numeric_format(); snmp_set_quick_print(0); /* set the output format to numeric */ snmp_set_valueretrieval($method); if ($version == '1') { $temp_array = @snmprealwalk("{$hostname}:{$port}", "{$community}", "{$oid}", $timeout * 1000, $retries); } elseif ($version == '2') { $temp_array = @snmp2_real_walk("{$hostname}:{$port}", "{$community}", "{$oid}", $timeout * 1000, $retries); } else { if ($priv_proto == '[None]') { $proto = 'authNoPriv'; $priv_proto = ''; } else { $proto = 'authPriv'; } $temp_array = @snmp3_real_walk("{$hostname}:{$port}", "{$username}", $proto, $auth_proto, "{$password}", $priv_proto, "{$priv_pass}", "{$oid}", $timeout * 1000, $retries); } if ($temp_array === false) { cacti_log("WARNING: SNMP Walk Timeout for Host:'{$hostname}', and OID:'{$oid}'", false); } /* check for bad entries */ if (is_array($temp_array) && sizeof($temp_array)) { foreach ($temp_array as $key => $value) { foreach ($banned_snmp_strings as $item) { if (strstr($value, $item) != '') { unset($temp_array[$key]); continue 2; } } } $o = 0; for (reset($temp_array); $i = key($temp_array); next($temp_array)) { if ($temp_array[$i] != 'NULL') { $snmp_array[$o]['oid'] = preg_replace('/^\\./', '', $i); $snmp_array[$o]['value'] = format_snmp_string($temp_array[$i], $snmp_oid_included); } $o++; } } } else { /* ucd/net snmp want the timeout in seconds */ $timeout = ceil($timeout / 1000); if ($version == '1') { $snmp_auth = '-c ' . snmp_escape_string($community); /* v1/v2 - community string */ } elseif ($version == '2') { $snmp_auth = '-c ' . snmp_escape_string($community); /* v1/v2 - community string */ $version = '2c'; /* ucd/net snmp prefers this over '2' */ } elseif ($version == '3') { if ($priv_proto == '[None]') { $proto = 'authNoPriv'; $priv_proto = ''; } else { $proto = 'authPriv'; } if (strlen($priv_pass)) { $priv_pass = '******' . snmp_escape_string($priv_pass) . ' -x ' . snmp_escape_string($priv_proto); } else { $priv_pass = ''; } if (strlen($context)) { $context = '-n ' . snmp_escape_string($context); } else { $context = ''; } $snmp_auth = trim('-u ' . snmp_escape_string($username) . ' -l ' . snmp_escape_string($proto) . ' -a ' . snmp_escape_string($auth_proto) . ' -A ' . snmp_escape_string($password) . ' ' . $priv_pass . ' ' . $context); /* v3 - username/password */ } if (file_exists($path_snmpbulkwalk) && $version > 1 && $max_oids > 1) { $temp_array = exec_into_array(cacti_escapeshellcmd($path_snmpbulkwalk) . " -O Qn {$snmp_auth} -v {$version} -t {$timeout} -r {$retries} -Cr{$max_oids} " . cacti_escapeshellarg($hostname) . ":{$port} " . cacti_escapeshellarg($oid)); } else { $temp_array = exec_into_array(cacti_escapeshellcmd(read_config_option('path_snmpwalk')) . " -O Qn {$snmp_auth} -v {$version} -t {$timeout} -r {$retries} " . cacti_escapeshellarg($hostname) . ":{$port} " . cacti_escapeshellarg($oid)); } if (substr_count(implode(' ', $temp_array), 'Timeout:')) { cacti_log("WARNING: SNMP Walk Timeout for Host:'{$hostname}', and OID:'{$oid}'", false); } /* check for bad entries */ if (is_array($temp_array) && sizeof($temp_array)) { foreach ($temp_array as $key => $value) { foreach ($banned_snmp_strings as $item) { if (strstr($value, $item) != '') { unset($temp_array[$key]); continue 2; } } } for ($i = 0; $i < count($temp_array); $i++) { if ($temp_array[$i] != 'NULL') { $snmp_array[$i]['oid'] = trim(preg_replace('/(.*) =.*/', "\\1", $temp_array[$i])); $snmp_array[$i]['value'] = format_snmp_string($temp_array[$i], true); } } } } return $snmp_array; }
/** * read the data into an internal array and also call the parent constructor * * @param String $enc encoding */ public function __construct($enc) { parent::__construct(__CLASS__, $enc); switch (strtolower(PSI_PLUGIN_SNMPPINFO_ACCESS)) { case 'command': if (defined('PSI_PLUGIN_SNMPPINFO_DEVICES') && is_string(PSI_PLUGIN_SNMPPINFO_DEVICES)) { if (preg_match(ARRAY_EXP, PSI_PLUGIN_SNMPPINFO_DEVICES)) { $printers = eval(PSI_PLUGIN_SNMPPINFO_DEVICES); } else { $printers = array(PSI_PLUGIN_SNMPPINFO_DEVICES); } foreach ($printers as $printer) { CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 " . $printer . " .1.3.6.1.2.1.1.5", $buffer, PSI_DEBUG); if (strlen(trim($buffer)) > 0) { $this->_filecontent[$printer] = $buffer; CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 " . $printer . " .1.3.6.1.2.1.43.11.1.1", $buffer2, PSI_DEBUG); if (strlen(trim($buffer2)) > 0) { $this->_filecontent[$printer] = $this->_filecontent[$printer] . "\n" . $buffer2; } CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 " . $printer . " .1.3.6.1.2.1.43.18.1.1", $buffer3, PSI_DEBUG); if (strlen(trim($buffer3)) > 0) { $this->_filecontent[$printer] = $this->_filecontent[$printer] . "\n" . $buffer3; } } } } break; case 'php-snmp': snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); if (defined('PSI_PLUGIN_SNMPPINFO_DEVICES') && is_string(PSI_PLUGIN_SNMPPINFO_DEVICES)) { if (preg_match(ARRAY_EXP, PSI_PLUGIN_SNMPPINFO_DEVICES)) { $printers = eval(PSI_PLUGIN_SNMPPINFO_DEVICES); } else { $printers = array(PSI_PLUGIN_SNMPPINFO_DEVICES); } foreach ($printers as $printer) { if (!PSI_DEBUG) { restore_error_handler(); /* default error handler */ $old_err_rep = error_reporting(); error_reporting(E_ERROR); /* fatal errors only */ } $bufferarr = snmprealwalk($printer, "public", ".1.3.6.1.2.1.1.5", 1000000, 1); if (!PSI_DEBUG) { error_reporting($old_err_rep); /* restore error level */ set_error_handler('errorHandlerPsi'); /* restore error handler */ } if (!empty($bufferarr)) { $buffer = ""; foreach ($bufferarr as $id => $string) { $buffer = $buffer . $id . " = " . $string . "\n"; } if (!PSI_DEBUG) { restore_error_handler(); /* default error handler */ $old_err_rep = error_reporting(); error_reporting(E_ERROR); /* fatal errors only */ } $bufferarr2 = snmprealwalk($printer, "public", ".1.3.6.1.2.1.43.11.1.1", 1000000, 1); if (!PSI_DEBUG) { error_reporting($old_err_rep); /* restore error level */ set_error_handler('errorHandlerPsi'); /* restore error handler */ } if (!empty($bufferarr2)) { foreach ($bufferarr2 as $id => $string) { $buffer = $buffer . $id . " = " . $string . "\n"; } } if (!PSI_DEBUG) { restore_error_handler(); /* default error handler */ $old_err_rep = error_reporting(); error_reporting(E_ERROR); /* fatal errors only */ } $bufferarr3 = snmprealwalk($printer, "public", ".1.3.6.1.2.1.43.18.1.1", 1000000, 1); if (!PSI_DEBUG) { error_reporting($old_err_rep); /* restore error level */ set_error_handler('errorHandlerPsi'); /* restore error handler */ } if (!empty($bufferarr3)) { foreach ($bufferarr3 as $id => $string) { $buffer = $buffer . $id . " = " . $string . "\n"; } } if (strlen(trim($buffer)) > 0) { $this->_filecontent[$printer] = $buffer; } } } } break; case 'data': if (defined('PSI_PLUGIN_SNMPPINFO_DEVICES') && is_string(PSI_PLUGIN_SNMPPINFO_DEVICES)) { if (preg_match(ARRAY_EXP, PSI_PLUGIN_SNMPPINFO_DEVICES)) { $printers = eval(PSI_PLUGIN_SNMPPINFO_DEVICES); } else { $printers = array(PSI_PLUGIN_SNMPPINFO_DEVICES); } $pn = 0; foreach ($printers as $printer) { $buffer = ""; if (CommonFunctions::rfts(APP_ROOT . "/data/snmppinfo{$pn}.txt", $buffer) && !empty($buffer)) { $this->_filecontent[$printer] = $buffer; } $pn++; } } break; default: $this->global_error->addError("switch(PSI_PLUGIN_SNMPPINFO_ACCESS)", "Bad SNMPPInfo configuration in SNMPPInfo.config.php"); break; } }
function __construct($version, $host, $community) { parent::__construct($version, $host, $community); //snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); /* Return values without SNMP type hint */ snmp_set_valueretrieval(SNMP_VALUE_PLAIN); /* needs php >= 5.2.0 */ // snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL); // snmp_set_quick_print(1); }
function cacti_snmp_walk($hostname, $community, $oid, $version, $username, $password, $auth_proto, $priv_pass, $priv_proto, $context, $port = 161, $timeout = 500, $retries = 0, $max_oids = 10, $method = SNMP_VALUE_LIBRARY, $environ = SNMP_POLLER) { global $config, $banned_snmp_strings; $snmp_oid_included = false; $snmp_auth = ''; $snmp_array = array(); $temp_array = array(); /* determine default retries */ if ($retries == 0 || !is_numeric($retries)) { $retries = read_config_option("snmp_retries"); if ($retries == "") { $retries = 3; } } /* do not attempt to poll invalid combinations */ if ($version == 0 || !is_numeric($version) || !is_numeric($max_oids) || !is_numeric($port) || !is_numeric($retries) || !is_numeric($timeout) || $community == "" && $version != 3) { return array(); } $path_snmpbulkwalk = read_config_option("path_snmpbulkwalk"); if (snmp_get_method($version) == SNMP_METHOD_PHP && (!strlen($context) || $version != 3) && ($version == 1 || version_compare(phpversion(), "5.1") >= 0 || !file_exists($path_snmpbulkwalk))) { /* make sure snmp* is verbose so we can see what types of data we are getting back */ /* force php to return numeric oid's */ if (function_exists("snmp_set_oid_numeric_print")) { snmp_set_oid_numeric_print(SNMP_OID_OUTPUT_NUMERIC); $snmp_oid_included = true; } snmp_set_quick_print(0); /* set the output format to numeric */ snmp_set_valueretrieval($method); if ($version == "1") { $temp_array = @snmprealwalk("{$hostname}:{$port}", "{$community}", "{$oid}", $timeout * 1000, $retries); } elseif ($version == "2") { $temp_array = @snmp2_real_walk("{$hostname}:{$port}", "{$community}", "{$oid}", $timeout * 1000, $retries); } else { if ($priv_proto == "[None]") { $proto = "authNoPriv"; $priv_proto = ""; } else { $proto = "authPriv"; } $temp_array = @snmp3_real_walk("{$hostname}:{$port}", "{$username}", $proto, $auth_proto, "{$password}", $priv_proto, "{$priv_pass}", "{$oid}", $timeout * 1000, $retries); } if ($temp_array === false) { cacti_log("WARNING: SNMP Walk Timeout for Host:'{$hostname}', and OID:'{$oid}'", false); } /* check for bad entries */ if (is_array($temp_array) && sizeof($temp_array)) { foreach ($temp_array as $key => $value) { foreach ($banned_snmp_strings as $item) { if (strstr($value, $item) != "") { unset($temp_array[$key]); continue 2; } } } } $o = 0; for (@reset($temp_array); $i = @key($temp_array); next($temp_array)) { if ($temp_array[$i] != "NULL") { $snmp_array[$o]["oid"] = ereg_replace("^\\.", "", $i); $snmp_array[$o]["value"] = format_snmp_string($temp_array[$i], $snmp_oid_included); } $o++; } } else { /* ucd/net snmp want the timeout in seconds */ $timeout = ceil($timeout / 1000); if ($version == "1") { $snmp_auth = read_config_option("snmp_version") == "ucd-snmp" ? snmp_escape_string($community) : "-c " . snmp_escape_string($community); /* v1/v2 - community string */ } elseif ($version == "2") { $snmp_auth = read_config_option("snmp_version") == "ucd-snmp" ? snmp_escape_string($community) : "-c " . snmp_escape_string($community); /* v1/v2 - community string */ $version = "2c"; /* ucd/net snmp prefers this over '2' */ } elseif ($version == "3") { if ($priv_proto == "[None]") { $proto = "authNoPriv"; $priv_proto = ""; } else { $proto = "authPriv"; } if (strlen($priv_pass)) { $priv_pass = "******" . snmp_escape_string($priv_pass) . " -x " . snmp_escape_string($priv_proto); } else { $priv_pass = ""; } if (strlen($context)) { $context = "-n " . snmp_escape_string($context); } else { $context = ""; } $snmp_auth = trim("-u " . snmp_escape_string($username) . " -l " . snmp_escape_string($proto) . " -a " . snmp_escape_string($auth_proto) . " -A " . snmp_escape_string($password) . " " . $priv_pass . " " . $context); /* v3 - username/password */ } if (read_config_option("snmp_version") == "ucd-snmp") { /* escape the command to be executed and vulnerable parameters * numeric parameters are not subject to command injection * snmp_auth is treated seperately, see above */ $temp_array = exec_into_array(cacti_escapeshellcmd(read_config_option("path_snmpwalk")) . " -v{$version} -t {$timeout} -r {$retries} " . cacti_escapeshellarg($hostname) . ":{$port} {$snmp_auth} " . cacti_escapeshellarg($oid)); } else { if (file_exists($path_snmpbulkwalk) && $version > 1 && $max_oids > 1) { $temp_array = exec_into_array(cacti_escapeshellcmd($path_snmpbulkwalk) . " -O Qn {$snmp_auth} -v {$version} -t {$timeout} -r {$retries} -Cr{$max_oids} " . cacti_escapeshellarg($hostname) . ":{$port} " . cacti_escapeshellarg($oid)); } else { $temp_array = exec_into_array(cacti_escapeshellcmd(read_config_option("path_snmpwalk")) . " -O Qn {$snmp_auth} -v {$version} -t {$timeout} -r {$retries} " . cacti_escapeshellarg($hostname) . ":{$port} " . cacti_escapeshellarg($oid)); } } if (substr_count(implode(" ", $temp_array), "Timeout:")) { cacti_log("WARNING: SNMP Walk Timeout for Host:'{$hostname}', and OID:'{$oid}'", false); } /* check for bad entries */ if (is_array($temp_array) && sizeof($temp_array)) { foreach ($temp_array as $key => $value) { foreach ($banned_snmp_strings as $item) { if (strstr($value, $item) != "") { unset($temp_array[$key]); continue 2; } } } } for ($i = 0; $i < count($temp_array); $i++) { if ($temp_array[$i] != "NULL") { $snmp_array[$i]["oid"] = trim(ereg_replace("(.*) =.*", "\\1", $temp_array[$i])); $snmp_array[$i]["value"] = format_snmp_string($temp_array[$i], true); } } } return $snmp_array; }
<?php require_once dirname(__FILE__) . '/snmp_include.inc'; echo "Checking error handling\n"; var_dump(snmp_get_valueretrieval('noarg')); var_dump(snmp_set_valueretrieval()); var_dump(snmp_set_valueretrieval('noarg')); var_dump(snmp_set_valueretrieval(67)); echo "Checking working\n"; var_dump(snmp_get_valueretrieval()); snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); var_dump(snmp_get_valueretrieval() === SNMP_VALUE_LIBRARY); snmp_set_valueretrieval(SNMP_VALUE_PLAIN); var_dump(snmp_get_valueretrieval() === SNMP_VALUE_PLAIN); snmp_set_valueretrieval(SNMP_VALUE_OBJECT); var_dump(snmp_get_valueretrieval() === SNMP_VALUE_OBJECT); snmp_set_valueretrieval(SNMP_VALUE_PLAIN | SNMP_VALUE_OBJECT); var_dump(snmp_get_valueretrieval() === (SNMP_VALUE_PLAIN | SNMP_VALUE_OBJECT)); snmp_set_valueretrieval(SNMP_VALUE_LIBRARY | SNMP_VALUE_OBJECT); var_dump(snmp_get_valueretrieval() === (SNMP_VALUE_LIBRARY | SNMP_VALUE_OBJECT));
/** * get all information from all configured ups in phpsysinfo.ini and store output in internal array */ public function __construct() { parent::__construct(); switch (strtolower(PSI_UPS_SNMPUPS_ACCESS)) { case 'command': if (defined('PSI_UPS_SNMPUPS_LIST') && is_string(PSI_UPS_SNMPUPS_LIST)) { if (preg_match(ARRAY_EXP, PSI_UPS_SNMPUPS_LIST)) { $upss = eval(PSI_UPS_SNMPUPS_LIST); } else { $upss = array(PSI_UPS_SNMPUPS_LIST); } foreach ($upss as $ups) { CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -r 1 " . $ups . " .1.3.6.1.4.1.318.1.1.1.1", $buffer, PSI_DEBUG); if (strlen($buffer) > 0) { $this->_output[$ups] = $buffer; $buffer = ""; CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -r 1 " . $ups . " .1.3.6.1.4.1.318.1.1.1.2", $buffer, PSI_DEBUG); if (strlen($buffer) > 0) { $this->_output[$ups] .= "\n" . $buffer; } $buffer = ""; CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -r 1 " . $ups . " .1.3.6.1.4.1.318.1.1.1.3", $buffer, PSI_DEBUG); if (strlen($buffer) > 0) { $this->_output[$ups] .= "\n" . $buffer; } $buffer = ""; CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -r 1 " . $ups . " .1.3.6.1.4.1.318.1.1.1.4", $buffer, PSI_DEBUG); if (strlen($buffer) > 0) { $this->_output[$ups] .= "\n" . $buffer; } } } } break; case 'php-snmp': if (!extension_loaded("snmp")) { $this->error->addError("Requirements error", "SNMPups plugin requires the snmp extension to php in order to work properly"); break; } snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); if (defined('PSI_UPS_SNMPUPS_LIST') && is_string(PSI_UPS_SNMPUPS_LIST)) { if (preg_match(ARRAY_EXP, PSI_UPS_SNMPUPS_LIST)) { $upss = eval(PSI_UPS_SNMPUPS_LIST); } else { $upss = array(PSI_UPS_SNMPUPS_LIST); } foreach ($upss as $ups) { if (!PSI_DEBUG) { restore_error_handler(); /* default error handler */ $old_err_rep = error_reporting(); error_reporting(E_ERROR); /* fatal errors only */ } $bufferarr = snmprealwalk($ups, "public", ".1.3.6.1.4.1.318.1.1.1.1", 1000000, 1); if (!PSI_DEBUG) { error_reporting($old_err_rep); /* restore error level */ set_error_handler('errorHandlerPsi'); /* restore error handler */ } if (!empty($bufferarr)) { $buffer = ""; foreach ($bufferarr as $id => $string) { $buffer .= $id . " = " . $string . "\n"; } if (!PSI_DEBUG) { restore_error_handler(); /* default error handler */ $old_err_rep = error_reporting(); error_reporting(E_ERROR); /* fatal errors only */ } $bufferarr2 = snmprealwalk($ups, "public", ".1.3.6.1.4.1.318.1.1.1.2", 1000000, 1); $bufferarr3 = snmprealwalk($ups, "public", ".1.3.6.1.4.1.318.1.1.1.3", 1000000, 1); $bufferarr4 = snmprealwalk($ups, "public", ".1.3.6.1.4.1.318.1.1.1.4", 1000000, 1); if (!PSI_DEBUG) { error_reporting($old_err_rep); /* restore error level */ set_error_handler('errorHandlerPsi'); /* restore error handler */ } if (!empty($bufferarr2)) { foreach ($bufferarr2 as $id => $string) { $buffer .= $id . " = " . $string . "\n"; } if (!empty($bufferarr3)) { foreach ($bufferarr3 as $id => $string) { $buffer .= $id . " = " . $string . "\n"; } } } if (!empty($bufferarr4)) { foreach ($bufferarr4 as $id => $string) { $buffer .= $id . " = " . $string . "\n"; } } if (strlen(trim($buffer)) > 0) { $this->_output[$ups] = $buffer; } } } } break; default: $this->error->addError("switch(PSI_UPS_SNMPUPS_ACCESS)", "Bad SNMPups configuration in phpsysinfo.ini"); break; } }
/** * Define connection target * * @param string $host * @param int $port * @param string $community */ public function Connect($host, $port = 161, $community = "public", $timeout = false, $retries = false, $SNMP_VALUE_PLAIN = false) { if (is_null($port)) { $port = self::DEFAULT_PORT; } //$this->Connection = "{$host}:{$port}"; $this->Connection = "{$host}"; $this->Community = $community; if (!$timeout) { $this->Timeout = !defined("SNMP_TIMEOUT") ? self::DEFAULT_TIMEOUT : SNMP_TIMEOUT; } else { $this->Timeout = $timeout; } $this->Timeout = $this->Timeout * 100000; $this->Retries = $retries ? $retries : self::DEFAULT_RETRIES; if ($SNMP_VALUE_PLAIN == true) { @snmp_set_valueretrieval(SNMP_VALUE_PLAIN); } else { @snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); } $this->Shell = ShellFactory::GetShellInstance(); }
function cacti_snmp_walk($hostname, $community, $oid, $version, $username, $password, $port = 161, $timeout = 500, $environ = SNMP_POLLER) { global $config; $snmp_array = array(); $temp_array = array(); /* determine default retries */ $retries = read_config_option("snmp_retries"); if ($retries == "") $retries = 3; if (snmp_get_method($version) == SNMP_METHOD_PHP) { /* make sure snmp* is verbose so we can see what types of data we are getting back */ snmp_set_quick_print(0); if (function_exists("snmp_set_valueretrieval")) { snmp_set_valueretrieval(SNMP_VALUE_PLAIN); } if ($version == "1") { $temp_array = @snmprealwalk("$hostname:$port", $community, $oid, ($timeout * 1000), $retries); } else { $temp_array = @snmp2_real_walk("$hostname:$port", $community, $oid, ($timeout * 1000), $retries); } $o = 0; for (@reset($temp_array); $i = @key($temp_array); next($temp_array)) { $snmp_array[$o]["oid"] = ereg_replace("^\.", "", $i); $snmp_array[$o]["value"] = format_snmp_string($temp_array[$i]); $o++; } }else{ /* ucd/net snmp want the timeout in seconds */ $timeout = ceil($timeout / 1000); if ($version == "1") { $snmp_auth = (read_config_option("snmp_version") == "ucd-snmp") ? SNMP_ESCAPE_CHARACTER . $community . SNMP_ESCAPE_CHARACTER : "-c " . SNMP_ESCAPE_CHARACTER . $community . SNMP_ESCAPE_CHARACTER; /* v1/v2 - community string */ }elseif ($version == "2") { $snmp_auth = (read_config_option("snmp_version") == "ucd-snmp") ? SNMP_ESCAPE_CHARACTER . $community . SNMP_ESCAPE_CHARACTER : "-c " . SNMP_ESCAPE_CHARACTER . $community . SNMP_ESCAPE_CHARACTER; /* v1/v2 - community string */ $version = "2c"; /* ucd/net snmp prefers this over '2' */ }elseif ($version == "3") { $snmp_auth = "-u $username -l authPriv -a MD5 -A $password -x DES -X $password"; /* v3 - username/password */ } if (read_config_option("snmp_version") == "ucd-snmp") { $temp_array = exec_into_array(read_config_option("path_snmpwalk") . " -v$version -t $timeout -r $retries $hostname:$port $snmp_auth $oid"); }else { $temp_array = exec_into_array(read_config_option("path_snmpwalk") . " -O QfntUe $snmp_auth -v $version -t $timeout -r $retries $hostname:$port $oid"); } if ((sizeof($temp_array) == 0) || (substr_count($temp_array[0], "No Such Object"))) { return array(); } for ($i=0; $i < count($temp_array); $i++) { $snmp_array[$i]["oid"] = trim(ereg_replace("(.*) =.*", "\\1", $temp_array[$i])); $snmp_array[$i]["value"] = format_snmp_string($temp_array[$i]); } } return $snmp_array; }
function ReadData($targetstring, &$map, &$item) { $data[IN] = NULL; $data[OUT] = NULL; $data_time = 0; $timeout = 1000000; $retries = 2; $abort_count = 0; $in_result = NULL; $out_result = NULL; if ($map->get_hint("snmp_timeout") != '') { $timeout = intval($map->get_hint("snmp_timeout")); debug("Timeout changed to " . $timeout . " microseconds.\n"); } if ($map->get_hint("snmp_abort_count") != '') { $abort_count = intval($map->get_hint("snmp_abort_count")); debug("Will abort after {$abort_count} failures for a given host.\n"); } if ($map->get_hint("snmp_retries") != '') { $retries = intval($map->get_hint("snmp_retries")); debug("Number of retries changed to " . $retries . ".\n"); } if (preg_match("/^snmp:([^:]+):([^:]+):([^:]+):([^:]+)\$/", $targetstring, $matches)) { $community = $matches[1]; $host = $matches[2]; $in_oid = $matches[3]; $out_oid = $matches[4]; if ($abort_count == 0 || $abort_count > 0 && (!isset($this->down_cache[$host]) || intval($this->down_cache[$host]) < $abort_count)) { if (function_exists("snmp_get_quick_print")) { $was = snmp_get_quick_print(); snmp_set_quick_print(1); } if (function_exists("snmp_get_valueretrieval")) { $was2 = snmp_get_valueretrieval(); } if (function_exists('snmp_set_oid_output_format')) { snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); } if (function_exists('snmp_set_valueretrieval')) { snmp_set_valueretrieval(SNMP_VALUE_PLAIN); } if ($in_oid != '-') { $in_result = snmpget($host, $community, $in_oid, $timeout, $retries); if ($in_result) { $data[IN] = floatval($in_result); $item->add_hint("snmp_in_raw", $in_result); } else { $this->down_cache[$host]++; } } if ($out_oid != '-') { $out_result = snmpget($host, $community, $out_oid, $timeout, $retries); if ($out_result) { // use floatval() here to force the output to be *some* kind of number // just in case the stupid formatting stuff doesn't stop net-snmp returning 'down' instead of 2 $data[OUT] = floatval($out_result); $item->add_hint("snmp_out_raw", $out_result); } else { $this->down_cache[$host]++; } } debug("SNMP ReadData: Got {$in_result} and {$out_result}\n"); $data_time = time(); if (function_exists("snmp_set_quick_print")) { snmp_set_quick_print($was); } } else { warn("SNMP for {$host} has reached {$abort_count} failures. Skipping. [WMSNMP01]"); } } debug("SNMP ReadData: Returning (" . ($data[IN] === NULL ? 'NULL' : $data[IN]) . "," . ($data[OUT] === NULL ? 'NULL' : $data[OUT]) . ",{$data_time})\n"); return array($data[IN], $data[OUT], $data_time); }
function __set($name, $value) { switch ($name) { case 'quick_print': snmp_set_quick_print($value); break; case 'oid_output_format': /* needs php >= 5.2.0 */ snmp_set_oid_output_format($value); break; case 'enum_print': snmp_set_enum_print($value); break; case 'valueretrieval': snmp_set_valueretrieval($value); break; default: $trace = debug_backtrace(); trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE); return null; } }
/** * read the data into an internal array and also call the parent constructor * * @param String $enc encoding */ public function __construct($enc) { parent::__construct(__CLASS__, $enc); switch (PSI_PLUGIN_SNMPPINFO_ACCESS) { case 'command': $printers = preg_split('/([\\s]+)?,([\\s]+)?/', PSI_PLUGIN_SNMPPINFO_DEVICES, -1, PREG_SPLIT_NO_EMPTY); foreach ($printers as $printer) { CommonFunctions::executeProgram("snmpwalk", "-On -c public -v 1 " . $printer . " 1.3.6.1.2.1.1.5", $buffer, PSI_DEBUG); if (strlen(trim($buffer)) > 0) { $this->_filecontent[$printer] = $buffer; CommonFunctions::executeProgram("snmpwalk", "-On -c public -v 1 " . $printer . " 1.3.6.1.2.1.43.11.1.1", $buffer2, PSI_DEBUG); if (strlen(trim($buffer2)) > 0) { $this->_filecontent[$printer] = $buffer . "\n" . $buffer2; } else { $this->_filecontent[$printer] = $buffer; } } } break; case 'php-snmp': snmp_set_valueretrieval(SNMP_VALUE_LIBRARY); snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); $printers = preg_split('/([\\s]+)?,([\\s]+)?/', PSI_PLUGIN_SNMPPINFO_DEVICES, -1, PREG_SPLIT_NO_EMPTY); foreach ($printers as $printer) { if (!PSI_DEBUG) { restore_error_handler(); } $bufferarr = snmprealwalk($printer, "public", "1.3.6.1.2.1.1.5"); if (!PSI_DEBUG) { set_error_handler('errorHandlerPsi'); } if (!empty($bufferarr)) { $buffer = ""; foreach ($bufferarr as $id => $string) { $buffer = $buffer . $id . " = " . $string . "\n"; } if (!PSI_DEBUG) { restore_error_handler(); } $bufferarr2 = snmprealwalk($printer, "public", "1.3.6.1.2.1.43.11.1.1"); if (!PSI_DEBUG) { set_error_handler('errorHandlerPsi'); } if (!empty($bufferarr2)) { foreach ($bufferarr2 as $id => $string) { $buffer = $buffer . $id . " = " . $string . "\n"; } } if (strlen(trim($buffer)) > 0) { $this->_filecontent[$printer] = $buffer; } } } break; case 'data': $printers = preg_split('/([\\s]+)?,([\\s]+)?/', PSI_PLUGIN_SNMPPINFO_DEVICES, -1, PREG_SPLIT_NO_EMPTY); $pn = 0; foreach ($printers as $printer) { $buffer = ""; if (CommonFunctions::rfts(APP_ROOT . "/data/SNMPPInfo{$pn}.txt", $buffer) && !empty($buffer)) { $this->_filecontent[$printer] = $buffer; } $pn++; } break; default: $this->global_error->addError("switch(PSI_PLUGIN_SNMPPINFO_ACCESS)", "Bad SNMPPInfo configuration in SNMPPInfo.config.php"); break; } }
<?php require_once dirname(__FILE__) . '/snmp_include.inc'; //EXPECTF format is quickprint OFF snmp_set_quick_print(false); snmp_set_valueretrieval(SNMP_VALUE_PLAIN); echo "Single OID\n"; var_dump(snmp2_getnext($hostname, $community, '.1.3.6.1.2.1.1.1.0', $timeout, $retries)); echo "Single OID in array\n"; var_dump(snmp2_getnext($hostname, $community, array('.1.3.6.1.2.1.1.1.0'), $timeout, $retries)); echo "Multiple OID\n"; var_dump(snmp2_getnext($hostname, $community, array('.1.3.6.1.2.1.1.1.0', '.1.3.6.1.2.1.1.6.0'), $timeout, $retries));
private function changeSNMPSettings() { if (function_exists("snmp_get_quick_print")) { $this->snmpSavedQuickPrint = snmp_get_quick_print(); snmp_set_quick_print(1); } if (function_exists("snmp_get_valueretrieval")) { $this->snmpSavedValueRetrieval = snmp_get_valueretrieval(); } if (function_exists('snmp_set_oid_output_format')) { snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); } if (function_exists('snmp_set_valueretrieval')) { snmp_set_valueretrieval(SNMP_VALUE_PLAIN); } }