예제 #1
0
 function MACtoIP($SearchMAC, $IP, $ReadCommunity)
 {
     $walk = snmprealwalk($IP, $ReadCommunity, ".1.3.6.1.2.1.3.1.1.2");
     if ($walk) {
         $i = 0;
         foreach ($walk as $entry) {
             $oid = array_keys($walk);
             $value = $entry;
             $oid = $oid[$i];
             if (stristr("atPhysAddress", $oid[0])) {
                 strtok($oid, "atPhysAddress");
                 $tmp = strtok("atPhysAddress");
                 $tmp = substr($tmp, 5);
             }
             $IP = $tmp;
             $MAC = $value;
             if ($MAC = $SearchMAC) {
                 break;
             } else {
                 unset($MAC);
                 unset($IP);
             }
             $i++;
         }
         return $IP;
     }
     // END if( $walk )
 }
예제 #2
0
function Walk($ip, $ver, $cm, $oid, $t = 1000000, $r = 2)
{
    global $debug, $comms;
    if ($ver == 3 and $comms[$cm]['pprot']) {
        if ($debug) {
            echo "<div class=\"textpad noti \">snmpwalk -v3 -c{$cm} " . $comms[$cm]['aprot'] . "/" . $comms[$cm]['pprot'] . " {$ip} {$oid} ({$t} usec * {$r})</div>";
        }
        return snmp3_real_walk($ip, $cm, 'authPriv', $comms[$cm]['aprot'], $comms[$cm]['apass'], $comms[$cm]['pprot'], $comms[$cm]['ppass'], ".{$oid}", $t);
    } elseif ($ver == 3 and $comms[$cm]['aprot']) {
        if ($debug) {
            echo "<div class=\"textpad noti \">snmpwalk -v3 -c{$cm} " . $comms[$cm]['aprot'] . " {$ip} {$oid} ({$t} usec * {$r})</div>";
        }
        return snmp3_real_walk($ip, $cm, 'authNoPriv', $comms[$cm]['aprot'], $comms[$cm]['apass'], 'DES', '', ".{$oid}", $t);
    } elseif ($ver == 2) {
        if ($debug) {
            echo "<div class=\"textpad noti \">snmpwalk -v2c -c{$cm} {$ip} {$oid} ({$t} usec * {$r})</div>";
        }
        return snmp2_real_walk($ip, $cm, ".{$oid}", $t);
    } else {
        if ($debug) {
            echo "<div class=\"textpad noti \">snmpwalk -v1 -c{$cm} {$ip} {$oid} ({$t} usec * {$r})</div>";
        }
        return snmprealwalk($ip, $cm, ".{$oid}", $t);
    }
}
예제 #3
0
파일: snmputils.php 프로젝트: engeld/snmphp
 function walk($oid)
 {
     // We're using realwalk so that we can build iterators with map_oids(), see:
     // walk     [0] => eth0
     // realwalk [IF-MIB::ifDescr.2] => eth0
     if ($this->version == "1") {
         $snmp_result = snmprealwalk($this->ip, $this->community, $oid);
     } else {
         if ($this->version == "2c") {
             $snmp_result = snmp2_real_walk($this->ip, $this->community, $oid);
         }
     }
     $result = $this->clear_snmp_string($snmp_result);
     return $result;
 }
예제 #4
0
 static function walk($host, $object_id, $cache_ttl = null)
 {
     if ($cache_ttl) {
         $cache_var = str_replace('.', '_', $host->ip . $object_id);
         $cache = new CacheAPC();
         $resultCache = $cache->load($cache_var);
         if ($resultCache !== null) {
             return $resultCache;
         }
     }
     snmp_set_oid_output_format(self::$oid_format);
     $snmp = $host->snmpTemplate;
     if ($snmp instanceof SnmpTemplate) {
         switch ($snmp->version) {
             case "1":
                 $result = @snmprealwalk($host->ip, $snmp->community, $object_id, $snmp->timeout, $snmp->retries);
                 break;
             case "2":
             case "2c":
                 $result = @snmp2_real_walk($host->ip, $snmp->community, $object_id, $snmp->timeout, $snmp->retries);
                 break;
             case "3":
                 $result = @snmp3_real_walk($host->ip, $snmp->security_name, $snmp->security_level, $snmp->auth_protocol, $snmp->auth_passphrase, $snmp->priv_protocol, $snmp->priv_passphrase, $object_id, $snmp->timeout, $snmp->retries);
                 break;
             default:
                 throw new Exception('SNMP Template not implemented yet');
         }
     }
     if (is_array($result)) {
         if ($cache_var && $cache_ttl) {
             $cache->save($cache_var, $result, $cache_ttl);
         }
         return $result;
     } else {
         //throw new Exception("Sem resposta SNMP");
         return array();
     }
 }
