简单实现SNMP获取系统信息以及网络接口信息

SNMP又称简单网络管理协议,由一组网络管理的标准组成,该协议能够支持网络管理系统,用以监测连接到网络上的设备是否有任何引起管理上关注的情况。简而言之,SNMP就是为不同种类、不同厂家生产、不同型号的设备,定义为一个统一的接口和协议,使得管理员可以是使用统一的方法来管理这些设备。

通过发送Oid(对象标示符,在现有的标识不能满足需要时,可以自定义oid)来获得我们想要的设备信息回应,以下是一些等下会出现的oid (=.=)

这里写图片描述
这里写图片描述

可知以上的oid请求方式有两种,分别是GET和WALK:

  • get则是取具体的oid的值。
  • snmpwalk是对oid值的遍历,依次遍历出这N个节点的值

代码

// 将用到的oid放在这个类中
public class Constants {
    public static final String sysDescr = ".1.3.6.1.2.1.1.1.0";
    public static final String sysName = ".1.3.6.1.2.1.1.5.0";
    public static final String sysObjectID = ".1.3.6.1.2.1.1.2.0";
    public static final String ifNumber = ".1.3.6.1.2.1.2.1.0";

    public static final String[] ifOids=new String[]{
        ".1.3.6.1.2.1.2.2.1.1",
        ".1.3.6.1.2.1.2.2.1.2",
        ".1.3.6.1.2.1.2.2.1.3",
        ".1.3.6.1.2.1.2.2.1.4",
        ".1.3.6.1.2.1.2.2.1.5",
        ".1.3.6.1.2.1.2.2.1.6",
        ".1.3.6.1.2.1.2.2.1.7",
        ".1.3.6.1.2.1.2.2.1.8",
        ".1.3.6.1.2.1.2.2.1.9",
        ".1.3.6.1.2.1.2.2.1.10",
        ".1.3.6.1.2.1.2.2.1.11",
        ".1.3.6.1.2.1.2.2.1.12",
        ".1.3.6.1.2.1.2.2.1.13",
        ".1.3.6.1.2.1.2.2.1.14",
        ".1.3.6.1.2.1.2.2.1.15",
        ".1.3.6.1.2.1.2.2.1.16",
        ".1.3.6.1.2.1.2.2.1.17",
        ".1.3.6.1.2.1.2.2.1.18",
        ".1.3.6.1.2.1.2.2.1.19",
        ".1.3.6.1.2.1.2.2.1.20",
        ".1.3.6.1.2.1.2.2.1.21",
        ".1.3.6.1.2.1.2.2.1.22"
    }
}

import bean.Constants;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

import java.io.IOException;
import java.util.*;

public class SNMPSessionUtil {
    private  Snmp snmp;
    private Address targetAddress;
    private String hostComputer;
    private String port;
    private String community;
    private int version;
    private  CommunityTarget communityTarget;

