snmp4j完整示例

 

#mib.properties
#Fri Jul 11 15:57:28 CST 2008
1.3.6.1.2.1.1.6.0=beijing
1.3.6.1.2.1.1.8.0=test
1.3.6.1.2.1.1.5.0=admin
1.3.6.1.2.1.1.7.0=8899

?mib搞的两天不是很明白,于是自己定义了个配置文件来充当mib库,mib.properties

?

下面的例子是服务器端,也就是manager:

?

import java.io.IOException;

import java.util.Vector;

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.GenericAddress;

import org.snmp4j.smi.OID;

import org.snmp4j.smi.OctetString;

import org.snmp4j.smi.VariableBinding;

import org.snmp4j.transport.DefaultUdpTransportMapping;

public class SnmpUtil {
	private Snmp snmp = null;
	private Address targetAddress = null;

	public void initComm() throws IOException {
		// 设置Agent方的IP和端口
		targetAddress = GenericAddress.parse("udp:192.168.10.191/161");
		TransportMapping transport = new DefaultUdpTransportMapping();
		snmp = new Snmp(transport);
		transport.listen();
	}

	public ResponseEvent sendPDU(PDU pdu) throws IOException {
		// 设置 target
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString("public"));
		target.setAddress(targetAddress);
		// 通信不成功时的重试次数
		target.setRetries(2);
		// 超时时间
		target.setTimeout(1500);
		target.setVersion(SnmpConstants.version1);
		// 向Agent发送PDU,并返回Response
		return snmp.send(pdu, target);
	}

	public void setPDU() throws IOException {
		// set PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 7,
				0 }), new OctetString("8899")));
		pdu.setType(PDU.SET);
		sendPDU(pdu);
	}
	public void getPDU() throws IOException {
		// get PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 6,
				0 })));// pcName
		pdu.setType(PDU.GET);
		readResponse(sendPDU(pdu));
	}

	public void readResponse(ResponseEvent respEvnt) {
		// 解析Response
		System.out.println("----------解析Response-------------");
		if (respEvnt != null && respEvnt.getResponse() != null) {
			Vector<VariableBinding> recVBs = respEvnt.getResponse()
			.getVariableBindings();
			for (int i = 0; i < recVBs.size(); i++) {
				VariableBinding recVB = recVBs.elementAt(i);
				System.out
						.println(recVB.getOid() + " : " + recVB.getVariable());
			}
		}

	}

	public static void main(String[] args) {
		System.out.println("----------start-------------");
		try {
			SnmpUtil util = new SnmpUtil();
			util.initComm();
			 util.setPDU();
			util.getPDU();
		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}

?

agent代理端代码:

?

import java.util.*;
/**
 * agent代理端
 * leo
 * 20080710
 */
import org.snmp4j.*;
import org.snmp4j.smi.*;

import snmputil.Config;

public class OTAAgent {

	public static class Handler implements org.snmp4j.CommandResponder {
		protected java.lang.String mAddress = null;
		protected int mPort = 0;
		protected java.lang.String mMyCommunityName = null;
		protected org.snmp4j.TransportMapping mServerSocket = null;
		protected org.snmp4j.Snmp mSNMP = null;

		public Handler() {
		}

		public void configure() {
			mAddress = "192.168.10.191";
			mPort = 161;
			mMyCommunityName = "OAagent";
		}

		public void start() {
			try {
				mServerSocket = new org.snmp4j.transport.DefaultUdpTransportMapping(
						new org.snmp4j.smi.UdpAddress(java.net.InetAddress
								.getByName(mAddress), mPort));
				mSNMP = new org.snmp4j.Snmp(mServerSocket);
				mSNMP.addCommandResponder(this);
				mServerSocket.listen();
			} catch (java.net.UnknownHostException vException) {
				System.out.println(vException);
			} catch (java.io.IOException vException) {
				System.out.println(vException);
			}
		}

		public synchronized void processPdu(
				org.snmp4j.CommandResponderEvent aEvent) {
			java.lang.String vCommunityName = new java.lang.String(aEvent
					.getSecurityName());
			System.out.println("Community name " + vCommunityName);
			org.snmp4j.PDU vPDU = aEvent.getPDU();
			Config config=new Config();
			if (vPDU == null) {
				System.out.println("Null pdu");
			} else {
				System.out.println("(rcv) " + vPDU.toString());
				switch (vPDU.getType()) {
				case org.snmp4j.PDU.GET:
				case org.snmp4j.PDU.GETNEXT:
					break;
				case org.snmp4j.PDU.SET:
					System.out.println("------SET----------");
					String reciv=vPDU.get(0).getVariable().getSyntaxString();
					System.out.println("----set------"+vPDU.get(0).toString());
					String setoid=vPDU.get(0).toString();
					System.out.println("-----set-----"+setoid.substring(0, setoid.indexOf("=")-1));
					System.out.println("-----set-----"+setoid.substring(setoid.indexOf("=")+1));
					config.setValueByOID(setoid.substring(0, setoid.indexOf("=")-1).trim(), setoid.substring(setoid.indexOf("=")+1).trim());
				}
				org.snmp4j.mp.StatusInformation statusInformation = new org.snmp4j.mp.StatusInformation();
				org.snmp4j.mp.StateReference ref = aEvent.getStateReference();
				try {
					System.out.println("Sending response");
					vPDU.setType(PDU.RESPONSE);
					
					OID oid=vPDU.get(0).getOid();
					String setoid=vPDU.get(0).toString();
					System.out.println("----get------"+setoid.substring(0, setoid.indexOf("=")-1));
					System.out.println("-----get-----"+setoid.substring(setoid.indexOf("=")+1));
					vPDU.set(0, new VariableBinding(oid,
							new OctetString(config.getValueByOID(setoid.substring(0, setoid.indexOf("=")-1).trim()))));

					aEvent.getMessageDispatcher().returnResponsePdu(
							aEvent.getMessageProcessingModel(),

							aEvent.getSecurityModel(),
							aEvent.getSecurityName(),

							aEvent.getSecurityLevel(), vPDU,
							aEvent.getMaxSizeResponsePDU(), ref,

							statusInformation);
				} catch (org.snmp4j.MessageException vException) {
					System.out.println(vException);
				}
			}
		}
	}

	public static void main(String argv[]) {
		Handler h = new Handler();
		/** 初始化参数 * */
		h.configure();
		h.start();
		/** Do nothing loop * */
		while (true) {
			System.out.println("----------loop-------------");
			synchronized (OTAAgent.class) {
				try {
					OTAAgent.class.wait();
				} catch (Exception e) {
				}
			}
		}
	}
}

?

还有一个就是获取和保存mib信息的类:

?

package snmputil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

public class Config {
	Properties properties;
	Map map;

	public Config() {
		properties = new Properties();

		try {
			properties.load(new FileInputStream("mib.properties"));
		} catch (IOException e) {
			System.out.println("读取properties文件错误");
			e.printStackTrace();
		}
	}

	/**
	 * 根据oid获取value
	 * 
	 * @param oid
	 * @return
	 */
	public String getValueByOID(String oid) {

		return properties.getProperty(oid);

	}

	public void setValueByOID(String oid, String value) {
		
		properties.setProperty(oid, value);
		try {
			properties.store(new FileOutputStream("mib.properties"),"mib.properties");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	

	}

	//测试主函数
	   public static void main(String[] args) {
		   Config cfg=new Config();
		   String oid="1.3.6.1.2.1.1.8.0";
		   System.out.println("---------"+cfg.getValueByOID(oid));
		   
		   cfg.setValueByOID(oid, "test");
		
		   
		
		   System.out.println("---------"+cfg.getValueByOID(oid));
	   }
}

?

?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值