예제 #5
0
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>';
            }
        }
    }
}
예제 #6
0
                 $subject = $message;
                 ticket_post($smtp_email, $smtp_email, "28", "{$subject}", "{$message}", '1');
             }
         }
     }
 } else {
     if ("Memory Utilization" == $param_name) {
         //end of else if dsk utilization
         snmp_set_quick_print(1);
         $snmp_result = '';
         $memInfo = "hrStorageDescr";
         if (strtolower($snmp_version) == 'v3') {
             //SNMP V3 is used
             $snmp_result = @snmp3_real_walk($hostname, $v3_user, "authNoPriv", "MD5", $v3_pwd, "DES", "", $memInfo, $timeout, $count);
         } else {
             $snmp_result = @snmprealwalk($hostname, $community_string, $memInfo, $timeout, $count);
         }
         if (count($snmp_result) < 1) {
             echo "Unable to query server {$hostname} for Memory Utilization";
         }
         $mem_pct_used = 0;
         foreach ($snmp_result as $oid => $val) {
             if ("/" == substr($val, 0, 1)) {
                 //ignore
             } else {
                 $index = substr($oid, strrpos($oid, ".") + 1);
                 $used = '';
                 $total = '';
                 if (strtolower($snmp_version) == 'v3') {
                     //SNMP V3 is used
                     $used = @snmp3_get($hostname, $v3_user, "authNoPriv", "MD5", $v3_pwd, "DES", "", "hrStorageUsed.{$index}", $timeout, $count);
예제 #7
0
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, $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;
        }
    }
    /* determine default max_oids */
    if ($max_oids == 0 || !is_numeric($max_oids)) {
        $max_oids = read_config_option("max_get_size");
        if ($max_oids == "") {
            $max_oids = 10;
        }
    }
    /* 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(TRUE);
        }
        if (function_exists("snmprealwalk")) {
            $snmp_oid_included = false;
        }
        snmp_set_quick_print(0);
        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]" || $priv_pass == '') {
                $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 = 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]" || $priv_pass == '') {
                $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(preg_replace("/(.*) =.*/", "\\1", $temp_array[$i]));
                $snmp_array[$i]["value"] = format_snmp_string($temp_array[$i], true);
            }
        }
    }
    return $snmp_array;
}
예제 #8
0
파일: snmp.php 프로젝트: songchin/Cacti
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;
}
예제 #9
0
파일: snmp.php 프로젝트: songchin/Cacti
function cacti_snmp_walk($hostname, $community, $oid, $version, $v3username, $v3password, $v3authproto = "", $v3privpassphrase = "", $v3privproto = "", $port = 161, $timeout = 500, $environ = SNMP_POLLER) {
	require_once(CACTI_BASE_PATH . "/lib/sys/exec.php");

	$snmp_array = array();
	$temp_array = array();

	/* determine default retries */
	$retries = read_config_option("snmp_retries");
	if ($retries == "") $retries = 3;

	/* get rid of quotes in privacy passphrase */
	$v3privpassphrase = str_replace("#space#", " ", $v3privpassphrase);

	if ($v3privproto == "[None]") {
		$v3privproto = "";
	}

	$path_snmpbulkwalk = read_config_option("path_snmpbulkwalk");

	if ((snmp_get_method($version) == SNMP_METHOD_PHP) &&
		(($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 */
		snmp_set_quick_print(0);

		/* force php to return numeric oid's */
		if (function_exists("snmp_set_oid_numeric_print")) {
			snmp_set_oid_numeric_print(1);
		}

		if ($version == "1") {
			$temp_array = @snmprealwalk("$hostname:$port", $community, trim($oid), ($timeout * 1000), $retries);
		}elseif ($version == "2") {
			$temp_array = @snmp2_real_walk("$hostname:$port", $community, trim($oid), ($timeout * 1000), $retries);
		}else{
			$temp_array = @snmp3_real_walk("$hostname:$port", $v3username, snmp_get_v3authpriv($v3privproto), $v3authproto,
				$v3password, $v3privproto, $v3privpassphrase, trim($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 $v3username -A $v3password -a $v3authproto -X $v3privpassphrase -x $v3privproto -l " . snmp_get_v3authpriv($v3privproto); /* v3 - username/password/etc... */
		}

		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 {
			if (strlen(trim($path_snmpbulkwalk)) && ($version > 1)) {
				$temp_array = exec_into_array(read_config_option("path_snmpbulkwalk") . " -O QfntUe $snmp_auth -v $version -t $timeout -r $retries -Cr50 $hostname:$port $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")) ||
			(substr_count($temp_array[0], "No more variables"))) {
			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;
}
예제 #10
0
    } else {
        ?>
<th valign=bottom><img src=img/dl.png title="DB value"><br>In Octets</th>
<th valign=bottom><img src=img/ul.png title="DB value"><br>Out Octets</th>
<th valign=bottom><img src=img/xr.png title="DB value"><br>In Err</th>
<th valign=bottom><img src=img/xg.png title="DB value"><br>Out Err</th>
<?php 
    }
    ?>
<th valign=bottom><img src=img/netg.png title="DB value"><br>Address</th>
<?php 
    if ($uptime) {
        foreach (snmprealwalk("{$ip}", "{$comm}", ".1.3.6.1.2.1.2.2.1.8") as $ix => $val) {
            $ifost[substr(strrchr($ix, "."), 1)] = $val;
        }
        foreach (snmprealwalk("{$ip}", "{$comm}", ".1.3.6.1.2.1.2.2.1.9") as $ix => $val) {
            $iflac[substr(strrchr($ix, "."), 1)] = $val;
        }
    }
    $row = 0;
    foreach ($ifn as $i => $in) {
        if ($row == "1") {
            $row = "0";
            $off = 180;
        } else {
            $row = "1";
            $off = 195;
        }
        $bg3 = sprintf("%02x", $off);
        $rs = $gs = $bg3;
        $bg = $bg3 . $bg3 . $bg3;
예제 #11
0
    usage("Must set Host (-H)");
}
if (!isset($community)) {
    usage("Must set Community (-n)");
}
if (!isset($partition)) {
    usage("Must set partition (-p)");
}
if (!isset($warning)) {
    usage("Must set warning threshold (-w)");
}
if (!isset($critical)) {
    usage("Must set critical threshold (-c)");
}
snmp_set_quick_print(1);
$hrStorageDescr = @snmprealwalk($host, $community, "hrStorageDescr", SNMP_TIMEOUT, SNMP_RETRIES);
if (count($hrStorageDescr) == 1) {
    print "Unable to query server {$host}\n";
    exit(1);
}
foreach ($hrStorageDescr as $oid => $val) {
    if (ereg("^{$partition}\$", $val)) {
        $index = substr($oid, strrpos($oid, ".") + 1);
    }
}
if (!isset($index)) {
    print "{$partition} isn't mounted on {$host} | used=\n";
    exit(1);
}
$used = @snmpget($host, $community, "hrStorageUsed.{$index}", SNMP_TIMEOUT, SNMP_RETRIES);
$total = @snmpget($host, $community, "hrStorageSize.{$index}", SNMP_TIMEOUT, SNMP_RETRIES);
>
<th width=20%><img src=img/32/cam.png><br>Source</th>
<th width=20%><img src=img/32/nglb.png><br>Destination</th>
<th><img src=img/32/tap.png><br>Bit/s</th>
<th><img src=img/32/clock.png><br>Last Used</th>
<?php 
        error_reporting(1);
        snmp_set_quick_print(1);
        foreach (snmprealwalk("{$ip}", "{$comm}", ".1.3.6.1.4.1.9.10.2.1.1.2.1.12") as $ix => $val) {
            $prun[substr(strstr($ix, '9.10.2.1.1.2.1.'), 18)] = $val;
            // cut string at beginning with strstr first, because it depends on snmpwalk & Co being installed!
        }
        foreach (snmprealwalk("{$ip}", "{$comm}", ".1.3.6.1.4.1.9.10.2.1.1.2.1.19") as $ix => $val) {
            $bps[substr(strstr($ix, '9.10.2.1.1.2.1.'), 18)] = $val;
        }
        foreach (snmprealwalk("{$ip}", "{$comm}", ".1.3.6.1.4.1.9.10.2.1.1.2.1.23") as $ix => $val) {
            $last[substr(strstr($ix, '9.10.2.1.1.2.1.'), 18)] = $val;
        }
        $nmrout = 0;
        ksort($prun);
        $row = 0;
        foreach ($prun as $mr => $pr) {
            if ($row % 2) {
                $bg = $bga;
                $bi = $bia;
            } else {
                $bg = $bgb;
                $bi = $bib;
            }
            $row++;
            $i = explode(".", $mr);
예제 #13
0
 public function onuListAction()
 {
     // Check if id and blogpost exists.
     $id = (int) $this->params()->fromRoute('id', 0);
     if (!$id) {
         $this->flashMessenger()->addErrorMessage('Device id doesn\'t set');
         return $this->redirect()->toRoute('device');
     }
     $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
     $device = $objectManager->getRepository('\\Application\\Entity\\Device')->findOneBy(array('id' => $id));
     if (!$device) {
         $this->flashMessenger()->addErrorMessage(sprintf('Device with id %s doesn\'t exists', $id));
         return $this->redirect()->toRoute('device');
     }
     error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
     $Array_descr = snmprealwalk($device->getIp(), $device->getSnmpCommunity(), "ifDescr");
     if (count($Array_descr) > 0) {
         foreach ($Array_descr as $key => $type) {
             $key = str_replace("IF-MIB::ifDescr.", "", $key);
             $type = trim(str_replace("STRING: ", "", $type));
             $olt = strtok($type, ":");
             if (preg_match("#:#", $type)) {
                 $active = "";
                 try {
                     $opt_level_up = snmpget($device->getIp(), $device->getSnmpCommunity(), ".1.3.6.1.4.1.3320.101.10.5.1.5.{$key}");
                     $opt_level_up = trim(str_replace("INTEGER: ", "", $opt_level_up) / 10);
                 } catch (Exception $e) {
                 }
                 $mac_onu = snmpget($device->getIp(), $device->getSnmpCommunity(), ".1.3.6.1.4.1.3320.101.10.4.1.1.{$key}");
                 $mac_onu = str_replace(" ", ":", strtolower(trim(str_replace("Hex-STRING: ", "", $mac_onu))));
                 //$active = snmpget("$ip", $communit, "1.3.6.1.4.1.3320.101.10.1.1.26.$key");
                 //                    $active = str_replace(" ", ":", strtolower(trim(str_replace("INTEGER: ", "", $active))));
                 //$onu_vendor = snmpget("$ip", $communit, ".1.3.6.1.4.1.3320.101.10.1.1.1.$key");
                 //                    $onu_vendor = str_replace(" ", ":", strtolower(trim(str_replace("STRING: ", "", $onu_vendor))));
                 //$onu_model = snmpget("$ip", $communit, ".1.3.6.1.4.1.3320.101.10.1.1.2.$key");
                 //                    $onu_model = str_replace(" ", ":", strtolower(trim(str_replace("STRING: ", "", $onu_model))));
                 //$onu_distance = snmpget("$ip", $communit, ".1.3.6.1.4.1.3320.101.10.1.1.27.$key");
                 //                    $onu_distance = str_replace(" ", ":", strtolower(trim(str_replace("INTEGER: ", "", $onu_distance))));
                 $Array_ports = "";
                 $Array_ports_ = "";
                 $Array_ports__ = "";
                 //$Array_ports = snmprealwalk("$ip", $communit, "enterprises.3320.101.12.1.1.8.$key");
                 //print_r($Array_ports);
                 /*foreach($Array_ports as $key_ => $state)
                   {
                       $Array_state=explode(":", $state);
                       $state = trim($Array_state[1]);
                       if($state == 1 ){ $state="up"; }
                       if($state == 2 ){ $state="down"; }
                       $Array_ports__[]= $port." : ".$state;
                   }*/
                 /*if(count($Array_ports__)>0){
                       $Array_olt[$olt][$mac_onu]['ports'] = implode("<br>", $Array_ports__);
                   }*/
                 $Array_olt[$olt][$mac_onu]['type'] = $type;
                 $Array_olt[$olt][$mac_onu]['level_up'] = $opt_level_up;
                 $Array_olt[$olt][$mac_onu]['active'] = $active;
                 $arr0[] = ["key" => $key, "olt" => $olt, "port" => $type, "mac_onu" => $mac_onu, "rxp" => $opt_level_up, "active" => $active];
             }
         }
         ksort($Array_olt);
         foreach ($Array_olt as $key => $type) {
             $olt = $key;
             $n = 0;
             foreach ($type as $key1 => $type1) {
                 $mac_onu = $key1;
                 $level_up = $type1['level_up'];
                 $type = $type1['type'];
                 //  $active = $type1['active'];
                 // $ports = $type1['ports'];
                 $n++;
                 if ($olt != $old_olt && $n != 1) {
                     $m = 0;
                 }
                 $m++;
                 $old_olt = $olt;
             }
         }
     }
     // print_r($arr0);
     $view = new ViewModel(array('device' => $device->getArrayCopy(), 'obj' => $arr0));
     return $view;
 }
예제 #14
0
 /**
  * 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;
     }
 }
예제 #15
0
 /**
  * get available mibs for a device
  *
  * @param args json params converted into an array
  *             id contains an array of ids
  *             community snmp community string
  * @throws none
  * @return array containing result and possible error messages
  */
 public function ajax_getMIBS($args)
 {
     try {
         $data = array();
         $dev = $this->getDevice($args['id']);
         snmp_set_quick_print(true);
         $oids = snmprealwalk($dev->address, $args['community'], null);
         if ($oids === false) {
             return array('result' => 'failure', 'error' => 'SNMP Failure');
         } else {
             // load returned mibs
             foreach ($oids as $k => $v) {
                 $mib_txt = sprintf("%s%s (%s%s)", substr($k, 0, 25), strlen($k) > 25 ? "..." : "", substr($v, 0, 15), strlen($v) > 15 ? "..." : "");
                 $data[] = array('mib' => $k, 'mib_txt' => $mib_txt, 'value' => $v);
             }
         }
     } catch (Exception $e) {
         return array('result' => 'failure', 'error' => $e->getMessage());
     }
     return array('result' => 'success', 'data' => $data);
 }
예제 #16
0
파일: Snmp.php 프로젝트: sad-systems/cradle
 protected function snmpget($oid, $version = null, $community = null)
 {
     if (!$version) {
         $version = $this->getAgentVersion();
     }
     if (!$community) {
         $community = $this->getAgentReadCommunity();
     }
     switch ($version) {
         case 1:
             return @snmprealwalk($this->host, $community, $oid, $this->timeout * 1000000, $this->retries);
         case 2:
             return @snmp2_real_walk($this->host, $community, $oid, $this->timeout * 1000000, $this->retries);
         case 3:
             extract($this->version3);
             return @snmp3_real_walk($this->host, $secName, $secLevel, $authProtocol, $authPassphrase, $privProtocol, $privPassphrase, $oid, $this->timeout * 1000000, $this->retries);
         default:
             return false;
     }
 }
예제 #17
0
function DevRoutes($ip, $c)
{
    global $toumsg;
    #error_reporting(1);
    snmp_set_quick_print(1);
    foreach (snmprealwalk($ip, $c, ".1.3.6.1.2.1.4.21.1.2") as $oid => $val) {
        $i = explode('.', $oid);
        $route["{$i['1']}.{$i['2']}.{$i['3']}.{$i['4']}"]['ifx'] = $val;
    }
    if (!$oid) {
        echo $toumsg;
        die;
    }
    foreach (snmprealwalk($ip, $c, ".1.3.6.1.2.1.4.21.1.3") as $oid => $val) {
        $i = explode('.', $oid);
        $route["{$i['1']}.{$i['2']}.{$i['3']}.{$i['4']}"]['me1'] = $val;
    }
    foreach (snmprealwalk($ip, $c, ".1.3.6.1.2.1.4.21.1.7") as $oid => $val) {
        $i = explode('.', $oid);
        $route["{$i['1']}.{$i['2']}.{$i['3']}.{$i['4']}"]['nho'] = $val;
    }
    foreach (snmprealwalk($ip, $c, ".1.3.6.1.2.1.4.21.1.9") as $oid => $val) {
        $i = explode('.', $oid);
        $route["{$i['1']}.{$i['2']}.{$i['3']}.{$i['4']}"]['pro'] = $val;
    }
    foreach (snmprealwalk($ip, $c, ".1.3.6.1.2.1.4.21.1.10") as $oid => $val) {
        $i = explode('.', $oid);
        $route["{$i['1']}.{$i['2']}.{$i['3']}.{$i['4']}"]['age'] = $val;
    }
    foreach (snmprealwalk($ip, $c, ".1.3.6.1.2.1.4.21.1.11") as $oid => $val) {
        $i = explode('.', $oid);
        $route["{$i['1']}.{$i['2']}.{$i['3']}.{$i['4']}"]['msk'] = $val;
    }
    return $route;
}
2">
<th width=20%><img src="img/32/cam.png"><br>Source</th>
<th width=20%><img src="img/32/nglb.png"><br>Destination</th>
<th><img src="img/32/tap.png"><br>Bit/s</th>
<th><img src="img/32/clock.png"><br>Last Used</th>
<?
		error_reporting(1);
		snmp_set_quick_print(1);

		foreach (snmprealwalk($ip,$dev[15],'.1.3.6.1.4.1.9.10.2.1.1.2.1.12') as $ix => $val){
			$prun[substr(strstr($ix,'9.10.2.1.1.2.1.'),18)] = $val;					// cut string at beginning with strstr first, because it depends on snmpwalk & Co being installed!
		}
		foreach (snmprealwalk($ip,$dev[15],'.1.3.6.1.4.1.9.10.2.1.1.2.1.19') as $ix => $val){
			$bps[substr(strstr($ix,'9.10.2.1.1.2.1.'),18)] = $val;
		}
		foreach (snmprealwalk($ip,$dev[15],'.1.3.6.1.4.1.9.10.2.1.1.2.1.23') as $ix => $val){
			$last[substr(strstr($ix,'9.10.2.1.1.2.1.'),18)] = $val;
		}

		$nmrout = 0;

		ksort($prun);
		$row = 0;
		foreach($prun as $mr => $pr){
			if ($row % 2){$bg = "txta"; $bi = "imga";}else{$bg = "txtb"; $bi = "imgb";}
			$row++;
			$i		= explode(".", $mr);
			if($pr == 1){$primg = "bstp";}else{$primg = "brgt";}
			sscanf($last[$mr], "%d:%d:%0d:%0d.%d",$lud,$luh,$lum,$lus,$ticks);
			$bpsbar = Bar( intval($bps[$mr]/1000),0);
			$ip = "$i[4].$i[5].$i[6].$i[7]";
예제 #19
0
 function my_snmp_real_walk($ip, $credentials, $oid)
 {
     $timeout = '30000000';
     $retries = '0';
     switch ($credentials->credentials->version) {
         case '1':
             $array = @snmprealwalk($ip, $credentials->credentials->community, $oid, $timeout, $retries);
             break;
         case '2':
             $array = @snmp2_real_walk($ip, $credentials->credentials->community, $oid, $timeout, $retries);
             break;
         case '3':
             $sec_name = $credentials->credentials->security_name ?: '';
             $sec_level = $credentials->credentials->security_level ?: '';
             $auth_protocol = $credentials->credentials->authentication_protocol ?: '';
             $auth_passphrase = $credentials->credentials->authentication_passphrase ?: '';
             $priv_protocol = $credentials->credentials->privacy_protocol ?: '';
             $priv_passphrase = $credentials->credentials->privacy_passphrase ?: '';
             $array = @snmp3_real_walk($ip, $sec_name, $sec_level, $auth_protocol, $auth_passphrase, $priv_protocol, $priv_passphrase, $oid, $timeout, $retries);
             break;
         default:
             return false;
             break;
     }
     if (!is_array($array)) {
         return false;
     }
     foreach ($array as $i => $value) {
         $array[$i] = trim($array[$i]);
         if ($array[$i] == '""') {
             $array[$i] = '';
         }
         if (strpos($array[$i], '.') === 0) {
             $array[$i] = substr($array[$i], 1);
         }
         // remove the first and last characters if they are "
         if (substr($array[$i], 0, 1) == "\"") {
             $array[$i] = substr($array[$i], 1, strlen($array[$i]));
         }
         if (substr($array[$i], -1, 1) == "\"") {
             $array[$i] = substr($array[$i], 0, strlen($array[$i]) - 1);
         }
         // remove some return strings
         if (strpos(strtolower($array[$i]), '/etc/snmp') !== false or strpos(strtolower($array[$i]), 'no such instance') !== false or strpos(strtolower($array[$i]), 'no such object') !== false or strpos(strtolower($array[$i]), 'not set') !== false or strpos(strtolower($array[$i]), 'unknown value type') !== false) {
             $array[$i] = '';
         }
         // remove any quotation marks
         $array[$i] = str_replace('"', ' ', $array[$i]);
         // replace any line breaks with spaces
         $array[$i] = str_replace(array("\r", "\n"), " ", $array[$i]);
     }
     return $array;
 }
예제 #20
0
 /**
  * Proxy to the snmp2_real_walk command
  *
  * @param string $oid The OID to walk
  * @return array The results of the walk
  */
 public function realWalk($oid)
 {
     switch ($this->getVersion()) {
         case 1:
             return $this->_lastResult = @snmprealwalk($this->getHost(), $this->getCommunity(), $oid, $this->getTimeout(), $this->getRetry());
             break;
         case '2c':
             return $this->_lastResult = @snmp2_real_walk($this->getHost(), $this->getCommunity(), $oid, $this->getTimeout(), $this->getRetry());
             break;
         case '3':
             return $this->_lastResult = @snmp3_real_walk($this->getHost(), $this->getSecName(), $this->getSecLevel(), $this->getAuthProtocol(), $this->getAuthPassphrase(), $this->getPrivProtocol(), $this->getPrivPassphrase(), $oid, $this->getTimeout(), $this->getRetry());
             break;
         default:
             throw new Exception('Invalid SNMP version: ' . $this->getVersion());
     }
 }
예제 #21
0
파일: snmp.php 프로젝트: songchin/Cacti
function cacti_snmp_walk($hostname, $community, $oid, $version, $username, $password, $port = 161, $timeout = 500, $retries = 0, $environ = SNMP_POLLER) {
	global $config;

	$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;
	}

	$path_snmpbulkwalk = read_config_option("path_snmpbulkwalk");

	if ((snmp_get_method($version) == SNMP_METHOD_PHP) &&
		(($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(TRUE);
		}

		snmp_set_quick_print(0);

		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{
			$temp_array = @snmp3_real_walk("$hostname:$port", $username, "authNoPriv", "MD5", $password, "", "", $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 authNoPriv -a MD5 -A $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 {
			if (file_exists($path_snmpbulkwalk) && ($version > 1)) {
				$temp_array = exec_into_array($path_snmpbulkwalk . " -O n $snmp_auth -v $version -t $timeout -r $retries -Cr50 $hostname:$port $oid");
			}else{
				$temp_array = exec_into_array(read_config_option("path_snmpwalk") . " -O n $snmp_auth -v $version -t $timeout -r $retries $hostname:$port $oid");
			}
		}

		if ((sizeof($temp_array) == 0) ||
			(substr_count($temp_array[0], "No Such Object")) ||
			(substr_count($temp_array[0], "No more variables"))) {
			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;
}
예제 #22
0
 /**
  * Executes native SNMP walk interface
  * 
  * @param string $ip
  * @param string $community
  * @param string $oid
  * @param bool   $cache
  * @param bool   $nowait
  * @return string
  */
 protected function snmpWalkNative($ip, $community, $oid, $cache = true)
 {
     $cachetime = time() - $this->cacheTime;
     $cachepath = self::CACHE_PATH;
     $cacheFile = $cachepath . $ip . '_' . $oid;
     $result = '';
     //cache handling
     if (file_exists($cacheFile)) {
         //cache not expired
         if (filemtime($cacheFile) > $cachetime and $cache == true) {
             $result = file_get_contents($cacheFile);
         } else {
             //cache expired - refresh data
             snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
             @($raw = snmpwalkoid($ip, $community, $oid, $this->timeoutNative, $this->retriesNative));
             if (!empty($raw)) {
                 foreach ($raw as $oid => $value) {
                     $result .= $oid . ' = ' . $value . "\n";
                 }
             } else {
                 @($value = snmpget($ip, $community, $oid, $this->timeoutNative, $this->retriesNative));
                 $result = $oid . ' = ' . $value;
             }
             file_put_contents($cacheFile, $result);
         }
     } else {
         //no cached file exists
         snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
         @($raw = snmprealwalk($ip, $community, $oid, $this->timeoutNative, $this->retriesNative));
         if (!empty($raw)) {
             foreach ($raw as $oid => $value) {
                 $result .= $oid . ' = ' . $value . "\n";
             }
         } else {
             @($value = snmpget($ip, $community, $oid, $this->timeoutNative, $this->retriesNative));
             $result = $oid . ' = ' . $value;
         }
         file_put_contents($cacheFile, $result);
     }
     return $result;
 }
예제 #23
0
파일: snmp.php 프로젝트: songchin/Cacti
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, $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;
	}

	$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(TRUE);
			$snmp_oid_included = true;
		}

		snmp_set_quick_print(0);

		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);
		}

		/* 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 = (read_config_option("snmp_version") == "ucd-snmp") ? cacti_escapeshellarg($community): "-c " . cacti_escapeshellarg($community); /* v1/v2 - community string */
		}elseif ($version == "2") {
			$snmp_auth = (read_config_option("snmp_version") == "ucd-snmp") ? cacti_escapeshellarg($community): "-c " . cacti_escapeshellarg($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 = "******" . cacti_escapeshellarg($priv_pass) . " -x " . cacti_escapeshellarg($priv_proto);
			}else{
				$priv_pass = "";
			}

			if (strlen($context)) {
				$context = "-n " . cacti_escapeshellarg($context);
			}else{
				$context = "";
			}

			$snmp_auth = trim("-u " . cacti_escapeshellarg($username) .
				" -l " . cacti_escapeshellarg($proto) .
				" -a " . cacti_escapeshellarg($auth_proto) .
				" -A " . cacti_escapeshellarg($password) .
				" "    . $priv_pass .
				" "    . $context); /* 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 {
			if (file_exists($path_snmpbulkwalk) && ($version > 1) && ($max_oids > 1)) {
				$temp_array = exec_into_array($path_snmpbulkwalk . " -O Qn $snmp_auth -v $version -t $timeout -r $retries -Cr$max_oids $hostname:$port $oid");
			}else{
				$temp_array = exec_into_array(read_config_option("path_snmpwalk") . " -O Qn $snmp_auth -v $version -t $timeout -r $retries $hostname:$port $oid");
			}
		}

		/* 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;
}
예제 #24
0
 /**
  * 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;
     }
 }
예제 #25
0
 /**
  * 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;
     }
 }
//EXPECTF format is quickprint OFF
snmp_set_quick_print(false);
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
echo "Checking error handling\n";
var_dump(snmprealwalk($hostname, $community, '.1.3.6.1.2.1.1', ''));
var_dump(snmprealwalk($hostname, $community, '.1.3.6.1.2.1.1', $timeout, ''));
echo "Checking working\n";
echo "Single OID\n";
$return = snmprealwalk($hostname, $community, '.1.3.6.1.2.1.1', $timeout, $retries);
var_dump(gettype($return));
var_dump(sizeof($return));
var_dump(key($return));
var_dump(array_shift($return));
echo "Single OID in array\n";
$return = snmprealwalk($hostname, $community, array('.1.3.6.1.2.1.1'), $timeout, $retries);
var_dump(gettype($return));
var_dump(sizeof($return));
var_dump(key($return));
var_dump(array_shift($return));
echo "More error handling\n";
echo "Multiple correct OID\n";
$return = snmprealwalk($hostname, $community, array('.1.3.6.1.2.1.1', '.1.3.6'), $timeout, $retries);
var_dump($return);
echo "Multiple OID with wrong OID\n";
$return = snmprealwalk($hostname, $community, array('.1.3.6.1.2.1.1', '.1.3.6...1'), $timeout, $retries);
var_dump($return);
$return = snmprealwalk($hostname, $community, array('.1.3.6...1', '.1.3.6.1.2.1.1'), $timeout, $retries);
var_dump($return);
echo "Single nonexisting OID\n";
$return = snmprealwalk($hostname, $community, array('.1.3.6.99999.0.99999.111'), $timeout, $retries);
var_dump($return);
예제 #27
0
 function walk($oid, $suffix_as_key = FALSE)
 {
     switch ($this->version) {
         case self::VERSION_1:
             if ($suffix_as_key) {
                 $this->result = snmpwalk($this->host, $this->community, $oid);
             } else {
                 $this->result = snmprealwalk($this->host, $this->community, $oid);
             }
             break;
         case self::VERSION_2C:
         case self::VERSION_2c:
             if ($suffix_as_key) {
                 $this->result = snmp2_walk($this->host, $this->community, $oid);
             } else {
                 $this->result = snmp2_real_walk($this->host, $this->community, $oid);
             }
             break;
         case self::VERSION_3:
             if ($suffix_as_key) {
                 $this->result = snmp3_walk($this->host, $this->community, $this->sec_level, $this->auth_protocol, $this->auth_passphrase, $this->priv_protocol, $this->priv_passphrase, $oid);
             } else {
                 $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);
             }
             break;
     }
     return $this->result;
 }
예제 #28
0
 /**
  * {@inheritdoc}
  */
 public function getARPTable() : array
 {
     $time = new \DateTimeImmutable();
     $result = [];
     $snmpData = snmprealwalk($this->ip, $this->snmpCommunity, $this->snmpArpOid);
     foreach ($snmpData as $oid => $data) {
         preg_match('`((?:[a-f0-9]{1,2}:?){6})`', strtolower($data), $match);
         $macPart = [];
         foreach (explode(':', $match[1]) as $part) {
             if (!isset($part[1])) {
                 $part = '0' . $part;
             }
             $macPart[] = $part;
         }
         $ip = implode('.', array_slice(explode('.', $oid), -4));
         $mac = implode(':', $macPart);
         if (!isset($result[$mac])) {
             $result[$mac] = [];
         }
         $result[$mac][$ip] = ['ip' => $ip, 'port' => null, 'sysname' => null, 'time' => $time];
     }
     return $result;
 }
예제 #29
0
파일: snmp.php 프로젝트: Cacti/plugin_hmib
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;
}
예제 #30
0
function cacti_snmp_walk($hostname, $community, $oid, $version, $username, $password, $auth_proto, $priv_pass, $priv_proto, $port = 161, $timeout = 500, $retries = 0, $environ = SNMP_POLLER)
{
    global $config;
    $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;
        }
    }
    $path_snmpbulkwalk = read_config_option("path_snmpbulkwalk");
    if (snmp_get_method($version) == SNMP_METHOD_PHP && ($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(TRUE);
        }
        snmp_set_quick_print(0);
        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 ($auth_proto == "[None]") {
                $proto = "authNoPriv";
            } else {
                $proto = "authPriv";
            }
            $temp_array = @snmp3_real_walk("{$hostname}:{$port}", $username, $proto, $auth_proto, "{$password}", "{$priv_pass}", $priv_proto, "{$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") {
            if ($auth_proto == "[None]") {
                $proto = "authNoPriv";
            } else {
                $proto = "authPriv";
            }
            if (strlen($priv_pass)) {
                $priv_pass = "******"{$priv_pass}\" -x {$priv_proto}";
            } else {
                $priv_pass = "";
            }
            $snmp_auth = "-u {$username} -l {$proto} -a {$auth_proto} -A {$password} {$priv_pass}";
            /* 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 {
            if (file_exists($path_snmpbulkwalk) && $version > 1) {
                $temp_array = exec_into_array($path_snmpbulkwalk . " -O Qn {$snmp_auth} -v {$version} -t {$timeout} -r {$retries} -Cr50 {$hostname}:{$port} {$oid}");
            } else {
                $temp_array = exec_into_array(read_config_option("path_snmpwalk") . " -O Qn {$snmp_auth} -v {$version} -t {$timeout} -r {$retries} {$hostname}:{$port} {$oid}");
            }
        }
        if (sizeof($temp_array) == 0 || substr_count($temp_array[0], "No Such Object") || substr_count($temp_array[0], "No more variables") || substr_count($temp_array[0], "End of MIB") || substr_count($temp_array[0], "Wrong Type")) {
            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;
}