CommSnmpGet.java 6.54 KB
package com.sitech.ismp.snmp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;

public class CommSnmpGet {

	private static final int RETRIES = 2;

	private static final int TIME_OUT = 20000;

	private Logger logger = Logger.getLogger("COLL");

	String ip_s = "";

	int port_s = 0;

	String community_s = "public";

	org.snmp4j.Snmp mSnmp = null;

	CommunityTarget mCommunityTarget = null;

	String rootOid = "";

	HashMap walkHashMap;

	public HashMap getWalkHashMap() {
		return walkHashMap;
	}

	public String getRootOid() {
		return rootOid;
	}

	public void setRootOid(String rootOid) {
		this.rootOid = rootOid;
	}

	/**
	 * 实例化类
	 * 
	 * @param ip
	 *            采集IP地址
	 * @param port
	 *            采集端口
	 */
	public CommSnmpGet(String ip, int port, String community) {
		ip_s = ip;
		port_s = port;
		community_s = community;
		walkHashMap = new HashMap();
	}

	/**
	 * 初始化SNMP
	 * 
	 */
	public void init() {
		try {
			String addr = "udp:" + ip_s + "/" + String.valueOf(port_s);
			OctetString community = new OctetString(community_s);
			Address address = GenericAddress.parse(addr);
			mCommunityTarget = new CommunityTarget(address, community);
			org.snmp4j.TransportMapping vTransport = new org.snmp4j.transport.DefaultUdpTransportMapping();
			mSnmp = new org.snmp4j.Snmp(vTransport);
			vTransport.listen();
			mCommunityTarget.setCommunity(community);
			mCommunityTarget.setAddress(new UdpAddress(java.net.InetAddress
					.getByName(ip_s), port_s));
			mCommunityTarget.setRetries(RETRIES);
			mCommunityTarget.setTimeout(TIME_OUT);
			// mCommunityTarget.setMaxSizeRequestPDU(500);
			mCommunityTarget.setVersion(org.snmp4j.mp.SnmpConstants.version2c);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void workTable(String curr_oid) throws IOException {
		if (curr_oid.startsWith(rootOid)) {
			PDU pdu_result = this.getNext(curr_oid);
			if (pdu_result == null) {
				return;
			}
			VariableBinding vb = pdu_result.get(0);
			Variable vars = vb.getVariable();
			OID oid = vb.getOid();

			String nextVars = vars.toString();
			String nextOid = oid.toString();
			if (nextOid.startsWith(rootOid)) {
				walkHashMap.put(nextOid, nextVars);
				System.out.println(nextOid + "=" + nextVars);
			}
			workTable(nextOid);
		}
	}

	/**
	 * SNMP是否有应答
	 * 
	 * @return
	 */
	public boolean isAdoptable() {
		boolean result = false;
		String oid = "1.3.6.1.2.1.1.1.0";
		PDU pdu = null;
		try {
			pdu = this.getPdu(oid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (pdu != null) {
			result = true;
		}
		return result;
	}

	public boolean isSwitch() {
		boolean result = false;
		String oid = "1.3.6.1.2.1.17.4.3.1.1";
		PDU pdu = null;
		try {
			pdu = this.getNext(oid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return result;
		}
		if (pdu != null) {
			VariableBinding vb = pdu.get(0);
			String s_oid = vb.getOid().toString();
			if (s_oid.startsWith(oid)) {
				result = true;
			}
		}
		return result;
	}

	public void workTable(String rootOid, String curr_oid) throws IOException {
		if (curr_oid.startsWith(rootOid)) {
			PDU pdu_result = this.getNext(curr_oid);

			VariableBinding vb = pdu_result.get(0);
			Variable vars = vb.getVariable();
			OID oid = vb.getOid();

			String nextVars = vars.toString();
			String nextOid = oid.toString();
			System.out.println("[" + nextOid + "] = " + nextVars);
			workTable(rootOid, nextOid);
		}
	}

	public Vector getPDU(Vector oidVector) throws Exception {
		PDU pdu = new PDU();
		for (int i = 0; i < oidVector.size(); i++) {
			// System.out.println("oid: " + (String)oidVector.get(i));
			VariableBinding var = new VariableBinding(new OID(
					(String) oidVector.get(i)),
					new org.snmp4j.smi.OctetString());
			pdu.add(var);
		}
		pdu.setType(PDU.GET);
		ResponseEvent res = mSnmp.send(pdu, mCommunityTarget);
		if (res.getResponse() == null) {
			System.out.println("[can not connect ip address: " + ip_s + "]");
		}
		return res.getResponse().getVariableBindings();
	}

	public PDU getPdu(String oid) throws Exception {
		PDU pdu = new PDU();
		VariableBinding var = new VariableBinding(new OID(oid),
				new org.snmp4j.smi.OctetString());
		pdu.add(var);

		pdu.setType(PDU.GET);
		ResponseEvent res = mSnmp.send(pdu, mCommunityTarget);
		if (res.getResponse() == null) {
			logger.error("[can not connect ip address: " + ip_s + "]");
		}
		return res.getResponse();
	}

	/**
	 * 得到提供oid的下一个PDU
	 * 
	 * @param oid
	 * @return PDU 协议数据单元
	 * @throws IOException
	 */
	public PDU getNext(String oid) throws IOException {
		PDU pdu = new PDU();
		VariableBinding var = new VariableBinding(new OID(oid),
				new org.snmp4j.smi.OctetString());
		pdu.add(var);
		pdu.setType(PDU.GETNEXT);
		ResponseEvent res = mSnmp.send(pdu, mCommunityTarget);
		if (res.getResponse() == null) {
			logger.error("[can not connect ip address: " + ip_s + "]");
		}
		return res.getResponse();
	}

	/**
	 * 断开SNMP连接
	 * 
	 */
	public void release() {
		try {
			mSnmp.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		mSnmp = null;
	}

	public static void main(String args[]) throws Exception {
		String ip = "";
		String port = "";
		String community = "";
		String oid = "1.3.6.1.2.1.1.1.0";

		if (args.length < 3) {
			System.out
					.println("Please Input Params <IpAddress> <Port> <Community> Or <IpAddress> <Port> <Community> <Oid>");
			System.exit(0);
		}

		if (args.length > 3) {
			if (args[3] != null && !(args[3].equals(""))) {
				oid = args[3];
			}
		}
		ip = args[0];
		port = args[1];
		community = args[2];
		int int_port = Integer.parseInt(port);

		CommSnmpGet snmpGet = new CommSnmpGet(ip, int_port, community);
		snmpGet.init();
		PDU pdu = snmpGet.getPdu(oid);
		if (pdu == null) {
			System.out.println("[Ip: " + ip + " can not connect ...]");
		} else {
			VariableBinding vb = pdu.get(0);
			String s_oid = vb.getOid().toString();
			String s_var = vb.getVariable().toString();
			System.out.println("[---Collection Ip: " + ip + " Information---]");
			System.out.println("[---" + s_oid + " = " + s_var + "---]");
			System.out.println("[---Collection Success !---]");
		}
		snmpGet.release();

	}
}