SNMPTarget.java 12 KB
package com.sitech.ismp.coll;

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

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.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import com.adventnet.snmp.beans.SnmpTarget;
import com.adventnet.snmp.snmp2.SnmpOID;

/**
 * ͨ��SNMP����ij��IP��ַ����SNMP����
 */
public class SNMPTarget extends CollBase {
	
	SnmpTarget target = null;
	public String ObjectIP = null;
	private int PORT = 161;
	private String VERSION = "2";
	private String COMMUNITY = "public";
	private int RETRIES = 3;
	private int TIMEOUT = 4;
	private String MIBS = "5";
	private String USER_NAME = "";
	private String AUTH_PROTOCOL = new String("NO_AUTH");
	private String AUTH_PASSWORD = "";
	private String PRIV_PASSWORD = "";
	private String CONTEXT_NAME = "";
	private String CONTEXT_ID = "";
	// public Vector KPISet = new Vector();
	private boolean DEBUG = false;

	public SNMPTarget() {
		// init(routerip,kbp_id);
	}

	public void init(String routerip, int port, String comm, String version) {
		COMMUNITY = comm;
		PORT = port;
		if (version != null && version.length() != 0) {
			VERSION = version;
		}
		init(routerip);
	}

	public void init(String routerip, int port, String comm) {
		COMMUNITY = comm;
		PORT = port;
		init(routerip);
	}

	public void init(String routerip, String comm) {
		COMMUNITY = comm;
		init(routerip);
	}

	public void init(String routerip) {
		this.ObjectIP = routerip;
		target = new SnmpTarget();
		//target.setLoadFromCompiledMibs(true);
		target.setDebug(DEBUG);
		if (this.VERSION.indexOf("1") != -1) {
			target.setSnmpVersion(SnmpTarget.VERSION1);
		} else if (this.VERSION.indexOf("2") != -1) {
			target.setSnmpVersion(SnmpTarget.VERSION2C);
		} else if (this.VERSION.indexOf("3") != -1) {
			target.setSnmpVersion(SnmpTarget.VERSION3);
		} else {
			target.setSnmpVersion(SnmpTarget.VERSION1);
		}
		target.setTargetHost(ObjectIP); // set the agent hostname
		target.setCommunity(COMMUNITY);
		target.setTargetPort(PORT);
		target.setRetries(RETRIES);
		target.setTimeout(TIMEOUT);
		if (target.getSnmpVersion() == target.VERSION3) {
			target.create_v3_tables();
		}
		KPISet.clear();
		/*
		 * System.out.println("*****************************************************************"
		 * ); System.out.println(KPISet.size());System.out.println(
		 * "*****************************************************************");
		 */
	}

	public void release() {
		// KPISet.clear();
		target.releaseResources();
	}

	public boolean getState() {
		return getSNMPState();
	}

	public boolean getSNMPState() {
		String value = getKPIInfo(".1.3.6.1.2.1.1.5.0");
		if (value == null) {
			return false;
		}
		return true;
	}

	public String getKPIInfo(String oid) {
		// System.out.println("Begin getKPIInfo");
		String oids[] = new String[1];
		String result[] = null;
		try{
		oids[0] = "1.0";
		
		target.setObjectIDList(oids);
		target.oidList[0] = new com.adventnet.snmp.snmp2.SnmpOID(oid);
		result = target.snmpGetList(); // do a get request
		// System.out.println("End getKPIInfo");

		}catch(Exception e){
			e.printStackTrace();
		}
		if (result == null) {
			return null;
		} else {
			return result[0];
		}

	}

