使用snmp测试与网络设备的连接

时间:2013-12-11 16:26:36

标签: php snmp

我有这个代码来检索复制机器的一些反值。

    foreach($sett as $key => $value){
    if (intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])))) {
        $c = intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])));
        $error = false;
    }
    else {
        $c = 0;
        $error = true;
    }
    $counters = array_push_assoc($counters,ucwords($key),array("total" => $c, "code" => $value["code"]));
}

一切都像魅力一样,但唯一的问题是当机器出现问题时,代码无法生成SNMPGET,整个脚本都会失败。

首先,我想检查与设备的连接是否处于活动状态,然后使用SNMPGET检索计数器

你们可以为我提供任何解决方案吗?

THX

1 个答案:

答案 0 :(得分:0)

如果snmpget()函数无法检索对象,则返回FALSE。

请参阅文档:http://www.php.net/manual/en/function.snmpget.php

您应该在代码中对此进行检查,例如:

try
{
    foreach($sett as $key => $value){

    $sntpReturn = snmpget($ip, "public", $base.$value["MIB"]);

    if ($sntpReturn === false)
    {
        // Do something to handle failed SNTP request.
        throw new Exception("Failed to execute the SNTP request to the machine.");
    }
    else
    {

    if (intval(str_replace("INTEGER: ","", $sntpReturn))) {
        $c = intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])));
        $error = false;
    }
    else {
        $c = 0;
        $error = true;
    }
    $counters = array_push_assoc($counters,ucwords($key),array("total" => $c, "code" => $value["code"]));

    }
}
catch (Exception $e)
{
    // Handle the exception, maybe kill the script because it failed?
}