java snmp协议_snmp属于哪一层协议

java snmp协议_snmp属于哪一层协议背景控制华为交换机的poe供电与断电来重启PADsnmp协议使用importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;importjava.util.Vector;importlombok.extern.slf4j.Slf4j;importorg.snmp4j.CommunityTarget;importorg.snmp4j.PDU;importorg.snmp4j.Snmp;

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

背景

  • 控制华为交换机的poe供电与断电来重启PAD

snmp协议使用

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

/** * * @description 华为交换机工具类 */
@Slf4j
public class HuaWeiSwitchesSnmpConnection { 
   

  private static final String USERNAME = "tuantimingcheng";


  private static final int DEFAULT_VERSION = SnmpConstants.version2c;
  private static final String DEFAULT_PROTOCOL = "udp";
  private static final int DEFAULT_PORT = 161;
  private static final long DEFAULT_TIMEOUT = 3 * 1000L;
  private static final int DEFAULT_RETRY = 3;


  /** * 根据ip 和 团体名称创建 团体Target * @param ip * @param community * @return */
  private static CommunityTarget createTarget(String ip, String community) { 
   
    Address targetAddress = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip + "/" + DEFAULT_PORT);
    CommunityTarget target = new CommunityTarget(targetAddress, new OctetString(community));
    target.setVersion(DEFAULT_VERSION);
    target.setTimeout(DEFAULT_TIMEOUT);
    target.setRetries(DEFAULT_RETRY);
    return target;
  }

  /** * 获取对应ip下交换机oid的状态 * * @param ip * @param oid * @return */
  public static int getStatus(String ip, String oid) { 
   
    int status = 0;
    CommunityTarget target = createTarget(ip, USERNAME);
    PDU pdu = new PDU();
    pdu.add(new VariableBinding(new OID(oid)));
    pdu.setType(PDU.GET);
    try { 
   
      Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
      snmp.listen();
      ResponseEvent respEvent = snmp.send(pdu, target);
      if (respEvent != null && respEvent.getResponse() != null) { 
   
        status = respEvent.getResponse().get(0).getVariable().toInt();
      } else { 
   
        // TODO 此处异常状态,需要log
        log.error(
            "SNMP getStatus request time out, Response is null. [ip = " + ip + ", community = "
                + SnmpDevice.PDU_READ_USER + "]");
      }
      snmp.close();
    } catch (IOException e) { 
   
      e.printStackTrace();
      // TODO 此处异常状态,需要log[exception];
      log.error("SNMP getStatus Exception:" + e);
    }
    return status;
  }

  /* 查询ip下oid对应的端口集合 */
  public static List<String> getOidAndPortList(String ip, String oid) { 
   
    CommunityTarget target = createTarget(ip, USERNAME);
    PDU pdu = new PDU();
    List<String> oidAndVariableList = new ArrayList<>();
    String currentOid = oid;
    Vector<VariableBinding> recVBs;
    try { 
   
      Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
      snmp.listen();
      while (true) { 
   
        pdu.add(new VariableBinding(new OID(currentOid)));
        pdu.setType(PDU.GETNEXT);
        ResponseEvent respEvent = snmp.send(pdu, target);
        if (respEvent != null && respEvent.getResponse() != null) { 
   
          recVBs = (Vector<VariableBinding>) respEvent.getResponse()
              .getVariableBindings();
          VariableBinding variableBinding = recVBs.get(recVBs.size() - 1);
          currentOid = variableBinding.getOid().toString();

          if (!oid.equals(currentOid
              .substring(0, currentOid.lastIndexOf(".")))) { 
   
            break;
          }
        }
      }
      for (int i = 0; i < recVBs.size(); i++) { 
   
        if (i != recVBs.size() - 1) { 
   
          oidAndVariableList.add(recVBs.get(i).getOid() + "," + recVBs.get(i).getVariable());
        }
      }
      snmp.close();
    } catch (IOException e) { 
   
      e.printStackTrace();
      // TODO 此处异常状态,需要log[exception];
      log.error("SNMP getStatus Exception:" + e);
    }
    return oidAndVariableList;
  }

  /** * 发送命令方法 * * @param ip  交换机ip * @param oid  发送命令的oid * @param command  命令参数 * @return */
  public static int setCommand(String ip, String oid, Integer command) { 
   
    int status = 0;
    CommunityTarget target = createTarget(ip, USERNAME);
    PDU pdu = new PDU();
    pdu.add(new VariableBinding(new OID(oid), new Integer32(command)));
    pdu.setType(PDU.SET);
    try { 
   
      Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
      snmp.listen();
      ResponseEvent respEvent = snmp.send(pdu, target);
      if (respEvent != null && respEvent.getResponse() != null) { 
   
        int result = respEvent.getResponse().get(0).getVariable().toInt();
        if (result == command) { 
   
          // 命令执行成功!
          status = 1;
        }
      } else { 
   
        // TODO 此处异常状态,需要log
        System.out.println(
            "SNMP sent command request time out, Response is null. [ip = " + ip + ", community = "
                + SnmpDevice.PDU_WRITE_USER + "]");
      }
      snmp.close();
    } catch (IOException e) { 
   
      e.printStackTrace();
      // TODO 此处异常状态,需要log[exception];
      System.out.println("SNMP sent command Get Exception:" + e);
    }
    return status;
  }

  private static final String HUA_WEI_OID = "1.3.6.1.4.1.2011.5.25.195.3.1.6";

  private static final String HUA_WEI_OID_SWITCH = "1.3.6.1.4.1.2011.5.25.195.3.1.15.23";

  /* 切换管理方式 */
  private static final String HUA_WEI_MANAGEMENT = "1.3.6.1.4.1.2011.5.25.195.2.1.8.0";

  public static void main(String[] args) { 
   
    String ip = "192.168.0.196";

    //切换管理方式 1.手动管理  2.自动管理
    HuaWeiSwitchesSnmpConnection.setCommand(ip, HUA_WEI_MANAGEMENT, 1);

    //控制开关 1.关机  2.开机

    HuaWeiSwitchesSnmpConnection.setCommand(ip, HUA_WEI_OID_SWITCH, 1);

    try { 
   
      Thread.sleep(4000);
    } catch (InterruptedException e) { 
   
      e.printStackTrace();
    }

    HuaWeiSwitchesSnmpConnection.setCommand(ip, HUA_WEI_OID_SWITCH, 2);

    //获取Oid和port
    /*List<String> status = HuaWeiSwitchesSnmpConnection.getOidAndPortList(ip, HUA_WEI_OID_SWITCH); for (String message : status) { System.out.println(message); }*/
    int status1 = HuaWeiSwitchesSnmpConnection.getStatus(ip, HUA_WEI_OID_SWITCH);
    System.out.println(status1);
  }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/181280.html原文链接:https://javaforall.net