	public Vector walkKPIInfo(String oid) {
		// System.out.println("Begin snmpWalkList");
		Vector tmp_result = new Vector();
		Vector tmp_oid = new Vector();
		target.setObjectID(oid);
		target.oidList[0] = new com.adventnet.snmp.snmp2.SnmpOID(oid);// .1.3.6.1.4.1.11.2.3.1.2.2.1
		// Each
		// entry
		// contains
		// objects
		// for a
		// particular
		// file
		// system.(HP)

		int maxtry = 0;
		com.adventnet.snmp.snmp2.SnmpOID[] oidList = target.getSnmpOIDList();
		if (oidList == null) {
			return null;
		} else {
			SnmpOID rootoid = oidList[0];
			SnmpOID curroid = null;
			while (maxtry++ < 3000) { // limit the max getnexts to 5000
				String result1[] = target.snmpGetNextList();
				if (result1 == null) {
					target.oidList[0] = curroid;
					continue;
					// break;
				}
				if (!SnmpTarget.isInSubTree(rootoid, target.getSnmpOID()))
					break; // check first column

				for (int i = 0; i < result1.length; i++) { // print the values
					// System.out.println(target.getObjectID(i) + ": " +
					// result1[i]);
					tmp_result.add(result1[i]);
					tmp_oid.add(target.getObjectID(i));
				}
			}

			if (maxtry == 1) { // we did not get a valid row
				System.err
						.println("Request fed, timed out or no available data("
								+ oid + "). \n " + target.getErrorString());
			}
		}
		// System.out.println("End snmpWalkList");
		return tmp_result;
	}

	public void walkShow() {
		/*com.adventnet.snmp.snmp2.SnmpOID[] oidList = target.getSnmpOIDList();
		if (oidList == null) {
			System.out.println("oidList is null");
		} else {
			System.out.println(oidList.length);
			for (int i = 0; i < oidList.length; i++) {
				SnmpOID oid = oidList[i];
				System.out.println(oid.toString());
			}
			try {
				String next = target.snmpGetNext();
				System.out.println("next = " + next);
				SnmpVarBind[][] svbs = target.snmpGetAllVariableBindings();
				if (svbs != null) {
					System.out.println("svbs.length=" + svbs.length);
				}
				
				 * String[][] s=target.snmpGetAllList(); for(int j=0;j<s.length;j++){
				 * String[] s1=s[j]; for(int k=0;k<s1.length;k++){
				 * System.out.println("s"+j+k+"="+s[j][k]); } }
				 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}*/
		String ip = this.ObjectIP;
		String port = String.valueOf(this.PORT);
		String cs = this.COMMUNITY;
		System.out.println("IP PORT COMMUNITY <> " + ip + " " + port + " " + cs);
		try {
            String resutl = null;
            Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
            //Snmp snmp= new Snmp(new DefaultTcpTransportMapping());
            CommunityTarget target = new CommunityTarget();// agent����
            target.setCommunity(new OctetString(cs));//���ù�ͬ����,û��������RWCommnity�ķ���,���ֻ����һ��.   
            //target.setVersion(SnmpConstants.version1);//���ð汾   
            target.setVersion(SnmpConstants.version2c);
            //����IP��ַ�Ͷ˿ں�,���ᄍȻ��'/'4�ָ�,����ȷʵû���ϵ�,JDOC��˵�����û��
            target.setAddress(new UdpAddress(ip + "/" + port));
            //target.setAddress(new TcpAddress(ip+"/"+port));
            target.setRetries(1); // �������Դ���
			target.setTimeout(5000); // ���ó�ʱ
			snmp.listen(); // ����
			String m_oid = "1";
			int w = 0;
			// BufferedWriter output = new BufferedWriter(new
			// FileWriter(".\\walk.txt"));
            while (true) {
                w++;
                // set pud type and set oid   
                PDU request = new PDU();         // new request PDU��
                request.setType(PDU.GETNEXT); // ����PDU����,
                //            request.add(new VariableBinding(new OID("1.3.6.1.2.1.1"))); //OID���   
                //request.add(new VariableBinding(new OID(".1.3.6.1.2.1.1"))); //OID���   
                request.add(new VariableBinding(new OID(m_oid)));  
//                System.out.println("request UDP:" + request);//��������������,   
                PDU response = null;//����response��   
                ResponseEvent responseEvent = snmp.send(request, target); //����request PDU   
                //����response PDU   
                response = responseEvent.getResponse();  
  
                //response PDU�����   
                if (response != null) {  
                    if (response.getErrorIndex() == response.noError && response.getErrorStatus() == response.noError) {  
//                        System.out.println("no error.");   
                        String pause = responseEvent.getResponse().getVariableBindings().toString();
                        System.out.println("PAUSE : " + pause);
						String getvalue = pause.substring(pause.indexOf("1"), pause.indexOf(']'));
						String oid = pause.substring(pause.indexOf("1"), pause.indexOf("=") - 1);
						String value = pause.substring(pause.indexOf("=") + 1, pause.indexOf("]"));
						System.out.println(value);
						System.out.println(getvalue);                         
                       // main.jTextArea1.append(getvalue + "\n");
                        //            System.out.println(response);   
                        m_oid = oid;
                    } else {  
                        System.out.println("get error:" + response.getErrorStatusText());  
                     //  output.write("error  " + response.getErrorStatusText());   
                        break;  
                    }  
                } else {  
                    System.out.println("get response error");                     
                    break;  
                }  
            }  
            System.out.println(":::::::" + w);  
           // output.newLine();   
           // output.write(":::::::" + w + "----------Snmp walk done");   
        } catch (IOException e){  
            e.printStackTrace();  
        }  
	}