    public SNMPSessionUtil(String hostComputer,String port ,String community, String version) {
        this.hostComputer = hostComputer;
        this.community = community;
        this.port=port;
        if (version.equals("2")){
            this.version=SnmpConstants.version2c;
        }else {
            System.out.println("版本不对");
        }
        init();
    }
// 初始化 
    public void init(){
        String target="udp:"+hostComputer+"/"+port;
        targetAddress= GenericAddress.parse(target);
        try {
            TransportMapping transportMapping=new DefaultUdpTransportMapping();
            snmp=new Snmp(transportMapping);
            snmp.listen();
            // 设置权限
            communityTarget=new CommunityTarget();
            communityTarget.setCommunity(new OctetString(community));
            communityTarget.setAddress(targetAddress);
            // 通信不成功重复次数
            communityTarget.setRetries(2);
            // 超时时间
            communityTarget.setTimeout(2*1000);
            // 设置版本
            communityTarget.setVersion(version);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
// 单个获取方式
    public void getSnmpGet(String... oid) throws IOException {
        ResponseEvent responseEvent=null;
        for (int i=0;i<oid.length;i++){
            PDU pdu=new PDU();
            pdu.add(new VariableBinding(new OID(oid[i])));
            // 设置请求方式
            pdu.setType(PDU.GET);
            ResponseEvent event=snmp.send(pdu,communityTarget);
            if (null!=event){
                readResponse(event);
            }
        }

    }
// 对结果进行解析
    public void readResponse(ResponseEvent event){
        if (null!=event&&event.getResponse()!=null){
            System.out.println("收到回复,正在解析");
            Vector<VariableBinding>vector=event.getResponse().getVariableBindings();
            for (int i=0;i<vector.size();i++){
                VariableBinding vec= vector.elementAt(i);
                System.out.println(vec);
            }
        }else
            System.out.println("没有收到回复");
    }
// 遍历请求
    public void snmpWalk2(String oids[]){
        mapList=new ArrayList<>();
        // 设置TableUtil的工具
        TableUtils utils=new TableUtils(snmp,new DefaultPDUFactory(PDU.GETBULK));
        utils.setMaxNumRowsPerPDU(2);
        OID[] clounmOid =new OID[oids.length];
        for (int i=0;i<oids.length;i++){
            clounmOid[i]=new OID(oids[i]);
        }
        // 获取查询结果list,new OID("0"),new OID("40")设置输出的端口数量
        List<TableEvent> list=utils.getTable(communityTarget,clounmOid,new OID("0"),new OID("40"));
        for (int i = 0; i < list.size(); i++) {
            // 取list中的一行
            TableEvent te = (TableEvent) list.get(i);
            // 对每一行结果进行再次拆分
            VariableBinding[] vb = te.getColumns();
            map  = new HashMap<String,String>();
            if (vb != null) {
                for (int j = 0; j < vb.length; j++) {
                    System.out.println(vb[j].toString());
                }
            } else {
                throw new NullPointerException("被监控系统的网络不通或IP或其它相关配置错识!");
            }
        }
    }
    public static void main(String[] args) {
        SNMPSessionUtil snmpSessionUtil=new SNMPSessionUtil("192.168.1.104","161","public", "2");

       try {
     snmpSessionUtil.getSnmpGet(Constants.sysDescr,Constants.sysName,Constants.sysObjectID,Constants.ifNumber);
           snmpSessionUtil.snmpWalk2(Constants.ifOids);
       } catch (IOException e) {
            e.printStackTrace();
       }
    }
}

这里写图片描述

  • 11
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SNMP简单网络管理协议)是一种用于管理和监控网络设备的协议。Python提供了一些库和模块来实现SNMP管理器。 首先,我们可以使用Python的PySNMP库来进行SNMP操作。这个库提供了一套简单而强大的API,用于发送SNMP请求和接收SNMP响应。 要实现一个SNMP管理器,我们需要做以下几个步骤: 1. 导入必要的库和模块: ```python from pysnmp.hlapi import * ``` 2. 设置SNMP代理的IP地址、端口和团体字符串(community string): ```python ip_address = '127.0.0.1' port = 161 community_string = 'public' ``` 3. 构建SNMP请求: ```python # 查询系统描述 snmp_object = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) snmp_request = getCmd(SnmpEngine(), CommunityData(community_string), UdpTransportTarget((ip_address, port)), ContextData(), snmp_object) ``` 4. 发送SNMP请求并接收响应: ```python snmp_response = next(snmp_request) error_indication, error_status, error_index, var_binds = snmp_response ``` 5. 处理和解析响应数据: ```python if error_indication: print('SNMP请求发送错误:{}'.format(error_indication)) elif error_status: print('SNMP错误状态:{} at {}'.format(error_status.prettyPrint(), var_binds[int(error_index) - 1] if error_index else '?')) else: for var_bind in var_binds: print('SNMP对象:{} = {}'.format(var_bind.prettyPrint(), var_bind)) ``` 通过以上步骤,我们就可以实现一个简单SNMP管理器。可以根据需要,扩展和定制SNMP请求,以获取不同的系统信息和监控网络设备。 总之,Python提供了丰富的库和模块来实现SNMP管理器。通过使用PySNMP库,我们可以编写简洁而功能强大的代码来管理和监控网络设备。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值