(0)
上一篇 2022年10月16日 下午6:00
下一篇 2022年10月16日 下午6:00


相关推荐

  • React多页面跳转[通俗易懂]

    React多页面跳转[通俗易懂]render(){const{app:{locationQuery}}=this.props;////////////tolist.jsconst{子页面数据}=this.state;const{id}=locationQuery;///获取当前页面地址栏的idconstinfo=queryA…

    2022年5月30日
    37
  • HTML渐变背景不重复,CSS背景渐变重复问题

    HTML渐变背景不重复,CSS背景渐变重复问题littlecharva 我有需要扩大宽度和高度的 HTML 页面 所以需要能够上下滚动和左右 但我似乎无法得到的 CSS 梯度重复 X 和向下留下了坚实的颜色 剥离代码 p gt http www w3 org TR html4 loose dtd gt html height 100 background color 366fcd body margin 0 h

    2026年3月18日
    1
  • 智谱 AI 发布开源 GLM 模型家族:MIT 许可、Z.ai 平台与高速推理服务同步亮相

    智谱 AI 发布开源 GLM 模型家族:MIT 许可、Z.ai 平台与高速推理服务同步亮相

    2026年3月12日
    3
  • mysql批量写入数据存储过程_mysql批量保存多大数据

    mysql批量写入数据存储过程_mysql批量保存多大数据一、以下共统计了3种批量插入的方法:1、普通方法:一条一条插入;2、使用拼接语句一次性插入,拼接语句的语法如下:insertintotable(col1,col2,col3)values(’a’,’b‘,’c‘),(’a1’,’b1‘,’c1‘),(’a2‘,’b2‘,’c2′),……对于拼接语句sql有一个长度限制:max_allowed_packet,查看限制最大值:showvariableslike‘%max_allowed_packet%’,使用Navic

    2022年10月6日
    4
  • 遍历ArrayList时如何正确移除一个元素「建议收藏」

    遍历ArrayList时如何正确移除一个元素「建议收藏」一个ArrayList对象aList中存有若干个字符串元素,现欲遍历该ArrayList对象,删除其中所有值为”abc”的字符串元素,请用代码实现。方法一、for循环遍历很简单,直接上代码:importjava.util.*;publicclassTest1{ publicstaticvoidmain(Stringargs[]){ List<String…

    2022年7月22日
    27
  • SQL聚合函数「建议收藏」

    SQL聚合函数「建议收藏」一、知识点聚合函数对组执行计算并返回每个组唯一的值。GROUPBY子句通常与聚合函数一起用于统计数据。GROUPBY子句将行排列成组,聚合函数返回每个组的统计量。常用的聚合函数有:COUNT(),SUM(),AVG(),MIN(),MAX()。COUNT(),其作用主要是返回每个组的行数,也会返回有NULL值的列,可用于数字和字符列。SUM(),主要用于返回表达式中所有的总和,忽略NULL值,仅用于数字列。AVG(),返回表达式所有的平均值,仅用于数字列并且自动忽略NULL值。MIN(),返

    2022年6月21日
    24

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号