snmp 코드

14211 단어
package com.nufront.euht.web.common.snmp;



import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.Address;
import org.snmp4j.smi.Gauge32;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableListener;
import org.snmp4j.util.TableUtils;

import com.nufront.euht.util.StringUtil;
import com.nufront.euht.web.common.util.MyStringUtil;
import com.nufront.euht.web.deviceConfig.dataStruct.SnmpDataStruct;

/**
 * snmp  
 * */
public class ParentSnmp {
	private static Log log = LogFactory.getLog(ParentSnmp.class);
	public static final int DEFAULT_VERSION = SnmpConstants.version2c;
	public static final String DEFAULT_PROTOCOL = "udp";
	public static final int DEFAULT_PORT = 161;
	public static final long DEFAULT_TIMEOUT = 800L;   // ms
	public static final int DEFAULT_RETRY = 2;
	public static final String COMMUNITY_PUBLIC = "public";
	public static final String COMMUNITY_PRIVATE = "private";
	private static final String DEFINE_OID ="59418";
	private static final int  BULK_MAX_ROWS_NUMBER = 20; // BULK         
	private Snmp snmp;
	/**
	 *     communityTarget 
	 * 
	 *  targetAddress
	 * @param community
	 * @param version
	 * @param timeOut
	 * @param retry
	 * @return C@paramommunityTarget
	 */
	public static CommunityTarget createTargetDefault(String ip, String community) {
		if(StringUtil.isNullOrBlank(ip)){
			return null ;
		}
		Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
				+ "/" + DEFAULT_PORT);
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString(community));
		target.setAddress(address);
		target.setVersion(DEFAULT_VERSION);
		target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
		target.setRetries(DEFAULT_RETRY);
		address = null;
		return target;
	}
	
	public String snmpGetOne(String ip, String community, String oid){
		if(ip!=null&&community!=null&&oid!=null){
			//   CommunityTarget
			CommunityTarget target = this.createTargetDefault(ip, community);
			PDU pdu = null;
			DefaultUdpTransportMapping transport = null;
			//   snmp
			try {
				pdu = new PDU();
				pdu.add(new VariableBinding(new OID(oid)));
			    transport = new DefaultUdpTransportMapping();
				snmp = new Snmp(transport);
				snmp.listen();
				pdu.setType(PDU.GET);
				//  pdu
				ResponseEvent respEvent = snmp.send(pdu, target);
				log.debug("PeerAddress:" + respEvent.getPeerAddress());
				//      
				PDU response = respEvent.getResponse();
				if (response == null) { //  
					log.debug("response is null, request time out");
				} else {
					//    
					VariableBinding vb = response.get(0);
				    String value = vb.getVariable().toString();
				    vb = null;
					return 	value;
				}
				respEvent = null;
				response = null;
				log.debug("SNMP GET one OID value finished !");
			} catch (Exception e) {
				log.error("SNMP Get Exception:" + e);
				
			} finally {
				if (snmp != null) {
					try {
						snmp.close();
						snmp = null;
					} catch (IOException ex1) {
						snmp = null;
					}
				}
				try{
					if(pdu!=null){
						pdu = null;
					}
					if(transport!=null){
						transport.close();
						transport = null;
					}
					
				}catch(Exception e){
					pdu = null;
					transport = null;
					e.printStackTrace();
				}
				
			}
			target = null;
		
		}
		return null;
	}
	/**
	 *     communityTarget
	 * 
	 *  targetAddress
	 * @param community
	 * @param version
	 * @param timeOut
	 * @param retry
	 * @return C@paramommunityTarget
	 */
	public static CommunityTarget createDefault(String ip, String community) {
		if(StringUtil.isNullOrBlank(ip)){
			return null ;
		}
		Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
				+ "/" + DEFAULT_PORT);
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString(community));
		target.setAddress(address);
		target.setVersion(DEFAULT_VERSION);
		target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
		target.setRetries(DEFAULT_RETRY);
		return target;
	}
	/*      */
	public static Map<String,Object> snmpWalk(String ip, String community, String targetOid) {
		Map<String,Object> resultMap =  new HashMap<String,Object>();
		CommunityTarget target = createDefault(ip, community);
		TransportMapping transport = null;
		PDU pdu = null;
		Snmp snmp = null;
		try {
			transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			transport.listen();

			pdu = new PDU();
			OID targetOID = new OID(targetOid);
			pdu.add(new VariableBinding(targetOID));

			boolean finished = false;
			System.out.println("----> demo start <----");
			while (!finished) {
				VariableBinding vb = null;
				ResponseEvent respEvent = snmp.getNext(pdu, target);

				PDU response = respEvent.getResponse();

				if (null == response) {
					System.out.println("responsePDU == null");
					finished = true;
					break;
				} else {
					vb = response.get(0);
				}
				// check finish
				finished = checkWalkFinished(targetOID, pdu, vb);
				if (!finished) {
					System.out.println("==== walk each vlaue :");
					System.out.println(vb.getOid() + " = " + vb.getVariable());
					resultMap.put(vb.getOid().toString(), vb.getVariable());
					// Set up the variable binding for the next entry.
					pdu.setRequestID(new Integer32(0));
					pdu.set(0, vb);
				} else {
					System.out.println("SNMP walk OID has finished.");
					snmp.close();
				}
				respEvent =null;
				response = null;
				vb = null;
			}
			targetOID =null;
			System.out.println("----> demo end <----");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SNMP walk Exception: " + e);
		} finally {
			target = null;
			if (snmp != null) {
				try {
					snmp.close();
				} catch (IOException ex1) {
					snmp = null;
				}
			}
			try{
				if(pdu!=null){
					pdu = null;
				}
				if(transport!=null){
					transport.close();
					transport = null;
				}
				
			}catch(Exception e){
				pdu = null;
				transport = null;
				e.printStackTrace();
			}
		}
		return resultMap;
	}
	
	private static boolean checkWalkFinished(OID targetOID, PDU pdu,
			VariableBinding vb) {
		boolean finished = false;
		if (pdu.getErrorStatus() != 0) {
			System.out.println("[true] responsePDU.getErrorStatus() != 0 ");
			System.out.println(pdu.getErrorStatusText());
			finished = true;
		} else if (vb.getOid() == null) {
			System.out.println("[true] vb.getOid() == null");
			finished = true;
		} else if (vb.getOid().size() < targetOID.size()) {
			System.out.println("[true] vb.getOid().size() < targetOID.size()");
			finished = true;
		} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
			System.out.println("[true] targetOID.leftMostCompare() != 0");
			finished = true;
		} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
			System.out
					.println("[true] Null.isExceptionSyntax(vb.getVariable().getSyntax())");
			finished = true;
		} else if (vb.getOid().compareTo(targetOID) <= 0) {
			System.out.println("[true] Variable received is not "
					+ "lexicographic successor of requested " + "one:");
			System.out.println(vb.toString() + " <= " + targetOID);
			finished = true;
		}
		return finished;

	}
	
	public Map<String,Object> snmpGetAll(String ip, String community, String[] oidArray) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(ip!=null&&community!=null&&oidArray!=null){
			//   CommunityTarget
			CommunityTarget target = this.createTargetDefault(ip, community); 
			PDU pdu = null;
			DefaultUdpTransportMapping transport = null;

			//   snmp
			try {
				pdu = new PDU();
				for(int i = 0 ; i < oidArray.length ; i++){
					pdu.add(new VariableBinding(new OID(oidArray[i])));
				}
			    transport = new DefaultUdpTransportMapping();
				snmp = new Snmp(transport);
				snmp.listen();
				pdu.setType(PDU.GET);
				//  pdu
				ResponseEvent respEvent = snmp.send(pdu, target);
				log.debug("PeerAddress:" + respEvent.getPeerAddress());
				//      
				PDU response = respEvent.getResponse();
				if (response == null) { //  
					log.debug("response is null, request time out");
				} else {
					//    
//					VariableBinding vb = response.get(0);
					for(int i = 0 ; i < response.size() ; i ++){
						VariableBinding vb = response.get(i);
						String oid = vb.getOid().toString();
						String value = vb.getVariable().toString();
						map.put(oid, value);
						vb = null; 
					}
					
				}
				log.debug("SNMP GET one OID value finished !");
				respEvent = null;
				response = null;
			} catch (Exception e) {
				log.error("SNMP Get Exception:" + e);
				
			} finally {
				if (snmp != null) {
					try {
						snmp.close();
					} catch (IOException ex1) {
						snmp = null;
					}
				}
				try{
					if(pdu!=null){
						pdu = null;
					}
					if(transport!=null){
						transport.close();
						transport = null;
					}
					
				}catch(Exception e){
					pdu = null;
					transport = null;
					e.printStackTrace();
				}
			}
			//    
			target = null;
			pdu = null;
			transport = null;
		}
		return map;
    }

	 
	/**
	 *     
	 * type = 0   long
	 * type = 1   string
	 * */
	public static String setPDU(String ip, String community, String oid , Object value,int type)
			throws IOException {
		String snmpTipsInfo ="";
		if(!StringUtil.isNullOrBlank(ip)){
			CommunityTarget target = createTargetDefault(ip, community);
			Snmp snmp = null;
			PDU pdu = new PDU();
			if(type==0){
				pdu.add(new VariableBinding(new OID(oid), new Gauge32(Long.parseLong(value+""))));
			}else if(type==1){
				pdu.add(new VariableBinding(new OID(oid), new OctetString((String)value)));
			}
			
			pdu.setType(PDU.SET);

			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
			
			log.debug("-------> setPDU single <-------");
			ResponseEvent response =  snmp.send(pdu, target);
			PDU responsePDU = response.getResponse();
			
			if(responsePDU!=null){
				String errorText = responsePDU.getErrorStatusText();
				if(errorText.contains("Success")){
					snmpTipsInfo = "  ";
				}else{
					snmpTipsInfo = "ip  oid  ";
				}
			
			}else{
				snmpTipsInfo = "    ";
			}
			
			snmp.close();
		}
		return snmpTipsInfo;
	}
	
	/*      */
	public static void setPDU(String ip, String community, List<SnmpDataStruct> list)
			throws IOException {
		if(!StringUtil.isNullOrBlank(ip)){
			CommunityTarget target = createTargetDefault(ip, community);
			Snmp snmp = null;
			PDU pdu = new PDU();
			if(list!=null){
				SnmpDataStruct snmpDataStruct = null;
				for(int i = 0 ; i < list.size() ; i++){
					 snmpDataStruct = list.get(i);
					if(snmpDataStruct.getType()==0){
						if( Integer.parseInt(snmpDataStruct.getValue()+"")!=-1){
							pdu.add(new VariableBinding(new OID(snmpDataStruct.getOid()), new Gauge32(Long.parseLong(snmpDataStruct.getValue()+""))));	
						}
						
					}else if(snmpDataStruct.getType()== 1){
						if(snmpDataStruct.getValue()!=null&&!"".equals((snmpDataStruct.getValue()+"").replace(" ", "")))
						pdu.add(new VariableBinding(new OID(snmpDataStruct.getOid()), new OctetString(snmpDataStruct.getValue()+"")));
					}
				} 
			}
			
			pdu.setType(PDU.SET);
			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
			log.debug("-------> setPDU list <-------");
			snmp.send(pdu, target);
			snmp.close();
		}
	}
	
	/**
	 *     Oid,      
	 * @throws IOException 
	 * */
	public Map<String,String> Snmp4jTableUtils(String ip,String community,String tableOid,Snmp snmp) throws IOException{
		Map<String,String> map = new HashMap<String,String>();
		if( MyStringUtil.strIsNullOrBlank(ip) || MyStringUtil.strIsNullOrBlank(community) || MyStringUtil.strIsNullOrBlank(tableOid)  || snmp == null ){
			return map ;
		}
		OID[] columnOIDs = {
				new OID(tableOid)
		};
		CommunityTarget target = createDefaultSnmpTarget(ip,community);
		TableListener listener;
		snmp.listen();
		TableUtils utils = new TableUtils(snmp, new DefaultPDUFactory(PDU.GET));
		utils.setMaxNumRowsPerPDU(BULK_MAX_ROWS_NUMBER);   // max 20 rows each BULK request
		List<TableEvent> events = utils.getTable(target, columnOIDs, null, null);  //rows: all
		VariableBinding[] vbs = null;
		String oid = null;
		String value = null;
		for( TableEvent e :events ){
			vbs = e.getColumns();
			if(vbs!=null){
				oid = vbs[0].getOid().toString();
				value = vbs[0].getVariable().toString();
				if( oid.contains(DEFINE_OID)){
					map.put(oid, value);
				}
			}

		}
		return map;
	}
	
	private static CommunityTarget createDefaultSnmpTarget(String ip, String community) {
		
		Address address = GenericAddress.parse("udp:" + ip + "/" 
				+ SnmpConstants.DEFAULT_COMMAND_RESPONDER_PORT);
		
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString(community));
		target.setAddress(address);
		target.setVersion( SnmpConstants.version2c  );
		target.setTimeout(1000); 
		target.setRetries(3);
		return target;
	}

}

좋은 웹페이지 즐겨찾기