cb30fd483231cdc684809443f714c3c0aa72df86
3 /********************************************
5 * RackTables 0.20.x snmpgeneric extension
7 * sync an RackTables object with an SNMP device.
9 * Should work with almost any SNMP capable device.
15 * - ipAddrTable (ipv4 only)
16 * - ipAddressTable (ipv4 + ipv6)
19 * - update object attributes
22 * - add and bind ip addresses
23 * - create as new object
24 * - save snmp settings per object (uses comment field)
27 * - Enterasys SecureStacks, S-Series
28 * - cisco 2620XM (thx to Rob)
29 * - hopefully many others
34 * 1. select "SNMP generic sync" tap
35 * 2. select your SNMP config (host, v1, v2c or v3, ...)
37 * 4. you will see a selection of all information that could be retrieved
38 * 5. select what should be updated and/or created
39 * 6. hit "Create" Button to make changes to RackTables
40 * 7. repeat step 1. to 6. as often as you like / need
45 * TESTED on FreeBSD 9.0, nginx/1.0.12, php 5.3.10, NET-SNMP 5.7.1
46 * and RackTables <= 0.20.3
48 * (c)2015 Maik Ehinger <m.ehinger@ltur.de>
53 * just place file in plugins directory
58 * The newest version of this plugin can be found at:
60 * https://github.com/github138/myRT-contribs/tree/develop-0.20.x
68 * - test if device supports mibs
69 * - gethostbyaddr / gethostbyname host list
70 * - correct iif_name display if != 1
72 * - set more Object attributs / fields
74 * - Input variables exceeded 1000
79 /* RackTables Debug Mode */
82 require_once('inc/snmp.php');
84 $tab['object']['snmpgeneric'] = 'SNMP Generic sync';
85 $tabhandler['object']['snmpgeneric'] = 'snmpgeneric_tabhandler';
86 $trigger['object']['snmpgeneric'] = 'snmpgeneric_tabtrigger';
88 $ophandler['object']['snmpgeneric']['create'] = 'snmpgeneric_opcreate';
90 /* snmptranslate command */
91 $sg_cmd_snmptranslate = '/usr/local/bin/snmptranslate';
93 /* create ports without connector */
94 $sg_create_noconnector_ports = FALSE;
96 /* deselect add port for this snmp port types */
97 $sg_ifType_ignore = array(
99 '24', /* softwareLoopback */
103 '53', /* propVirtual */
106 '136', /* l3ipvlan */
108 '161', /* ieee8023adLag */
111 /* ifType to RT oif_id mapping */
112 $sg_ifType2oif_id = array(
113 /* 440 causes SQLSTATE[23000]: Integrity constraint violation:
114 * 1452 Cannot add or update a child row:
115 * a foreign key constraint fails
117 // '1' => 440, /* other => unknown 440 */
118 '1' => 1469, /* other => virutal port 1469 */
119 '6' => 24, /* ethernetCsmacd => 1000BASE-T 24 */
120 '24' => 1469, /* softwareLoopback => virtual port 1469 */
121 '33' => 1469, /* rs232 => RS-232 (DB-9) 681 */
122 '34' => 1469, /* para => virtual port 1469 */
123 '53' => 1469, /* propVirtual => virtual port 1469 */
124 '62' => 19, /* fastEther => 100BASE-TX 19 */
125 '131' => 1469, /* tunnel => virtual port 1469 */
126 '136' => 1469, /* l3ipvlan => virtual port 1469 */
127 '160' => 1469, /* usb => virtual port 1469 */
128 '161' => 1469, /* ieee8023adLag => virtual port 1469 */
131 /* -------------------------------------------------- */
133 /* snmp vendor list http://www.iana.org/assignments/enterprise-numbers */
135 $sg_known_sysObjectIDs = array
137 /* ------------ default ------------ */
140 // 'text' => 'default',
141 'pf' => array('snmpgeneric_pf_entitymib'),
144 2 => array('pf' => 'snmpgeneric_pf_hwtype'), /* HW Typ*/
145 3 => array('oid' => 'sysName.0'),
146 /* FQDN check only if regex matches */
147 //3 => array('oid' => 'sysName.0', 'regex' => '/^[^ .]+(\.[^ .]+)+\.?/', 'uncheck' => 'no FQDN'),
148 4 => array('pf' => 'snmpgeneric_pf_swtype', 'uncheck' => 'experimental'), /* SW type */
149 14 => array('oid' => 'sysContact.0'), /* Contact person */
150 // 1235 => array('value' => 'Constant'),
154 // 'AC-in' => array('porttypeid' => '1-16', 'uncheck' => 'uncheck reason/comment'),
155 // 'name' => array('porttypeid' => '1-24', 'ifDescr' => 'visible label'),
159 /* ------------ ciscoSystems --------------- */
162 * 'text' => 'ciscoSystems',
167 'text' => 'ciscoProducts',
169 4 => array('pf' => 'snmpgeneric_pf_catalyst'), /* SW type/version */
170 16 => array('pf' => 'snmpgeneric_pf_ciscoflash'), /* flash memory */
175 /* ------------ Microsoft --------------- */
178 'text' => 'Microsoft',
180 4 => array('pf' => 'snmpgeneric_pf_swtype', 'oid' => 'sysDescr.0', 'regex' => '/.* Windows Version (.*?) .*/', 'replacement' => 'Windows \\1', 'uncheck' => 'TODO RT matching'), /*SW type */
183 /* ------------ Enterasys --------------- */
186 'text' => 'Enterasys',
188 4 => array('pf' => 'snmpgeneric_pf_enterasys'), /* SW type/version */
193 '5624.2.1.53' => array
196 'text' => 'Matrix N3',
199 '5624.2.2.284' => array
202 'text' => 'Securestack C2',
205 '5624.2.1.98' => array
208 'text' => 'Securestack C3',
211 '5624.2.1.100' => array
214 'text' => 'Securestack B3',
217 '5624.2.1.128' => array
220 'text' => 'S-series SSA130',
223 '5624.2.1.129' => array
226 'text' => 'S-series SSA150',
229 '5624.2.1.137' => array
232 'text' => 'Securestack B5 POE',
236 '5624.2.1.131' => array
239 'text' => 'S-series S3',
243 '5624.2.1.132' => array
246 'text' => 'S-series S4'
250 '5624.2.1.133' => array
253 'text' => 'S-series S8'
256 '5624.2.1.165' => array
259 'text' => 'S-series Bonded SSA',
262 /* ------------ net-snmp --------------- */
265 'text' => 'net-snmp',
267 4 => array('pf' => 'snmpgeneric_pf_swtype', 'oid' => 'sysDescr.0', 'regex' => '/(.*?) .*? (.*?) .*/', 'replacement' => '\\1 \\2', 'uncheck' => 'TODO RT matching'), /*SW type */
271 /* ------------ Frauenhofer FOKUS ------------ */
274 'text' => 'Fraunhofer FOKUS',
276 4 => array('pf' => 'snmpgeneric_pf_swtype', 'oid' => 'sysDescr.0', 'regex' => '/.*? .*? (.*? .*).*/', 'replacement' => '\\1', 'uncheck' => 'TODO RT matching'), /*SW type */
280 '12325.1.1.2.1.1' => array
282 'dict_key' => 42, /* Server model noname/unknown */
283 'text' => 'BSNMP - mini SNMP daemon (bsnmpd)',
287 /* add snmp.php known_switches */
289 /* ------------ Sample function --------------- */
291 * Sample Precessing Function (pf)
293 function snmpgeneric_pf_sample(&$snmp, &$sysObjectID, $attr_id) {
295 $object = &$sysObjectID['object'];
296 $attr = &$sysObjectID['attr'][$attr_id];
298 if(!isset($attr['oid']))
301 /* output success banner */
302 showSuccess('Found sysObjectID '.$sysObjectID['value']);
304 /* access attribute oid setting and do snmpget */
306 $value = $snmp->get($oid);
308 /* set new attribute value */
309 $attr['value'] = $value;
311 /* do not check attribute per default */
312 $attr['uncheck'] = "comment";
314 /* set informal comment */
315 $attr['comment'] = "comment";
317 /* add additional ports */
318 // $sysObjectID['port']['name'] = array('porttypeid' => '1-24', 'ifPhysAddress' => '001122334455', 'ifDescr' => 'visible label', 'uncheck' => 'comment', 'disabled' => 'porttypeid select disabled');
320 /* set other attribute */
321 // $sysObjectID['attr'][1234]['value'] = 'attribute value';
323 } /* snmpgeneric_pf_sample */
325 /* ------------ Enterasys --------------- */
327 function snmpgeneric_pf_enterasys(&$snmp, &$sysObjectID, $attr_id) {
329 $attrs = &$sysObjectID['attr'];
331 //snmpgeneric_pf_entitymib($snmp, $sysObjectID, $attr_id);
333 /* TODO find correct way to get Bootroom and Firmware versions */
336 /*if(preg_match('/.*\.([^.]+)$/', $sysObjectID['value'], $matches)) {
337 * showNotice('Device '.$matches[1]);
342 //$attrs[4]['value'] = 'Enterasys'; /* SW type */
344 /* set SW version only if not already set by entitymib */
345 if(isset($attrs[5]['value']) && !empty($attrs[5]['value'])) {
347 /* SW version from sysDescr */
348 if(preg_match('/^Enterasys .* Inc\. (.+) [Rr]ev ([^ ]+) ?(.*)$/', $snmp->sysDescr
, $matches)) {
350 $attrs[5]['value'] = $matches[2]; /* SW version */
352 // showSuccess("Found Enterasys Model ".$matches[1]);
357 /* add serial port */
358 //$sysObjectID['port']['console'] = array('porttypeid' => '1-29', 'ifDescr' => 'console', 'disabled' => 'disabled');
362 /* ------------ Cisco --------------- */
364 /* logic from snmp.php */
365 function snmpgeneric_pf_catalyst(&$snmp, &$sysObjectID, $attr_id) {
366 $attrs = &$sysObjectID['attr'];
367 $ports = &$sysObjectID['port'];
369 /* sysDescr multiline on C5200 */
370 if(preg_match ('/.*, Version ([^ ]+), .*/', $snmp->sysDescr
, $matches)) {
371 $exact_release = $matches[1];
372 $major_line = preg_replace ('/^([[:digit:]]+\.[[:digit:]]+)[^[:digit:]].*/', '\\1', $exact_release);
381 $attrs[5]['value'] = $exact_release;
383 if (array_key_exists ($major_line, $ios_codes))
384 $attrs[4]['value'] = $ios_codes[$major_line];
386 } /* sw type / version */
388 $sysChassi = $snmp->get ('1.3.6.1.4.1.9.3.6.3.0');
389 if ($sysChassi !== FALSE or $sysChassi !== NULL)
390 $attrs[1]['value'] = str_replace ('"', '', $sysChassi);
392 $ports['con0'] = array('porttypeid' => '1-29', 'ifDescr' => 'console'); // RJ-45 RS-232 console
394 if (preg_match ('/Cisco IOS Software, C2600/', $snmp->sysDescr
))
395 $ports['aux0'] = array('porttypeid' => '1-29', 'ifDescr' => 'auxillary'); // RJ-45 RS-232 aux port
397 // blade devices are powered through internal circuitry of chassis
398 if ($sysObjectID['value'] != '9.1.749' and $sysObjectID['value'] != '9.1.920')
400 $ports['AC-in'] = array('porttypeid' => '1-16');
403 } /* snmpgeneric_pf_catalyst */
405 /* -------------------------------------------------- */
406 function snmpgeneric_pf_ciscoflash(&$snmp, &$sysObjectID, $attr_id) {
408 * ciscoflashMIB = 1.3.6.1.4.1.9.9.10
411 | 16 | uint | flash memory, MB |
413 $attrs = &$sysObjectID['attr'];
415 $ciscoflash = $snmp->walk('1.3.6.1.4.1.9.9.10.1.1.2'); /* ciscoFlashDeviceTable */
420 $flash = array_keys($ciscoflash, 'flash');
422 foreach($flash as $oid) {
423 if(!preg_match('/(.*)?\.[^\.]+\.([^\.]+)$/',$oid,$matches))
426 $index = $matches[2];
427 $prefix = $matches[1];
429 showSuccess("Found Flash: ".$ciscoflash[$prefix.'.8.'.$index]." ".$ciscoflash[$prefix.'.2.'.$index]." bytes");
431 $attrs[16]['value'] = ceil($ciscoflash[$prefix.'.2.'.$index] / 1024 / 1024); /* ciscoFlashDeviceSize */
436 * ciscoMemoryPoolMIB = 1.3.6.1.4.1.9.9.48
437 * ciscoMemoryPoolUsed .1.1.1.5
438 * ciscoMemoryPoolFree .1.1.1.6
441 $ciscomem = $snmp->walk('1.3.6.1.4.1.9.9.48');
443 if(!empty($ciscomem)) {
448 foreach($ciscomem as $oid => $value) {
450 switch(preg_replace('/.*?(\.1\.1\.1\.[^\.]+)\.[^\.]+$/','\\1',$oid)) {
461 $attrs[17]['value'] = ceil(($free +
$used) / 1024 / 1024); /* RAM, MB */
464 } /* snmpgeneric_pf_ciscoflash */
466 /* -------------------------------------------------- */
467 /* -------------------------------------------------- */
469 /* HW Type processor function */
470 function snmpgeneric_pf_hwtype(&$snmp, &$sysObjectID, $attr_id) {
472 $attr = &$sysObjectID['attr'][$attr_id];
474 if (isset($sysObjectID['dict_key'])) {
476 $value = $sysObjectID['dict_key'];
477 showSuccess("Found HW type dict_key: $value");
479 /* return array of attr_id => attr_value) */
480 $attr['value'] = $value;
483 showNotice("HW type dict_key not set - Unknown OID");
486 } /* snmpgeneric_pf_hwtype */
488 /* -------------------------------------------------- */
490 /* SW type processor function */
492 /* Find a way to match RT SW types !? */
493 function snmpgeneric_pf_swtype(&$snmp, &$sysObjectID, $attr_id) {
497 $attr = &$sysObjectID['attr'][$attr_id];
499 $object = &$sysObjectID['object'];
501 $objtype_id = $object['objtype_id'];
503 if(isset($attr['oid']))
508 $raw_value = $snmp->get($oid);
510 $replacement = '\\1';
512 if(isset($attr['regex'])) {
513 $regex = $attr['regex'];
515 if(isset($attr['replacement']))
516 $replacement = $attr['replacement'];
519 $list = array('bsd','linux','centos','suse','fedora','ubuntu','windows','solaris','vmware');
521 $regex = '/.* ([^ ]*('.implode($list,'|').')[^ ]*) .*/i';
522 $replacement = '\\1';
525 $value = preg_replace($regex, $replacement, $raw_value, -1, $count);
526 //$attr['value'] = $value;
528 if(!empty($value) && $count > 0) {
529 /* search dict_key for value in RT Dictionary */
530 /* depends on object type server(13)/switch(14)/router(15) */
531 $result = usePreparedSelectBlade
533 'SELECT dict_key,dict_value FROM Dictionary WHERE chapter_id in (13,14,15) and dict_value like ? order by dict_key desc limit 1',
534 array ('%'.$value.'%')
536 $row = $result->fetchAll(PDO
::FETCH_GROUP|PDO
::FETCH_UNIQUE|PDO
::FETCH_COLUMN
);
539 $RTvalue = key($row);
541 if(isset($attr['comment']))
542 $attr['comment'] .= ", $value ($RTvalue) ".$row[$RTvalue];
544 $attr['comment'] = "$value ($RTvalue) ".$row[$RTvalue];
546 showSuccess("Found SW type: $value ($RTvalue) ".$row[$RTvalue]);
551 $attr['value'] = $value;
552 // unset($attr['uncheck']);
556 if(isset($attr['comment']))
557 $attr['comment'] .= ' (experimental)';
559 $attr['comment'] = '(experimental)';
561 } /* snmpgeneric_pf_swtype */
563 /* -------------------------------------------------- */
564 /* try to set SW version
565 * and add some AC ports
568 /* needs more testing */
569 function snmpgeneric_pf_entitymib(&$snmp, &$sysObjectID, $attr_id) {
571 /* $attr_id == NULL -> device pf */
573 $attrs = &$sysObjectID['attr'];
574 $ports = &$sysObjectID['port'];
576 $entPhysicalClass = $snmp->walk('.1.3.6.1.2.1.47.1.1.1.1.5'); /* entPhysicalClass */
578 if(empty($entPhysicalClass))
581 showNotice("Found Entity Table (Experimental)");
600 /* always index = 1 ??? */
601 $chassis = array_keys($entPhysicalClass, '3'); /* 3 chassis */
604 if(!empty($chassis)) {
607 foreach($chassis as $key => $oid) {
609 if(!preg_match('/\.(\d+)$/',$oid, $matches))
612 $index = $matches[1];
614 $name = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.7.$index");
615 $serialnum = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.11.$index");
616 $mfgname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.12.$index");
617 $modelname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.13.$index");
619 //showNotice("$name $mfgname $modelname $serialnum");
621 echo("<tr><td>$name</td><td>$mfgname</td><td>$modelname</td><td>$serialnum</td>");
633 $modules = array_keys($entPhysicalClass, '9'); /* 9 Modules */
635 if(!empty($modules)) {
637 echo '<br><br>Modules<br><table>';
638 echo("<tr><th>Name</th><th>MfgName</th><th>ModelName</th><th>HardwareRev</th><th>FirmwareRev</th><th>SoftwareRev</th><th>SerialNum</th>");
640 foreach($modules as $key => $oid) {
643 if(!preg_match('/\.(\d+)$/',$oid, $matches))
646 $index = $matches[1];
648 $name = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.7.$index");
653 $hardwarerev = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.8.$index");
654 $firmwarerev = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.9.$index");
655 $softwarerev = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.10.$index");
656 $serialnum = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.11.$index");
657 $mfgname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.12.$index");
658 $modelname = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.13.$index");
660 //showNotice("$name $mfgname $modelname $hardwarerev $firmwarerev $softwarerev $serialnum");
662 echo("<tr><td>".(empty($name) ?
'-' : $name )."</td><td>$mfgname</td><td>$modelname</td><td>$hardwarerev</td><td>$firmwarerev</td><td>$softwarerev</td><td>$serialnum</td>");
664 /* set SW version to first module software version */
667 $attrs[5]['value'] = $softwarerev; /* SW version */
668 $attrs[5]['comment'] = 'entity MIB';
680 $powersupply = array_keys($entPhysicalClass, '6'); /* 6 powerSupply */
682 foreach($powersupply as $oid) {
685 if(!preg_match('/\.(\d+)$/',$oid, $matches))
688 $index = $matches[1];
689 $descr = $snmp->get(".1.3.6.1.2.1.47.1.1.1.1.2.$index");
691 $ports['AC-'.$count] = array('porttypeid' => '1-16', 'ifDescr' => $descr, 'comment' => 'entity MIB', 'uncheck' => '');
697 /* -------------------------------------------------- */
700 * regex processor function
701 * needs 'oid' and 'regex'
702 * uses first back reference as attribute value
704 function snmpgeneric_pf_regex(&$snmp, &$sysObjectID, $attr_id) {
706 $attr = &$sysObjectID['attr'][$attr_id];
708 if (isset($attr['oid']) && isset($attr['regex'])) {
711 $regex = $attr['regex'];
713 $raw_value = $snmp->get($oid);
716 if(isset($attr['replacement']))
717 $replace = $attr['replacement'];
721 $value = preg_replace($regex,$replace, $raw_value);
723 /* return array of attr_id => attr_value) */
724 $attr['value'] = $value;
729 } /* snmpgeneric_pf_regex */
731 /* -------------------------------------------------- */
733 $sg_portiifoptions= getPortIIFOptions();
734 $sg_portiifoptions[-1] = 'sfp'; /* generic sfp */
736 $sg_portoifoptions= getPortOIFOptions();
738 /* -------------------------------------------------- */
739 /* -------------------------------------------------- */
741 function snmpgeneric_tabhandler($object_id) {
743 // sg_var_dump_html($_POST);
745 if(isset($_POST['asnewobject']) && $_POST['asnewobject'] == "1")
747 $newobject_name = $_POST['object_name'];
748 $newobject_label = $_POST['object_label'];
749 $newobject_type_id = $_POST['object_type_id'];
750 $newobject_asset_no = $_POST['object_asset_no'];
752 if(sg_checkObjectNameUniqueness($newobject_name, $newobject_type_id))
755 $object_id = commitAddObject($newobject_name, $newobject_label, $newobject_type_id, $newobject_asset_no);
757 $_POST['asnewobject'] = "0";
759 parse_str($_SERVER['QUERY_STRING'],$query_string);
761 $query_string['object_id'] = $object_id;
763 $_SERVER['QUERY_STRING'] = http_build_query($query_string);
765 list($path, $qs) = explode('?',$_SERVER['REQUEST_URI'],2);
766 $_SERVER['REQUEST_URI'] = $path.'?'.$_SERVER['QUERY_STRING'];
769 // switch to new object
771 echo '<body onload="document.forms[\'newobject\'].submit();">';
773 echo '<form method=POST id=newobject action='.$_SERVER['REQUEST_URI'].'>';
775 foreach($_POST as $name => $value)
777 echo "<input type=hidden name=$name value=$value>";
780 echo '<input type=submit id="submitbutton" tabindex="1" value="Show List">';
781 echo '</from></body>';
786 showError("Object with name: \"$newobject_name\" already exists!!!");
787 $_POST['snmpconfig'] = "0";
791 // save snmp settings
792 if(isset($_POST['save']) && $_POST['save'] == "1")
794 // TODO save only on success !!
796 $object = spotEntity('object', $object_id);
798 $snmpvalues[0] = 'SNMP';
799 $snmpnames = array('host', 'version', 'community');
800 if($_POST['version'] == "v3")
801 $snmpnames = array_merge($snmpnames, array('sec_level','auth_protocol','auth_passphrase','priv_protocol','priv_passphrase'));
803 foreach($snmpnames as $key => $value)
805 if(isset($_POST[$value]))
809 case "auth_passphrase":
810 case "priv_passphrase":
811 $snmpvalues[$key +
1] = base64_encode($_POST[$value]);
814 default: $snmpvalues[$key +
1] = $_POST[$value];
819 // sg_var_dump_html($snmpvalues);
821 $newsnmpstr = implode($snmpvalues,":");
823 $snmpstr = strtok($object['comment'],"\n\r");
825 $snmpstrarray = explode(':', $snmpstr);
828 if($snmpstrarray[0] == "SNMP")
830 if($newsnmpstr == $snmpstr)
833 $setcomment = "update";
836 if($setcomment != "ok")
839 if($setcomment == "update")
840 $comment = str_replace($snmpstr,$newsnmpstr, $object['comment']);
842 $comment = "$newsnmpstr\n".$object['comment'];
844 // echo "$snmpnewstr ".$object['comment']." --> $comment";
846 commitUpdateObject($object_id, $object['name'], NULL, $object['has_problems'], NULL, $comment );
847 showNotice("$setcomment SNMP Settings: $newsnmpstr");
853 if(isset($_POST['snmpconfig']) && $_POST['snmpconfig'] == '1') {
854 snmpgeneric_list($object_id);
856 snmpgeneric_snmpconfig($object_id);
858 } /* snmpgeneric_tabhandler */
860 /* -------------------------------------------------- */
862 function snmpgeneric_tabtrigger() {
863 // display tab only on IPv4 Objects
864 return considerConfiguredConstraint (spotEntity ('object', getBypassValue()), 'IPV4OBJ_LISTSRC') ?
'std' : '';
865 } /* snmpgeneric_tabtrigger */
867 /* -------------------------------------------------- */
869 function snmpgeneric_snmpconfig($object_id) {
872 $object = spotEntity ('object', $object_id);
873 //$object['attr'] = getAttrValues($object_id);
874 $endpoints = findAllEndpoints ($object_id, $object['name']);
876 addJS('function showsnmpv3(element) {
878 if(element.value != \'v3\') {
880 document.getElementById(\'snmp_community_label\').style.display=\'\';
883 document.getElementById(\'snmp_community_label\').style.display=\'none\';
886 var elements = document.getElementsByName(\'snmpv3\');
887 for(var i=0;i<elements.length;i++) {
888 elements[i].style.display=style;
892 addJS('function shownewobject(element) {
895 if(element.checked) {
901 var elements = document.getElementsByName(\'newobject\');
902 for(var i=0;i<elements.length;i++) {
903 elements[i].style.display=style;
907 addJS('function checkInput() {
908 var host = document.getElementById(\'host\');
910 if(host.value == "-1") {
911 var newvalue = prompt("Enter Hostname or IP Address","");
913 host.options[host.options.length] = new Option(newvalue, newvalue);
914 host.value = newvalue;
918 if(host.value != "-1" && host.value != "")
924 echo '<body onload="document.getElementById(\'submitbutton\').focus(); showsnmpv3(document.getElementById(\'snmpversion\')); shownewobject(document.getElementById(\'asnewobject\'));">';
926 foreach( $endpoints as $key => $value) {
927 $endpoints[$value] = $value;
928 unset($endpoints[$key]);
933 foreach( getObjectIPv4Allocations($object_id) as $ip => $value) {
935 $ip = ip_format($ip);
937 if(!in_array($ip, $endpoints))
938 $endpoints[$ip] = $ip;
943 foreach( getObjectIPv6Allocations($object_id) as $value) {
944 $ip = ip_format(ip_parse($value['addrinfo']['ip']));
946 if(!in_array($ip, $endpoints))
947 $endpoints[$ip] = $ip;
951 /* ask for ip/host name on submit see js checkInput() */
952 $endpoints['-1'] = 'ask me';
954 // saved snmp settings
955 $snmpstr = strtok($object['comment'],"\n\r");
956 $snmpstrarray = explode(':', $snmpstr);
958 if($snmpstrarray[0] == "SNMP")
960 /* keep it compatible with older version */
961 switch($snmpstrarray[2])
964 $snmpstrarray[2] = 'v1';
968 $snmpstrarray[2] = 'v2c';
971 $snmpstrarray[2] = 'v3';
975 $snmpnames = array('SNMP','host', 'version', 'community');
976 if($snmpstrarray[2] == "v3")
977 $snmpnames = array_merge($snmpnames, array('sec_level','auth_protocol','auth_passphrase','priv_protocol','priv_passphrase'));
979 $snmpvalues = array();
980 foreach($snmpnames as $key => $value)
982 if(isset($snmpstrarray[$key]))
988 $snmpvalues[$value] = base64_decode($snmpstrarray[$key]);
991 default: $snmpvalues[$value] = $snmpstrarray[$key];
996 unset($snmpvalues['SNMP']);
998 $snmpconfig = $snmpvalues;
1001 $snmpconfig = array();
1003 $snmpconfig +
= $_POST;
1005 if(!isset($snmpconfig['host'])) {
1006 $snmpconfig['host'] = -1;
1008 /* try to find first FQDN or IP */
1009 foreach($endpoints as $value) {
1010 if(preg_match('/^[^ .]+(\.[^ .]+)+\.?/',$value)) {
1011 $snmpconfig['host'] = $value;
1018 // sg_var_dump_html($endpoints);
1020 if(!isset($snmpconfig['version']))
1021 $snmpconfig['version'] = mySNMP
::SNMP_VERSION
;
1023 if(!isset($snmpconfig['community']))
1024 $snmpconfig['community'] = getConfigVar('DEFAULT_SNMP_COMMUNITY');
1026 if(empty($snmpconfig['community']))
1027 $snmpconfig['community'] = mySNMP
::SNMP_COMMUNITY
;
1029 if(!isset($snmpconfig['sec_level']))
1030 $snmpconfig['sec_level'] = NULL;
1032 if(!isset($snmpconfig['auth_protocol']))
1033 $snmpconfig['auth_protocol'] = NULL;
1035 if(!isset($snmpconfig['auth_passphrase']))
1036 $snmpconfig['auth_passphrase'] = NULL;
1038 if(!isset($snmpconfig['priv_protocol']))
1039 $snmpconfig['priv_protocol'] = NULL;
1041 if(!isset($snmpconfig['priv_passphrase']))
1042 $snmpconfig['priv_passphrase'] = NULL;
1044 if(!isset($snmpconfig['asnewobject']))
1045 $snmpconfig['asnewobject'] = NULL;
1047 if(!isset($snmpconfig['object_type_id']))
1048 $snmpconfig['object_type_id'] = '8';
1050 if(!isset($snmpconfig['object_name']))
1051 $snmpconfig['object_name'] = NULL;
1053 if(!isset($snmpconfig['object_label']))
1054 $snmpconfig['object_label'] = NULL;
1056 if(!isset($snmpconfig['object_asset_no']))
1057 $snmpconfig['object_asset_no'] = NULL;
1059 if(!isset($snmpconfig['save']))
1060 $snmpconfig['save'] = true;
1062 // sg_var_dump_html($snmpconfig);
1064 // $snmpv3displaystyle = ($snmpconfig['version'] == "3" ? "style=\"\"" : "style=\"display:none;\"");
1066 echo '<h1 align=center>SNMP Config</h1>';
1067 echo '<form method=post name="snmpconfig" onsubmit="return checkInput()" action='.$_SERVER['REQUEST_URI'].' />';
1069 echo '<table cellspacing=0 cellpadding=5 align=center class=widetable>
1070 <tr><th class=tdright>Host:</th><td>';
1072 //if($snmpconfig['asnewobject'] == '1' )
1073 if($snmpconfig['host'] != '-1' and !isset($endpoints[$snmpconfig['host']]))
1074 $endpoints[$snmpconfig['host']] = $snmpconfig['host'];
1076 echo getSelect ($endpoints, array ('id' => 'host','name' => 'host'), $snmpconfig['host'], FALSE);
1080 <th class=tdright><label for=snmpversion>Version:</label></th>
1083 echo getSelect (array("v1" => 'v1', "v2c" => 'v2c', "v3" => 'v3'),
1084 array ('name' => 'version', 'id' => 'snmpversion', 'onchange' => 'showsnmpv3(this)'),
1085 $snmpconfig['version'], FALSE);
1090 <th id="snmp_community_label" class=tdright><label for=community>Community:</label></th>
1091 <th name="snmpv3" style="display:none;" class=tdright><label for=community>Security Name:</label></th>
1092 <td class=tdleft><input type=text name=community value='.$snmpconfig['community'].' ></td>
1094 <tr name="snmpv3" style="display:none;">
1097 <tr name="snmpv3" style="display:none;">
1098 <th class=tdright><label">Security Level:</label></th>
1101 echo getSelect (array('noAuthNoPriv' => 'no Auth and no Priv', 'authNoPriv'=> 'auth without Priv', 'authPriv' => 'auth with Priv'),
1102 array ('name' => 'sec_level'),
1103 $snmpconfig['sec_level'], FALSE);
1106 <tr name="snmpv3" style="display:none;">
1107 <th class=tdright><label>Auth Type:</label></th>
1109 <input name=auth_protocol type=radio value=MD5 '.($snmpconfig['auth_protocol'] == 'MD5' ?
' checked="checked"' : '').'/><label>MD5</label>
1110 <input name=auth_protocol type=radio value=SHA '.($snmpconfig['auth_protocol'] == 'SHA' ?
' checked="checked"' : '').'/><label>SHA</label>
1113 <tr name="snmpv3" style="display:none;">
1114 <th class=tdright><label>Auth Key:</label></th>
1115 <td class=tdleft><input type=password id=auth_passphrase name=auth_passphrase value="'.$snmpconfig['auth_passphrase'].'"></td>
1117 <tr name="snmpv3" style="display:none;">
1118 <th class=tdright><label>Priv Type:</label></th>
1120 <input name=priv_protocol type=radio value=DES '.($snmpconfig['priv_protocol'] == 'DES' ?
' checked="checked"' : '').'/><label>DES</label>
1121 <input name=priv_protocol type=radio value=AES '.($snmpconfig['priv_protocol'] == 'AES' ?
' checked="checked"' : '').'/><label>AES</label>
1124 <tr name="snmpv3" style="display:none;">
1125 <th class=tdright><label>Priv Key</label></th>
1126 <td class=tdleft><input type=password name=priv_passphrase value="'.$snmpconfig['priv_passphrase'].'"></td>
1133 <input name=asnewobject id=asnewobject type=checkbox value=1 onchange="shownewobject(this)"'.($snmpconfig['asnewobject'] == '1' ?
' checked="checked"' : '').'>
1134 <label>Create as new object</label></td>
1137 // $newobjectdisplaystyle = ($snmpconfig['asnewobject'] == '1' ? "" : "style=\"display:none;\"");
1139 echo '<tr name="newobject" style="display:none;">
1140 <th class=tdright>Type:</th><td class=tdleft>';
1142 $typelist = withoutLocationTypes (readChapter (CHAP_OBJTYPE
, 'o'));
1143 $typelist = cookOptgroups ($typelist);
1145 printNiftySelect ($typelist, array ('name' => "object_type_id"), $snmpconfig['object_type_id']);
1149 <tr name="newobject" style="display:none;">
1150 <th class=tdright>Common name:</th><td class=tdleft><input type=text name=object_name value='.$snmpconfig['object_name'].'></td></tr>
1151 <tr name="newobject" style="display:none;">
1152 <th class=tdright>Visible label:</th><td class=tdleft><input type=text name=object_label value='.$snmpconfig['object_label'].'></td></tr>
1153 <tr name="newobject" style="display:none;">
1154 <th class=tdright>Asset tag:</th><td class=tdleft><input type=text name=object_asset_no value='.$snmpconfig['object_asset_no'].'></td></tr>
1159 <input name=save id=save type=checkbox value=1'.($snmpconfig['save'] == '1' ?
' checked="checked"' : '').'>
1160 <label>Save SNMP settings for object</label></td>
1164 <input type=hidden name=snmpconfig value=1>
1165 <input type=submit id="submitbutton" tabindex="1" value="Show List"></td></tr>
1169 } /* snmpgeneric_snmpconfig */
1171 function snmpgeneric_list($object_id) {
1173 global $sg_create_noconnector_ports, $sg_known_sysObjectIDs, $sg_portoifoptions, $sg_ifType_ignore;
1175 if(isset($_POST['snmpconfig'])) {
1176 $snmpconfig = $_POST;
1178 showError("Missing SNMP Config");
1182 // sg_var_dump_html($snmpconfig);
1184 echo '<body onload="document.getElementById(\'createbutton\').focus();">';
1186 addJS('function setchecked(classname) { var boxes = document.getElementsByClassName(classname);
1187 var value = document.getElementById(classname).checked;
1188 for(i=0;i<boxes.length;i++) {
1189 if(boxes[i].disabled == false)
1190 boxes[i].checked=value;
1194 $object = spotEntity ('object', $object_id);
1196 $object['attr'] = getAttrValues($object_id);
1198 $snmpdev = new mySNMP($snmpconfig['version'], $snmpconfig['host'], $snmpconfig['community']);
1200 if($snmpconfig['version'] == "v3" ) {
1201 $snmpdev->setSecurity( $snmpconfig['sec_level'],
1202 $snmpconfig['auth_protocol'],
1203 $snmpconfig['auth_passphrase'],
1204 $snmpconfig['priv_protocol'],
1205 $snmpconfig['priv_passphrase']
1211 if($snmpdev->getErrno()) {
1212 showError($snmpdev->getError());
1216 /* SNMP connect successfull */
1218 showSuccess("SNMP ".$snmpconfig['version']." connect to ${snmpconfig['host']} successfull");
1220 echo '<form name=CreatePorts method=post action='.$_SERVER['REQUEST_URI'].'&module=redirect&op=create>';
1222 echo "<strong>System Informations</strong>";
1224 // echo "<tr><th>OID</th><th>Value</th></tr>";
1226 $systemoids = array('sysDescr', 'sysObjectID', 'sysUpTime', 'sysContact', 'sysName', 'sysLocation');
1227 foreach ($systemoids as $shortoid) {
1229 $value = $snmpdev->{$shortoid};
1231 if($shortoid == 'sysUpTime') {
1232 /* in hundredths of a second */
1233 $secs = (int)($value / 100);
1234 $days = (int)($secs / (60 * 60 * 24));
1235 $secs -= $days * 60 *60 * 24;
1236 $hours = (int)($secs / (60 * 60));
1237 $secs -= $hours * 60 * 60;
1238 $mins = (int)($secs / (60));
1239 $secs -= $mins * 60;
1240 $value = "$value ($days $hours:$mins:$secs)";
1243 echo "<tr><td title=\"".$snmpdev->lastgetoid
."\" align=\"right\">$shortoid: </td><td>$value</td></tr>";
1250 /* sysObjectID Attributes and Ports */
1251 $sysObjectID['object'] = &$object;
1253 /* get sysObjectID */
1254 $sysObjectID['raw_value'] = $snmpdev->sysObjectID
;
1255 //$sysObjectID['raw_value'] = 'NET-SNMP-MIB::netSnmpAgentOIDs.10';
1257 $sysObjectID['value'] = preg_replace('/^.*enterprises\.([\.[:digit:]]+)$/','\\1', $sysObjectID['raw_value']);
1259 /* try snmptranslate to numeric */
1260 if(preg_match('/[^\.0-9]+/',$sysObjectID['value'])) {
1261 $numeric_value = $snmpdev->translatetonumeric($sysObjectID['value']);
1263 if(!empty($numeric_value)) {
1264 showSuccess("sysObjectID: ".$sysObjectID['value']." translated to $numeric_value");
1265 $sysObjectID['value'] = preg_replace('/^.1.3.6.1.4.1.([\.[:digit:]]+)$/','\\1', $numeric_value);
1269 /* array_merge doesn't work with numeric keys !! */
1270 $sysObjectID['attr'] = array();
1271 $sysObjectID['port'] = array();
1273 $sysobjid = $sysObjectID['value'];
1279 if(isset($sg_known_sysObjectIDs[$sysobjid])) {
1280 $sysObjectID = $sysObjectID +
$sg_known_sysObjectIDs[$sysobjid];
1282 if(isset($sg_known_sysObjectIDs[$sysobjid]['attr']))
1283 $sysObjectID['attr'] = $sysObjectID['attr'] +
$sg_known_sysObjectIDs[$sysobjid]['attr'];
1285 if(isset($sg_known_sysObjectIDs[$sysobjid]['port']))
1286 $sysObjectID['port'] = $sysObjectID['port'] +
$sg_known_sysObjectIDs[$sysobjid]['port'];
1288 if(isset($sg_known_sysObjectIDs[$sysobjid]['text'])) {
1289 showSuccess("found sysObjectID ($sysobjid) ".$sg_known_sysObjectIDs[$sysobjid]['text']);
1293 $sysobjid = preg_replace('/\.[[:digit:]]+$/','',$sysobjid, 1, $count);
1295 /* add default sysobjectid */
1296 if($count == 0 && $sysobjid != 'default') {
1297 $sysobjid = 'default';
1302 $sysObjectID['vendor_number'] = $sysobjid;
1305 if(isset($sysObjectID['pf']))
1306 foreach($sysObjectID['pf'] as $function) {
1307 if(function_exists($function)) {
1308 /* call device pf */
1309 $function($snmpdev, $sysObjectID, NULL);
1311 showWarning("Missing processor function ".$function." for device $sysobjid");
1316 /* sort attributes maintain numeric keys */
1317 ksort($sysObjectID['attr']);
1320 //sg_var_dump_html($sysObjectID['attr'], "Before processing");
1322 /* needs PHP >= 5 foreach call by reference */
1323 /* php 5.1.6 doesn't seem to work */
1324 //foreach($sysObjectID['attr'] as $attr_id => &$attr)
1325 foreach($sysObjectID['attr'] as $attr_id => $value) {
1327 $attr = &$sysObjectID['attr'][$attr_id];
1329 if(isset($object['attr'][$attr_id])) {
1333 case isset($attr['pf']):
1334 if(function_exists($attr['pf'])) {
1336 $attr['pf']($snmpdev, $sysObjectID, $attr_id);
1339 showWarning("Missing processor function ".$attr['pf']." for attribute $attr_id");
1344 case isset($attr['oid']):
1346 $attrvalue = $snmpdev->get($attr['oid']);
1348 if(isset($attr['regex'])) {
1349 $regex = $attr['regex'];
1351 if(isset($attr['replacement'])) {
1352 $replacement = $attr['replacement'];
1353 $attrvalue = preg_replace($regex, $replacement, $attrvalue);
1355 if(!preg_match($regex, $attrvalue)) {
1356 if(!isset($attr['uncheck']))
1357 $attr['uncheck'] = "regex doesn't match";
1359 unset($attr['uncheck']);
1363 $attr['value'] = $attrvalue;
1367 case isset($attr['value']):
1371 showError("Error handling attribute id: $attr_id");
1376 showWarning("Object has no attribute id: $attr_id");
1377 unset($sysObjectID['attr'][$attr_id]);
1383 /* sort again in case there where attribs added ,maintain numeric keys */
1384 ksort($sysObjectID['attr']);
1386 /* print attributes */
1387 echo '<br>Attributes<br><table>';
1388 echo '<tr><th><input type="checkbox" id="attribute" checked="checked" onclick="setchecked(this.id)"></td>';
1389 echo '<th>Name</th><th>Current Value</th><th>new value</th></tr>';
1392 //sg_var_dump_html($sysObjectID['attr'], "After processing");
1394 foreach($sysObjectID['attr'] as $attr_id => &$attr) {
1396 if(isset($object['attr'][$attr_id]) && isset($attr['value'])) {
1398 if($attr['value'] == $object['attr'][$attr_id]['value'])
1399 $attr['uncheck'] = 'Current = new value';
1401 $value = $attr['value'];
1403 $val_key = (isset($object['attr'][$attr_id]['key']) ?
' ('.$object['attr'][$attr_id]['key'].')' : '' );
1406 if(isset($attr['comment'])) {
1407 if(!empty($attr['comment']))
1408 $comment = $attr['comment'];
1411 if(isset($attr['uncheck'])) {
1413 $comment .= ', '.$attr['uncheck'];
1415 $checked = ' checked="checked"';
1418 $updateattrcheckbox = '<b style="background-color:#00ff00">'
1419 .'<input style="background-color:#00ff00" class="attribute" type="checkbox" name="updateattr['.$attr_id.']" value="'.$value.'"'
1422 $comment = trim($comment,', ');
1424 echo "<tr><td>$updateattrcheckbox</td><td title=\"id: $attr_id\">"
1425 .$object['attr'][$attr_id]['name'].'</td><td style="background-color:#d8d8d8">'
1426 .$object['attr'][$attr_id]['value'].$val_key.'</td><td>'.$value.'</td>'
1427 .'<td style="color:#888888">'.$comment.'</td></tr>';
1437 amplifyCell($object);
1439 /* set array key to port name */
1440 foreach($object['ports'] as $key => $values) {
1441 $object['ports'][$values['name']] = $values;
1442 unset($object['ports'][$key]);
1445 $newporttypeoptions = getNewPortTypeOptions();
1447 // sg_var_dump_html($sysObjectID['port']);
1449 if(!empty($sysObjectID['port'])) {
1451 echo '<br>Vendor / Device specific ports<br>';
1452 echo '<table><tr><th><input type="checkbox" id="moreport" checked="checked" onclick="setchecked(this.id)"></th><th>ifName</th><th>porttypeid</th></tr>';
1454 foreach($sysObjectID['port'] as $name => $port) {
1456 if(array_key_exists($name,$object['ports']))
1457 $disableport = TRUE;
1459 $disableport = FALSE;
1463 if(isset($port['comment'])) {
1464 if(!empty($port['comment']))
1465 $comment = $port['comment'];
1467 if(isset($port['uncheck'])) {
1469 $comment .= ', '.$port['uncheck'];
1471 $checked = ' checked="checked"';
1474 $portcreatecheckbox = '<b style="background-color:'.($disableport ?
'#ff0000' : '#00ff00')
1475 .'"><input style="background-color:'.($disableport ?
'#ff0000' : '#00ff00').'" class="moreport" type="checkbox" name="portcreate['.$name.']" value="'.$name.'"'
1476 .($disableport ?
' disabled="disbaled"' : $checked ).'></b>';
1478 $formfield = '<input type="hidden" name="ifName['.$name.']" value="'.$name.'">';
1479 echo "<tr>$formfield<td>$portcreatecheckbox</td><td>$name</td>";
1481 if(isset($port['disabled'])) {
1482 $disabledselect = array('disabled' => "disabled");
1484 $disabledselect = array();
1487 foreach($port as $key => $value) {
1489 if($key == 'uncheck' ||
$key == 'comment')
1493 if($key == 'porttypeid')
1494 $displayvalue = getNiftySelect($newporttypeoptions,
1495 array('name' => "porttypeid[$name]") +
$disabledselect, $value);
1496 /* disabled formfied won't be submitted ! */
1498 $displayvalue = $value;
1500 $formfield = '<input type="hidden" name="'.$key.'['.$name.']" value="'.$value.'">';
1501 echo "$formfield<td>$displayvalue</td>";
1504 $comment = trim($comment,', ');
1505 echo "<td style=\"color:#888888\">$comment</td></tr>";
1515 $ifsnmp = new ifSNMP($snmpdev);
1520 foreach($ifsnmp->ipaddress
as $ifindex => $ipaddresses) {
1522 foreach($ipaddresses as $ipaddr => $value) {
1523 $addrtype = $value['addrtype'];
1524 $netaddr = $value['net'];
1525 $maskbits = $value['maskbits'];
1529 //echo "<br> - DEBUG: ipspace $ipaddr - $netaddr - $addrtype - $maskbits<br>";
1531 /* check for ip space */
1538 $netid = getIPv4AddressNetworkId(ip_parse($ipaddr));
1543 /* format ipaddr for ip6_parse */
1544 $ipaddr = preg_replace('/((..):(..))/','\\2\\3',$ipaddr);
1545 $ipaddr = preg_replace('/%.*$/','',$ipaddr);
1547 if(ip_checkparse($ipaddr) === false)
1548 continue(2); // 2 because of switch
1550 $ip6_bin = ip6_parse($ipaddr);
1551 $ip6_addr = ip_format($ip6_bin);
1552 $netid = getIPv6AddressNetworkId($ip6_bin);
1554 $node = constructIPRange($ip6_bin, $maskbits);
1556 $netaddr = $node['ip'];
1557 $linklocal = substr($ip6_addr,0,5) == "fe80:";
1559 //echo "<br> - DEBUG: ipspace $ipaddr - $addrtype - $maskbits - $netaddr - >$linklocal<<br>";
1570 if(empty($netid) && $netaddr != '::1' && $netaddr != '127.0.0.1' && $netaddr != '127.0.0.0' && $netaddr != '0.0.0.0' && !$linklocal) {
1572 $netaddr .= "/$maskbits";
1573 $ipspace[$netaddr] = array('addrtype' => $addrtype, 'checked' => ($maskbits > 0 ?
true : false));
1581 unset($ipaddresses);
1583 /* print ip spaces table */
1584 if(!empty($ipspace)) {
1585 echo '<br><br>Create IP Spaces';
1586 echo '<table><tr><th><input type="checkbox" id="ipspace" onclick="setchecked(this.id)" checked=\"checked\"></th>';
1587 echo '<th>Type</th><th>prefix</th><th>name</th><th width=150 title="reserve network and router addresses">reserve network / router addresses</th></tr>';
1590 foreach($ipspace as $prefix => $ipspace) {
1592 $netcreatecheckbox = '<b style="background-color:#00ff00">'
1593 .'<input class="ipspace" style="background-color:#00ff00" type="checkbox" name="netcreate['
1594 .$i.']" value="'.$ipspace['addrtype'].'"'.($ipspace['checked'] ?
' checked=\"checked\"' : '').'></b>';
1596 $netprefixfield = '<input type="text" size=50 name="netprefix['.$i.']" value="'.$prefix.'">';
1598 $netnamefield = '<input type="text" name="netname['.$i.']">';
1600 $netreservecheckbox = '<input type="checkbox" name="netreserve['.$i.']" checked="checked">';
1602 echo "<tr><td>$netcreatecheckbox</td><td style=\"color:#888888\">${ipspace['addrtype']}</td><td>$netprefixfield</td><td>$netnamefield</td><td>$netreservecheckbox</td></tr>";
1614 echo "<br><br>ifNumber: ".$ifsnmp->ifNumber
."<br>indexcount: ".$ifsnmp->indexcount
."<br><table><tbody valign=\"top\">";
1616 $portcompat = getPortInterfaceCompat();
1620 $ifsnmp->printifInfoTableHeader("<th>add ip</th><th>add port</th><th>upd label</th><th title=\"update mac\">upd mac</th><td>upd port type</th><th>porttypeid</th><th>comment</th></tr>");
1622 echo '<tr><td colspan="11"></td>
1623 <td><input type="checkbox" id="ipaddr" onclick="setchecked(this.id)">IPv4<br>
1624 <input type="checkbox" id="ipv6addr" onclick="setchecked(this.id)">IPv6</td>
1625 <td><input type="checkbox" id="ports" onclick="setchecked(this.id)"></td>
1626 <td><input type="checkbox" id="label" onclick="setchecked(this.id)" checked="checked"></td>
1627 <td><input type="checkbox" id="mac" onclick="setchecked(this.id)" checked="checked"></td>
1628 <td><input type="checkbox" id="porttype" onclick="setchecked(this.id);"></td></tr>';
1630 foreach($ifsnmp as $if) {
1633 $disableport = FALSE;
1634 $ignoreport = FALSE;
1636 $updatelabel = false;
1637 $updateporttype = false;
1639 $updatemaccheckbox = '';
1645 if(trim($ifsnmp->ifName($if)) == '') {
1646 $comment .= "no ifName";
1647 $createport = FALSE;
1650 if(array_key_exists($ifsnmp->ifName($if),$object['ports'])){
1651 $port_info = &$object['ports'][$ifsnmp->ifName($if)];
1652 $comment .= "Name exists";
1654 /* ifalias change */
1655 if($port_info['label'] != $ifsnmp->ifAlias($if))
1656 $updatelabel = true;
1658 $createport = FALSE;
1659 $disableport = TRUE;
1663 if($ifsnmp->ifPhysAddress($if) != '' ) {
1665 $ifPhysAddress = $ifsnmp->ifPhysAddress($if);
1667 $l2port = sg_checkL2Address($ifPhysAddress);
1669 if(!empty($l2port)) {
1671 $l2object_id = key($l2port);
1673 $porthref = makeHref(array('page'=>'object', 'tab' => 'ports',
1674 'object_id' => $l2object_id, 'hl_port_id' => $l2port[$l2object_id]));
1676 $comment .= ", L2Address exists";
1677 $hrefs['ifPhysAddress'] = $porthref;
1678 $createport = FALSE;
1679 // $disableport = TRUE;
1680 $updatemaccheckbox = '';
1685 if($port_info !== NULL) {
1686 if(str_replace(':','',$port_info['l2address']) != $ifPhysAddress)
1687 $disablemac = false;
1692 /* port create always updates mac */
1693 $updatemaccheckbox = '<b style="background-color:#00ff00">'
1694 .'<input style="background-color:'
1695 .'#00ff00" type="checkbox"'
1696 .' checked="checked"'
1697 .' disabled=\"disabled\"></b>';
1701 $updatemaccheckbox = '<b style="background-color:'.($disablemac ?
'#ff0000' : '#00ff00').'">'
1702 .'<input class="mac" style="background-color:'
1703 .($disablemac ?
'#ff0000' : '#00ff00').'" type="checkbox" name="updatemac['.$if.']" value="'
1704 .$object['ports'][$ifsnmp->ifName($if)]['id'].'" checked="checked"'
1705 .($disablemac ?
' disabled=\"disabled\"' : '' ).'></b>';
1710 $porttypeid = guessRToif_id($ifsnmp->ifType($if), $ifsnmp->ifDescr($if));
1712 if(in_array($ifsnmp->ifType($if),$sg_ifType_ignore)) {
1713 $comment .= ", ignore if type";
1714 $createport = FALSE;
1721 $ptid = $port_info['iif_id']."-".$port_info['oif_id'];
1722 if($porttypeid != $ptid)
1724 $comment .= ", Update Type $ptid -> $porttypeid";
1725 $updateporttype = true;
1730 /* ignore ports without an Connector */
1731 if(!$sg_create_noconnector_ports && ($ifsnmp->ifConnectorPresent($if) == 2)) {
1732 $comment .= ", no Connector";
1733 $createport = FALSE;
1736 /* Allocate IPs ipv4 and ipv6 */
1738 $ipaddresses = $ifsnmp->ipaddress($if);
1740 if(!empty($ipaddresses)) {
1742 $ipaddrcell = '<table>';
1744 foreach($ipaddresses as $ipaddr => $value) {
1745 $createipaddr = FALSE;
1746 $disableipaddr = FALSE;
1750 $addrtype = $value['addrtype'];
1751 $maskbits = $value['maskbits'];
1752 $bcast = $value['bcast'];
1754 //echo "<br> - DEBUG: ip $ipaddr - $addrtype - $maskbits - $bcast<br>";
1766 $disableipaddr = TRUE;
1768 $inputname = 'ipv6';
1770 /* format ipaddr for ip6_parse */
1771 $ipaddr = preg_replace('/((..):(..))/','\\2\\3',$ipaddr);
1772 $ipaddr = preg_replace('/%.*$/','',$ipaddr);
1774 if(ip_checkparse($ipaddr) === false)
1775 continue(2); // 2 because of switch
1777 /* ip_parse throws exception on parse errors */
1778 $ip6_bin = ip_parse($ipaddr);
1779 $ipaddr = ip_format($ip6_bin);
1781 $node = constructIPRange($ip6_bin, $maskbits);
1783 $linklocal = ($node['ip'] == 'fe80::');
1785 $createipaddr = FALSE;
1790 $address = getIPAddress(ip_parse($ipaddr));
1792 /* only if ip not already allocated */
1793 if(empty($address['allocs'])) {
1795 $createipaddr = TRUE;
1798 $disableipaddr = TRUE;
1800 $ipobject_id = $address['allocs'][0]['object_id'];
1802 $ipaddrhref = makeHref(array('page'=>'object',
1803 'object_id' => $ipobject_id, 'hl_ipv4_addr' => $ipaddr));
1807 /* reserved addresses */
1808 if($address['reserved'] == 'yes') {
1809 $comment .= ', '.$address['ip'].' reserved '.$address['name'];
1810 $createipaddr = FALSE;
1811 // $disableipaddr = TRUE;
1814 if($ipaddr == '127.0.0.1' ||
$ipaddr == '0.0.0.0' ||
$ipaddr == '::1' ||
$ipaddr == '::' ||
$linklocal) {
1815 $createipaddr = FALSE;
1816 $disableipaddr = TRUE;
1819 if($ipaddr === $bcast) {
1820 $comment .= ", $ipaddr broadcast";
1821 $createipaddr = FALSE;
1822 $disableipaddr = TRUE;
1825 if(!$disableipaddr) {
1826 $ipaddrcheckbox = '<b style="background-color:'.($disableipaddr ?
'#ff0000' : '#00ff00')
1827 .'"><input class="'.$inputname.'addr" style="background-color:'
1828 .($disableipaddr ?
'#ff0000' : '#00ff00')
1829 .'" type="checkbox" name="'.$inputname.'addrcreate['.$ipaddr.']" value="'.$if.'"'
1830 .($disableipaddr ?
' disabled="disabled"' : '')
1831 .($createipaddr ?
' checked="checked"' : '').'></b>';
1833 $ipaddrcheckbox = '';
1836 $ipaddrcell .= "<tr><td>$ipaddrcheckbox</td>";
1838 if(!empty($ipaddrhref)) {
1839 $ipaddrcell .= "<td><a href=$ipaddrhref>$ipaddr/$maskbits</a></td></tr>";
1841 $ipaddrcell .= "<td>$ipaddr/$maskbits</td></tr>";
1848 $ipaddrcell .= '</table>';
1850 // if(!empty($ipaddresses))
1852 $ipaddrcreatecheckbox = '';
1856 /* checkboxes for add port and add ip */
1857 /* FireFox needs <b style=..>, IE and Opera work with <td style=..> */
1859 $portcreatecheckbox = '<b style="background-color:'.($disableport ?
'#ff0000' : '#00ff00')
1860 .'"><input class="ports" style="background-color:'.($disableport ?
'#ff0000' : '#00ff00')
1861 .'" type="checkbox" name="portcreate['.$if.']" value="'.$if.'"'
1862 .($disableport ?
' disabled="disbaled"' : '').($createport ?
' checked="checked"' : '').'></b>';
1864 $portcreatecheckbox = '';
1867 /* add port type to newporttypeoptions if missing */
1868 if(strpos(serialize($newporttypeoptions),$porttypeid) === FALSE) {
1870 $portids = explode('-',$porttypeid);
1871 $oif_name = $sg_portoifoptions[$portids[1]];
1873 $newporttypeoptions['auto'] = array($porttypeid => "*$oif_name");
1876 $selectoptions = array('name' => "porttypeid[$if]");
1878 if($disableport && !$updateporttype)
1879 $selectoptions['disabled'] = "disabled";
1881 $updateporttypecheckbox = "";
1884 $updateporttypecheckbox = '<b style="background-color:#00ff00;">'
1885 .'<input class="porttype" style="background-color:#00ff00;" type="checkbox" name="updateporttype['.$if.']" value="'
1886 .$port_info['id'].'"></b>';
1888 $porttypeidselect = getNiftySelect($newporttypeoptions, $selectoptions, $porttypeid);
1890 $updatelabelcheckbox = "";
1893 $updatelabelcheckbox = '<b style="background-color:#00ff00;">'
1894 .'<input class="label" style="background-color:#00ff00;" type="checkbox" name="updatelabel['.$if.']" value="'
1895 .$port_info['id'].($updatelabel ?
'" checked="checked"' : '' ).'></b>';
1897 $comment = trim($comment,', ');
1899 $ifsnmp->printifInfoTableRow($if,"<td>$ipaddrcell</td><td>$portcreatecheckbox</td><td>$updatelabelcheckbox</td><td>$updatemaccheckbox</td><td>$updateporttypecheckbox</td><td>$porttypeidselect</td><td nowrap=\"nowrap\">$comment</td>", $hrefs);
1904 /* preserve snmpconfig */
1905 foreach($_POST as $key => $value) {
1906 echo '<input type=hidden name='.$key.' value='.$value.' />';
1911 echo '<tr><td colspan=15 align="right"><p><input id="createbutton" type=submit value="Create Ports and IPs" onclick="return confirm(\'Create selected items?\')"></p></td></tr></tbody></table></form>';
1913 } // END function snmpgeneric_list
1915 /* -------------------------------------------------- */
1916 function snmpgeneric_opcreate() {
1918 $object_id = $_REQUEST['object_id'];
1919 $attr = getAttrValues($object_id);
1921 // sg_var_dump_html($_REQUEST);
1922 // sg_var_dump_html($attr);
1924 /* commitUpdateAttrValue ($object_id, $attr_id, $new_value); */
1925 if(isset($_POST['updateattr'])) {
1926 foreach($_POST['updateattr'] as $attr_id => $value) {
1927 // if(empty($attr[$attr_id]['value']))
1928 if(!empty($value)) {
1929 commitUpdateAttrValue ($object_id, $attr_id, $value);
1930 showSuccess("Attribute ".$attr[$attr_id]['name']." set to $value");
1939 if(isset($_POST['portcreate'])) {
1940 foreach($_POST['portcreate'] as $if => $value) {
1942 $ifName = (isset($_POST['ifName'][$if]) ?
trim($_POST['ifName'][$if]) : '' );
1943 $ifPhysAddress = (isset($_POST['ifPhysAddress'][$if]) ?
trim($_POST['ifPhysAddress'][$if]) : '' );
1944 $ifAlias = (isset($_POST['ifAlias'][$if]) ?
trim($_POST['ifAlias'][$if]) : '' );
1945 $ifDescr = (isset($_POST['ifDescr'][$if]) ?
trim($_POST['ifDescr'][$if]) : '' );
1947 //$visible_label = (empty($ifAlias) ? '' : $ifAlias.'; ').$ifDescr;
1948 $visible_label = $ifAlias;
1950 if(empty($ifName)) {
1951 showError('Port without ifName '.$_POST['porttypeid'][$if].', '.$visible_label.', '.$ifPhysAddress);
1953 commitAddPort ($object_id, $ifName, $_POST['porttypeid'][$if], $visible_label, $ifPhysAddress);
1954 showSuccess('Port created '.$ifName.', '.$_POST['porttypeid'][$if].', '.$visible_label.', '.$ifPhysAddress);
1963 if(isset($_POST['netcreate'])) {
1964 foreach($_POST['netcreate'] as $id => $addrtype) {
1965 $range = $_POST['netprefix'][$id];
1966 $name = $_POST['netname'][$id];
1967 $is_reserved = isset($_POST['netreserve'][$id]);
1969 if($addrtype == 'ipv4' ||
$addrtype == 'ipv4z')
1970 createIPv4Prefix($range, $name, $is_reserved);
1972 createIPv6Prefix($range, $name, $is_reserved);
1974 showSuccess("$range $name created");
1982 /* allocate ipv6 adresses */
1983 if(isset($_POST['ipv6addrcreate'])) {
1984 foreach($_POST['ipv6addrcreate'] as $ipaddr => $if) {
1986 bindIPv6ToObject(ip6_parse($ipaddr), $object_id,$_POST['ifName'][$if], 1); /* connected */
1987 showSuccess("$ipaddr allocated");
1992 /* allocate ip adresses */
1993 if(isset($_POST['ipaddrcreate'])) {
1994 foreach($_POST['ipaddrcreate'] as $ipaddr => $if) {
1996 bindIPToObject(ip_parse($ipaddr), $object_id,$_POST['ifName'][$if], 1); /* connected */
1997 showSuccess("$ipaddr allocated");
2005 if(isset($_POST['updatelabel'])) {
2006 foreach($_POST['updatelabel'] as $if => $port_id) {
2008 $ifAlias = (isset($_POST['ifAlias'][$if]) ?
trim($_POST['ifAlias'][$if]) : '' );
2010 sg_commitUpdatePortLabel($object_id, $port_id, $ifAlias);
2012 $ifName = (isset($_POST['ifName'][$if]) ?
trim($_POST['ifName'][$if]) : '' );
2013 showSuccess("label updated on $ifName to $ifAlias");
2020 /* update mac addresses only */
2021 if(isset($_POST['updatemac'])) {
2022 foreach($_POST['updatemac'] as $if => $port_id) {
2024 $ifPhysAddress = (isset($_POST['ifPhysAddress'][$if]) ?
trim($_POST['ifPhysAddress'][$if]) : '' );
2026 sg_commitUpdatePortl2address($object_id, $port_id, $ifPhysAddress);
2028 $ifName = (isset($_POST['ifName'][$if]) ?
trim($_POST['ifName'][$if]) : '' );
2029 showSuccess("l2address updated on $ifName to $ifPhysAddress");
2036 /* update port type */
2037 if(isset($_POST['updateporttype'])) {
2038 foreach($_POST['updateporttype'] as $if => $port_id) {
2040 $porttypeid = (isset($_POST['porttypeid'][$if]) ?
trim($_POST['porttypeid'][$if]) : '' );
2042 sg_commitUpdatePortType($object_id, $port_id, $porttypeid);
2044 $ifName = (isset($_POST['ifName'][$if]) ?
trim($_POST['ifName'][$if]) : '' );
2045 showSuccess("port type updated on $ifName");
2050 /* updateporttype */
2051 } /* snmpgeneric_opcreate */
2053 /* -------------------------------------------------- */
2055 /* returns RT interface type depending on ifType, ifDescr, .. */
2056 function guessRToif_id($ifType,$ifDescr = NULL) {
2057 global $sg_ifType2oif_id;
2058 global $sg_portiifoptions;
2059 global $sg_portoifoptions;
2062 $retval = '24'; /* 1000BASE-T */
2064 if(isset($sg_ifType2oif_id[$ifType])) {
2065 $retval = $sg_ifType2oif_id[$ifType];
2068 if(strpos($retval,'-') === FALSE)
2069 $retval = "1-$retval";
2071 /* no ethernetCsmacd */
2076 /* try to identify outer and inner interface type from ifDescr */
2080 case preg_match('/fast.?ethernet/i',$ifDescr,$matches):
2084 case preg_match('/10.?gigabit.?ethernet/i',$ifDescr,$matches):
2085 // 10-Gigabit Ethernet
2088 case preg_match('/gigabit.?ethernet/i',$ifDescr,$matches):
2094 /**********************
2099 * Unit: 1 1000BASE-T RJ45 Gigabit Ethernet Frontpanel Port 45 - no sfp inserted
2100 * Unit: 1 1000BASE-T RJ45 Gigabit Ethernet Frontpanel Port 47 - sfp 1000BASE-SX inserted
2105 * Enterasys Networks, Inc. 1000BASE Gigabit Ethernet Port; No GBIC/MGBIC Inserted
2106 * Enterasys Networks, Inc. 1000BASE-SX Mini GBIC w/LC connector
2107 * Enterasys Networks, Inc. 10GBASE SFP+ 10-Gigabit Ethernet Port; No SFP+ Inserted
2108 * Enterasys Networks, Inc. 10GBASE-SR SFP+ 10-Gigabit Ethernet Port (850nm Short Wavelength, 33/82m MMF, LC)
2109 * Enterasys Networks, Inc. 1000BASE Gigabit Ethernet Port; Unknown GBIC/MGBIC Inserted
2113 foreach($sg_portiifoptions as $iif_id => $iif_type) {
2115 /* TODO better matching */
2119 if(preg_match('/(.*?)('.preg_quote($iif_type).')(.*)/i',$ifDescr,$matches)) {
2121 $oif_type = "empty ".$iif_type;
2123 $no = preg_match('/ no $/i', $matches[1]);
2125 if(preg_match('/(\d+[G]?)BASE[^ ]+/i', $matches[1], $basematch)) {
2126 $oif_type=$basematch[0];
2128 if(preg_match('/(\d+[G]?)BASE[^ ]+/i', $matches[3], $basematch)) {
2129 $oif_type=$basematch[0];
2134 /* 2 => SFP-100 or 4 => SFP-1000 */
2136 if(isset($basematch[1])) {
2137 switch($basematch[1]) {
2140 $iif_type = "SFP-100";
2145 $iif_type = "SFP-1000";
2150 if(preg_match('/sfp 1000-sx/i',$ifDescr))
2151 $oif_type = '1000BASE-SX';
2153 if(preg_match('/sfp 1000-lx/i',$ifDescr))
2154 $oif_type = '1000BASE-LX';
2159 $oif_type = "empty ".$iif_type;
2162 $oif_type = preg_replace('/BASE/',"Base",$oif_type);
2164 $oif_id = array_search($oif_type,$sg_portoifoptions);
2167 $retval = "$iif_id-$oif_id";
2170 /* TODO check port compat */
2179 if(strpos($retval,'-') === FALSE)
2180 $retval = "1-$retval";
2186 /* --------------------------------------------------- */
2188 function sg_commitUpdatePortl2address($object_id, $port_id, $port_l2address)
2190 $db_l2address = l2addressForDatabase ($port_l2address);
2193 $dbxlink->exec ('LOCK TABLES Port WRITE');
2194 if (alreadyUsedL2Address ($db_l2address, $object_id))
2196 $dbxlink->exec ('UNLOCK TABLES');
2197 // FIXME: it is more correct to throw InvalidArgException here
2198 // and convert it to InvalidRequestArgException at upper level,
2199 // when there is a mean to do that.
2200 throw new InvalidRequestArgException ('port_l2address', $db_l2address, 'address belongs to another object');
2202 usePreparedUpdateBlade
2207 'l2address' => ($db_l2address === '') ?
NULL : $db_l2address,
2212 'object_id' => $object_id
2215 $dbxlink->exec ('UNLOCK TABLES');
2216 } /* sg_commitUpdatePortl2address */
2218 /* --------------------------------------------------- */
2220 function sg_commitUpdatePortType($object_id, $port_id, $porttypeid)
2224 list($iif_id, $type) = explode("-",$porttypeid);
2226 $dbxlink->exec ('LOCK TABLES Port WRITE');
2227 usePreparedUpdateBlade
2232 'iif_id' => ($iif_id === '') ?
NULL : $iif_id,
2233 'type' => ($type === '') ?
NULL : $type
2238 'object_id' => $object_id
2241 $dbxlink->exec ('UNLOCK TABLES');
2242 } /* sg_commitUpdatePortType */
2244 function sg_commitUpdatePortLabel($object_id, $port_id, $label)
2248 $dbxlink->exec ('LOCK TABLES Port WRITE');
2249 usePreparedUpdateBlade
2254 'label' => ($label === '') ?
NULL : $label
2259 'object_id' => $object_id
2262 $dbxlink->exec ('UNLOCK TABLES');
2263 } /* sg_commitUpdatePortLabel */
2264 /* ----------------------------------------------------- */
2266 /* returns object_id and port_id to a given l2address */
2267 function sg_checkL2Address ($address)
2269 $result = usePreparedSelectBlade
2271 'SELECT object_id,id FROM Port WHERE BINARY l2address = ?',
2274 $row = $result->fetchAll(PDO
::FETCH_GROUP|PDO
::FETCH_UNIQUE|PDO
::FETCH_COLUMN
);
2278 function sg_checkObjectNameUniqueness ($name, $type_id, $object_id = 0)
2280 // Some object types do not need unique names
2283 $dupes_allowed = array (1560, 1561);
2284 if (in_array ($type_id, $dupes_allowed))
2287 $result = usePreparedSelectBlade
2289 'SELECT COUNT(*) FROM Object WHERE name = ? AND id != ?',
2290 array ($name, $object_id)
2292 $row = $result->fetch (PDO
::FETCH_NUM
);
2300 /* ------------------------------------------------------- */
2306 /* SNMPv1 and SNMPv2c */
2307 protected $community;
2310 protected $sec_level;
2311 protected $auth_protocol;
2312 protected $auth_passphrase;
2313 protected $priv_protocol;
2314 protected $priv_passphrase;
2315 // protected $contextName;
2316 // protected $contextEngineID;
2318 const VERSION_1
= 0;
2319 const VERSION_2C
= 1;
2320 const VERSION_2c
= 1;
2321 const VERSION_3
= 3;
2325 function __construct($version, $host, $community) {
2327 $this->host
= $host;
2329 $this->version
= $version;
2330 $this->community
= $community;
2332 set_error_handler(array($this,'ErrorHandler'), E_WARNING
);
2335 function setSecurity($sec_level, $auth_protocol = 'md5', $auth_passphrase = '', $priv_protocol = 'des', $priv_passphrase = '') {
2336 $this->sec_level
= $sec_level;
2337 $this->auth_protocol
= $auth_protocol;
2338 $this->auth_passphrase
= $auth_passphrase;
2339 $this->priv_protocol
= $priv_protocol;
2340 $this->priv_passphrase
= $priv_passphrase;
2345 function __set($name, $value)
2350 snmp_set_quick_print($value);
2352 case 'oid_output_format':
2353 snmp_set_oid_output_format($value);
2356 snmp_set_enum_print($value);
2358 case 'valueretrieval':
2359 snmp_set_valueretrieval($value);
2362 $trace = debug_backtrace();
2364 'Undefined property via __set(): ' . $name .
2365 ' in ' . $trace[0]['file'] .
2366 ' on line ' . $trace[0]['line'],
2372 function walk( $oid, $suffix_as_key = FALSE) {
2374 switch($this->version
) {
2375 case self
::VERSION_1
:
2377 $this->result
= snmpwalk($this->host
,$this->community
,$oid);
2379 $this->result
= snmprealwalk($this->host
,$this->community
,$oid);
2383 case self
::VERSION_2C
:
2384 case self
::VERSION_2c
:
2386 $this->result
= snmp2_walk($this->host
,$this->community
,$oid);
2388 $this->result
= snmp2_real_walk($this->host
,$this->community
,$oid);
2392 case self
::VERSION_3
:
2394 $this->result
= snmp3_walk($this->host
,$this->community
, $this->sec_level
, $this->auth_protocol
, $this->auth_passphrase
, $this->priv_protocol
, $this->priv_passphrase
,$oid);
2396 $this->result
= snmp3_real_walk($this->host
,$this->community
, $this->sec_level
, $this->auth_protocol
, $this->auth_passphrase
, $this->priv_protocol
, $this->priv_passphrase
,$oid);
2401 return $this->result
;
2405 private function __snmpget($object_id) {
2409 switch($this->version
) {
2410 case self
::VERSION_1
:
2411 $retval = snmpget($this->host
,$this->community
,$object_id);
2414 case self
::VERSION_2C
:
2415 case self
::VERSION_2c
:
2416 $retval = snmp2_get($this->host
,$this->community
,$object_id);
2419 case self
::VERSION_3
:
2420 $retval = snmp3_get($this->host
,$this->community
, $this->sec_level
, $this->auth_protocol
, $this->auth_passphrase
, $this->priv_protocol
, $this->priv_passphrase
,$object_id);
2427 function get($object_id, $preserve_keys = false) {
2429 if(is_array($object_id)) {
2431 if( $preserve_keys ) {
2432 foreach($object_id as $oid) {
2433 $this->result
[$oid] = $this->__snmpget($oid);
2437 foreach($object_id as $oid) {
2438 $result_oid = preg_replace('/.\d$/','',$oid);
2439 $this->result
[$result_oid] = $this->__snmpget($oid);
2444 $this->result
= $this->__snmpget($object_id);
2447 return $this->result
;
2454 function getErrno() {
2455 return ($this->result
=== FALSE);
2458 function getError() {
2459 $var = error_get_last();
2460 return $var['message'];
2463 function Errorhandler($errno, $errstr, $errfile, $errline) {
2465 case (False !== strpos($errstr,'No Such Object available on this agent at this OID')):
2466 /* no further error processing */
2471 /* proceed with default error handling */
2476 /* ------------------------------------------------------- */
2478 * SNMP with system OIDs
2480 class mySNMP
extends SNMPgeneric
implements Iterator
{
2482 const SNMP_VERSION
= parent
::VERSION_2C
;
2483 const SNMP_COMMUNITY
= 'public';
2490 /* is system table available ? */
2491 private $systemerror = TRUE;
2493 function __construct($version, $host, $community) {
2499 $version = parent
::VERSION_1
;
2504 $version = parent
::VERSION_2c
;
2508 $version = parent
::VERSION_3
;
2512 parent
::__construct($version, $host, $community);
2514 //snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
2516 /* Return values without SNMP type hint */
2517 //snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
2518 $this->valueretrieval
= SNMP_VALUE_PLAIN
;
2520 /* needs php >= 5.2.0 */
2521 // snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);
2523 // snmp_set_quick_print(1);
2528 /* .iso.org.dod.internet.mgmt.mib-2.system */
2529 $this->system
= $this->walk(".1.3.6.1.2.1.1");
2531 $this->systemerror
= $this->getErrno() ||
empty($this->system
);
2534 /* get value from system cache */
2535 private function _getvalue($object_id) {
2537 /* TODO better matching */
2539 if( isset($this->system
["SNMPv2-MIB::$object_id"])) {
2540 $this->lastgetoid
= "SNMPv2-MIB::$object_id";
2541 return $this->system
["SNMPv2-MIB::$object_id"];
2543 if( isset($this->system
[".iso.org.dod.internet.mgmt.mib-2.system.$object_id"])) {
2544 $this->lastgetoid
= ".iso.org.dod.internet.mgmt.mib-2.system.$object_id";
2545 return $this->system
[".iso.org.dod.internet.mgmt.mib-2.system.$object_id"];
2547 if( isset($this->system
[$object_id])) {
2548 $this->lastgetoid
= $object_id;
2549 return $this->system
[$object_id];
2551 foreach($this->system
as $key => $value) {
2552 if(strpos($key, $object_id)) {
2553 $this->lastgetoid
= $key;
2566 function get($object_id, $preserve_keys = false) {
2568 if(!$this->systemerror
)
2569 $retval = $this->_getvalue($object_id);
2573 if($retval === NULL) {
2574 $this->lastgetoid
= $object_id;
2575 $retval = parent
::get($object_id,$preserve_keys);
2582 function translatetonumeric($oid) {
2583 global $sg_cmd_snmptranslate;
2585 $val = exec(escapeshellcmd($sg_cmd_snmptranslate).' -On '.escapeshellarg($oid), $output, $retval);
2592 } /* translatetonumeric */
2594 function get_new($object_id, $preserve_keys = false) {
2595 $result = parent::get($object_id,$preserve_keys);
2596 return $this->removeDatatype($result);
2599 function walk_new($object_id) {
2600 $result = parent::walk($object_id);
2601 return $this->removeDatatype($result);
2605 /* use snmp_set_valueretrieval(SNMP_VALUE_PLAIN) instead */
2606 /* function removeDatatype($val) {
2607 return preg_replace('/^\w+: /','',$val);
2610 /* make something like $class->sysDescr work */
2611 function __get($name) {
2612 if($this->systemerror
) {
2616 $retval = $this->_getvalue($name);
2618 if($retval === NULL) {
2620 $trace = debug_backtrace();
2622 'Undefinierte Eigenschaft für __call(): ' . $name .
2623 ' in ' . $trace[0]['file'] .
2624 ' Zeile ' . $trace[0]['line'],
2632 /* Iteration through all system OIDs */
2635 function current() {
2636 if($this->systemerror
)
2639 return current($this->system
);
2643 if($this->systemerror
)
2646 return key($this->system
);
2650 return next($this->system
);
2654 return ($this->current() !== FALSE) && ($this->systemerror
!== TRUE);
2658 if($this->systemerror
)
2661 reset($this->system
);
2668 /* ------------------------------------------------------- */
2670 class ifSNMP
implements Iterator
{
2671 private $snmpdevice;
2672 private $ifNumber = 0;
2673 private $indexcount = 0;
2676 private $interfaceserror = TRUE;
2678 function __construct(&$snmpdevice) {
2679 $this->snmpdevice
= $snmpdevice;
2681 $this->ifNumber
= intval($this->snmpdevice
->get('ifNumber.0'));
2683 $this->interfaceserror
= $this->snmpdevice
->getErrno();
2685 if(!$this->interfaceserror
) {
2686 $this->getifTable();
2690 function getifTable() {
2691 $this->ifTable
['ifIndex'] = $this->snmpdevice
->walk('ifIndex',TRUE);
2693 $this->indexcount
= count($this->ifTable
['ifIndex']);
2695 $this->ifTable
['ifDescr'] = $this->snmpdevice
->walk('ifDescr',TRUE);
2696 $this->ifTable
['ifAlias'] = $this->snmpdevice
->walk('ifAlias',TRUE);
2697 $this->ifTable
['ifName'] = $this->snmpdevice
->walk('ifName',TRUE);
2699 $this->ifTable
['ifType'] = $this->snmpdevice
->walk('ifType',TRUE);
2701 $this->ifTable
['ifSpeed'] = $this->snmpdevice
->walk('ifSpeed',TRUE);
2703 /* notation changes when SNMP_VALUE_PLAIN is set string -> hex!! */
2704 $this->ifTable
['ifPhysAddress'] = $this->snmpdevice
->walk('ifPhysAddress',TRUE);
2706 $this->ifTable
['ifOperStatus'] = $this->snmpdevice
->walk('ifOperStatus',TRUE);
2708 $this->ifTable
['ifInOctets'] = $this->snmpdevice
->walk('ifInOctets',TRUE);
2709 $this->ifTable
['ifOutOctets'] = $this->snmpdevice
->walk('ifOutOctets',TRUE);
2711 $this->ifTable
['ifConnectorPresent'] = $this->snmpdevice
->walk('ifConnectorPresent',TRUE);
2713 $this->ifTable
['ipaddress'] = array();
2715 /* ip address v4 only ipaddrtable */
2716 $ipAdEntIfIndex = $this->snmpdevice
->walk('ipAdEntIfIndex');
2718 if(!empty($ipAdEntIfIndex)) {
2719 $ipAdEntNetMask = $this->snmpdevice
->walk('ipAdEntNetMask');
2721 /* all addresses per interface */
2723 reset($ipAdEntNetMask);
2724 foreach($ipAdEntIfIndex as $oid => $value) {
2726 $netmask = current($ipAdEntNetMask);
2727 next($ipAdEntNetMask);
2729 $ipaddr = preg_replace('/.*\.([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/','$1',$oid);
2731 $ifindex = array_search($value,$this->ifTable
['ifIndex']);
2733 if($netmask != '0.0.0.0') {
2734 $maskbits = 32-log((ip2long($netmask) ^
0xffffffff)+
1,2);
2735 $net = ip2long($ipaddr) & ip2long($netmask);
2736 $bcast = $net |
( ip2long($netmask) ^
0xffffffff);
2738 $this->ifTable
['ipaddress'][$ifindex][$ipaddr] = array(
2739 'addrtype' => 'ipv4',
2740 'maskbits' => $maskbits,
2741 'net' => long2ip($net),
2742 'bcast' => long2ip($bcast)
2750 // sg_var_dump_html($this->ipaddress);
2751 // sg_var_dump_html($ipAdEntIfIndex);
2752 // sg_var_dump_html($ipAdEntNetMask);
2753 } /* ipadentifindex */
2755 /* ipv4 ipv6 ipaddresstable */
2756 /* also overwrites ipv4 from ipaddrtable */
2757 $ipAddressIfIndex = $this->snmpdevice
->walk('ipAddressIfIndex');
2759 if(!empty($ipAddressIfIndex)) {
2760 $ipAddressPrefix = $this->snmpdevice
->walk('ipAddressPrefix');
2761 $ipAddressType = $this->snmpdevice
->walk('ipAddressType'); /* 1 unicast, 2 anycast, 3 braodcast */
2763 reset($ipAddressPrefix);
2764 reset($ipAddressType);
2765 foreach($ipAddressIfIndex as $oid => $value) {
2767 $prefix = current($ipAddressPrefix);
2768 next($ipAddressPrefix);
2770 $type = current($ipAddressType);
2771 next($ipAddressType);
2773 if(!preg_match('/.*\.(ipv[46]z?)\.\"(.*)"$/',$oid, $matches))
2776 /* ipv4 or ipv6 address */
2777 $ifindex = array_search($value,$this->ifTable
['ifIndex']);
2783 if(preg_match('/\."([\.0-9a-fA-F:%]+)"\.([0-9]+)$/',$prefix,$prefixmatches)) {
2784 $net = $prefixmatches[1];
2785 $maskbits = $prefixmatches[2];
2788 if($matches[1] == 'ipv4z' ||
$matches[1] == 'ipv4') {
2789 $intnetmask = (int)(0xffffffff << (32 - $maskbits));
2790 $intnet = ip2long($net) & $intnetmask;
2791 $intbcast = $intnet |
( $intnetmask ^
0xffffffff);
2793 $net = long2ip($intnet);
2794 $bcast = long2ip($intbcast);
2798 $this->ifTable
['ipaddress'][$ifindex][$matches[2]] = array(
2799 'addrtype' => $matches[1],
2800 'maskbits' => $maskbits,
2808 // sg_var_dump_html($ipAddressIfIndex);
2809 // sg_var_dump_html($ipAddressPrefix);
2810 } /* ipaddressifindex */
2814 function printifInfoTableHeader($suffix = "") {
2815 if($this->interfaceserror
) {
2820 foreach ($this->ifTable
as $key => $value) {
2823 case 'ifOperStatus':
2824 $displayvalue = 'if Oper Status';
2826 case 'ifConnectorPresent':
2827 $displayvalue = 'if Con Pres';
2834 $displayvalue = $key;
2837 if(!empty($displayvalue))
2838 echo "<th title=\"$key\">$displayvalue</th>";
2843 echo "$suffix</tr>";
2846 private $formfieldlist = array('ifName', 'ifDescr', 'ifAlias', 'ifPhysAddress');
2848 function printifInfoTableRow($ifIndex, $suffix = "", $hrefs = NULL) {
2849 if($this->interfaceserror
) {
2853 echo "<tr".($ifIndex %
2 ?
' style="background-color:#d8d8d8"' : '' ).">";
2855 foreach ($this->ifTable
as $key => $value) {
2857 if($key == 'ipaddress' ||
$key == 'ipaddressv6')
2862 /* minimize posted data to necessary fields */
2863 if(in_array($key,$this->formfieldlist
)) {
2865 /* $value would contain raw values; $this->{$key}($ifIndex) post processed values */
2866 $fieldvalue = $this->{$key}($ifIndex);
2868 if(!empty($fieldvalue)) {
2869 if($key == 'ifDescr' ||
$key == 'ifAlias') {
2870 $formfield = '<input readonly="readonly" type="text" size="15" name="'.$key.'['.$ifIndex.']" value="'
2871 .$this->$key($ifIndex).'">';
2874 $formfield = '<input type="hidden" name="'.$key.'['.$ifIndex.']" value="'.$fieldvalue.'">';
2878 if($key == 'ifName') {
2879 /* create textfield set to ifDescr */
2880 $formfield = '<input type="text" size="8" name="'.$key.'['.$ifIndex.']" value="'
2881 .$this->ifDescr($ifIndex).'">';
2891 $displayvalue=$formfield;
2893 $displayvalue = $this->{$key}($ifIndex);
2895 if(isset($hrefs) && isset($hrefs[$key])) {
2896 $displayvalue = "<a href=".$hrefs[$key].">$displayvalue</a>";
2900 echo "<td nowrap=\"nowrap\">$displayvalue</td>";
2905 echo "$suffix</tr>";
2908 function formatMACAddr($addr) {
2912 /* TODO test origin format */
2913 if(strlen($addr)== 6 ) {
2914 $retval = unpack('H12',$addr);
2915 $retval = $retval[1];
2918 /* often used as loopback on Enterasys switches */
2919 if($retval == '000000000000') {
2926 function ifPhysAddress($index) {
2928 if(isset($this->ifTable
['ifPhysAddress'][$index-1])) {
2929 return strtoupper($this->formatMACAddr($this->ifTable
['ifPhysAddress'][$index-1]));
2933 function ipaddress($index) {
2934 if(isset($this->ifTable
['ipaddress'][$index-1])) {
2935 return $this->ifTable
['ipaddress'][$index-1];
2940 function &__get($name) {
2945 return $this->{$name};
2948 return $this->ifTable
['ipaddress'];
2952 $trace = debug_backtrace();
2955 'Undefinierte Eigenschaft für __get(): ' . $name .
2956 ' in ' . $trace[0]['file'] .
2957 ' Zeile ' . $trace[0]['line'],
2963 /* $obj->ifDescr(3) = $ifTable[$name][$arg]*/
2964 function __call($name,$args) {
2966 if($this->interfaceserror
)
2969 if(isset($this->ifTable
[$name])) {
2970 if(isset($this->ifTable
[$name][$args[0]-1])) {
2971 return $this->ifTable
[$name][$args[0]-1];
2976 $trace = debug_backtrace();
2979 'Undefinierte Methode für __call(): ' . $name .
2980 ' in ' . $trace[0]['file'] .
2981 ' Zeile ' . $trace[0]['line'],
2991 private $IteratorIndex = 1;
2993 function current() {
2994 return $this->IteratorIndex
;
3001 $this->IteratorIndex++
;
3005 return ($this->IteratorIndex
<=$this->indexcount
);
3009 $this->IteratorIndex
= 1;
3015 /* ------------------------------------------------------- */
3016 /* ------------------------------------------------------- */
3018 function sg_var_dump_html(&$var, $text = '') {
3020 echo "<pre>------------------Start Var Dump - $text -----------------------\n";
3022 echo "\n---------------------END Var Dump - $text -----------------------</pre>";