	public Vector getRowKPIInfo(String rootoid, Vector suboid) {
		return null;
	}

	public Vector getColKPIInfo(String oid) {
		return null;
	}

	static public void main(String args[])  {
		SNMPTarget collection = new SNMPTarget();
		if (args != null) {
			if (args.length == 2) {
				String ip = args[0];
				String port = args[1];
				System.out.println("SNMP ip=" + ip);
				int intport = Integer.valueOf(port).intValue();
				System.out.println("SNMP port=" + intport);
				// collection.init(ip, 161, community);
				// collection.init(ip, intport, "");

				// collection.init(ip, 161, "public");
				System.out
						.println("getSNMPState :" + collection.getSNMPState());
				collection.walkShow();
				System.out.println("getSNMPState over!");
			} else if (args.length == 3) {
				String ip = args[0];
				String community = args[1];
				String port = args[2];
				System.out.println("SNMP ip=" + ip);
				int intport = Integer.valueOf(port).intValue();
				System.out.println("SNMP port=" + intport);
				//collection.init(ip, 161, community);
				collection.init(ip, intport, community);

				// collection.init(ip, 161, "public");
				System.out
						.println("getSNMPState :" + collection.getSNMPState());
				collection.walkShow();
				System.out.println("getSNMPState over!");

			} else if (args.length == 4) {

				String ip = args[0];
				String community = args[1];
				String port = args[2];
				String oid = args[3];
				System.out.println("SNMP ip=" + ip);
				int intport = Integer.valueOf(port).intValue();
				System.out.println("SNMP port=" + intport);
				// collection.init(ip, 161, community);
				collection.init(ip, intport, community, "3");

				// collection.init(ip, 161, "public");
				System.out
						.println("getSNMPState :" + collection.getSNMPState());
				String value = collection.getKPIInfo(oid);
				System.out.println(oid + ":" + value);
				System.out.println("getSNMPState over!");
				//collection.walkShow();
			} else {
				// collection.init("127.0.0.1", 1161, "public");
				// collection.init("10.7.7.254", 161, "public");
				// collection.init("192.168.3.254", 1161, "public");
				System.out.println("aa");
				System.out
						.println("getSNMPState :" + collection.getSNMPState());
				System.out.println("aa");
				// return ;
				// System.out.println("getKPIInfo:" +
				// collection.getKPIInfo(".1.3.6.1.2.1.1.5.0"));
				/*
				 * String aaa = ""; for(int i=0;i<1000;i++){ aaa = aaa +
				 * "12345\n"; }
				 * 
				 * collection.addKPI("2222","VM-22222",aaa);
				 * collection.saveKPI();
				 */
				System.out.println(collection.getKPIInfo(".1.2.3.4.1.1"));
				System.out.println(collection.getKPIInfo(".1.2.3.4.1.2"));
				System.out.println(collection.getKPIInfo(".1.2.3.4.1.3"));
			}
		}
		collection.release();
	}
}