snmp4j完整示例

来源:互联网 发布:淘宝u盘32g多少钱 编辑:程序博客网 时间:2024/05/25 05:35
Java代码  收藏代码
  1. #mib.properties  
  2. #Fri Jul 11 15:57:28 CST 2008  
  3. 1.3.6.1.2.1.1.6.0=beijing  
  4. 1.3.6.1.2.1.1.8.0=test  
  5. 1.3.6.1.2.1.1.5.0=admin  
  6. 1.3.6.1.2.1.1.7.0=8899  

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

 

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

 

Java代码  收藏代码
  1. import java.io.IOException;  
  2.   
  3. import java.util.Vector;  
  4.   
  5. import org.snmp4j.CommunityTarget;  
  6.   
  7. import org.snmp4j.PDU;  
  8.   
  9. import org.snmp4j.Snmp;  
  10.   
  11. import org.snmp4j.TransportMapping;  
  12.   
  13. import org.snmp4j.event.ResponseEvent;  
  14.   
  15. import org.snmp4j.mp.SnmpConstants;  
  16.   
  17. import org.snmp4j.smi.Address;  
  18.   
  19. import org.snmp4j.smi.GenericAddress;  
  20.   
  21. import org.snmp4j.smi.OID;  
  22.   
  23. import org.snmp4j.smi.OctetString;  
  24.   
  25. import org.snmp4j.smi.VariableBinding;  
  26.   
  27. import org.snmp4j.transport.DefaultUdpTransportMapping;  
  28.   
  29. public class SnmpUtil {  
  30.     private Snmp snmp = null;  
  31.     private Address targetAddress = null;  
  32.   
  33.     public void initComm() throws IOException {  
  34.         // 设置Agent方的IP和端口  
  35.         targetAddress = GenericAddress.parse("udp:192.168.10.191/161");  
  36.         TransportMapping transport = new DefaultUdpTransportMapping();  
  37.         snmp = new Snmp(transport);  
  38.         transport.listen();  
  39.     }  
  40.   
  41.     public ResponseEvent sendPDU(PDU pdu) throws IOException {  
  42.         // 设置 target  
  43.         CommunityTarget target = new CommunityTarget();  
  44.         target.setCommunity(new OctetString("public"));  
  45.         target.setAddress(targetAddress);  
  46.         // 通信不成功时的重试次数  
  47.         target.setRetries(2);  
  48.         // 超时时间  
  49.         target.setTimeout(1500);  
  50.         target.setVersion(SnmpConstants.version1);  
  51.         // 向Agent发送PDU,并返回Response  
  52.         return snmp.send(pdu, target);  
  53.     }  
  54.   
  55.     public void setPDU() throws IOException {  
  56.         // set PDU  
  57.         PDU pdu = new PDU();  
  58.         pdu.add(new VariableBinding(new OID(new int[] { 13612117,  
  59.                 0 }), new OctetString("8899")));  
  60.         pdu.setType(PDU.SET);  
  61.         sendPDU(pdu);  
  62.     }  
  63.     public void getPDU() throws IOException {  
  64.         // get PDU  
  65.         PDU pdu = new PDU();  
  66.         pdu.add(new VariableBinding(new OID(new int[] { 13612116,  
  67.                 0 })));// pcName  
  68.         pdu.setType(PDU.GET);  
  69.         readResponse(sendPDU(pdu));  
  70.     }  
  71.   
  72.     public void readResponse(ResponseEvent respEvnt) {  
  73.         // 解析Response  
  74.         System.out.println("----------解析Response-------------");  
  75.         if (respEvnt != null && respEvnt.getResponse() != null) {  
  76.             Vector<VariableBinding> recVBs = respEvnt.getResponse()  
  77.             .getVariableBindings();  
  78.             for (int i = 0; i < recVBs.size(); i++) {  
  79.                 VariableBinding recVB = recVBs.elementAt(i);  
  80.                 System.out  
  81.                         .println(recVB.getOid() + " : " + recVB.getVariable());  
  82.             }  
  83.         }  
  84.   
  85.     }  
  86.   
  87.     public static void main(String[] args) {  
  88.         System.out.println("----------start-------------");  
  89.         try {  
  90.             SnmpUtil util = new SnmpUtil();  
  91.             util.initComm();  
  92.              util.setPDU();  
  93.             util.getPDU();  
  94.         } catch (IOException e) {  
  95.   
  96.             e.printStackTrace();  
  97.   
  98.         }  
  99.   
  100.     }  
  101.   
  102. }  

 

agent代理端代码:

 

Java代码  收藏代码
  1. import java.util.*;  
  2. /** 
  3.  * agent代理端 
  4.  * leo 
  5.  * 20080710 
  6.  */  
  7. import org.snmp4j.*;  
  8. import org.snmp4j.smi.*;  
  9.   
  10. import snmputil.Config;  
  11.   
  12. public class OTAAgent {  
  13.   
  14.     public static class Handler implements org.snmp4j.CommandResponder {  
  15.         protected java.lang.String mAddress = null;  
  16.         protected int mPort = 0;  
  17.         protected java.lang.String mMyCommunityName = null;  
  18.         protected org.snmp4j.TransportMapping mServerSocket = null;  
  19.         protected org.snmp4j.Snmp mSNMP = null;  
  20.   
  21.         public Handler() {  
  22.         }  
  23.   
  24.         public void configure() {  
  25.             mAddress = "192.168.10.191";  
  26.             mPort = 161;  
  27.             mMyCommunityName = "OAagent";  
  28.         }  
  29.   
  30.         public void start() {  
  31.             try {  
  32.                 mServerSocket = new org.snmp4j.transport.DefaultUdpTransportMapping(  
  33.                         new org.snmp4j.smi.UdpAddress(java.net.InetAddress  
  34.                                 .getByName(mAddress), mPort));  
  35.                 mSNMP = new org.snmp4j.Snmp(mServerSocket);  
  36.                 mSNMP.addCommandResponder(this);  
  37.                 mServerSocket.listen();  
  38.             } catch (java.net.UnknownHostException vException) {  
  39.                 System.out.println(vException);  
  40.             } catch (java.io.IOException vException) {  
  41.                 System.out.println(vException);  
  42.             }  
  43.         }  
  44.   
  45.         public synchronized void processPdu(  
  46.                 org.snmp4j.CommandResponderEvent aEvent) {  
  47.             java.lang.String vCommunityName = new java.lang.String(aEvent  
  48.                     .getSecurityName());  
  49.             System.out.println("Community name " + vCommunityName);  
  50.             org.snmp4j.PDU vPDU = aEvent.getPDU();  
  51.             Config config=new Config();  
  52.             if (vPDU == null) {  
  53.                 System.out.println("Null pdu");  
  54.             } else {  
  55.                 System.out.println("(rcv) " + vPDU.toString());  
  56.                 switch (vPDU.getType()) {  
  57.                 case org.snmp4j.PDU.GET:  
  58.                 case org.snmp4j.PDU.GETNEXT:  
  59.                     break;  
  60.                 case org.snmp4j.PDU.SET:  
  61.                     System.out.println("------SET----------");  
  62.                     String reciv=vPDU.get(0).getVariable().getSyntaxString();  
  63.                     System.out.println("----set------"+vPDU.get(0).toString());  
  64.                     String setoid=vPDU.get(0).toString();  
  65.                     System.out.println("-----set-----"+setoid.substring(0, setoid.indexOf("=")-1));  
  66.                     System.out.println("-----set-----"+setoid.substring(setoid.indexOf("=")+1));  
  67.                     config.setValueByOID(setoid.substring(0, setoid.indexOf("=")-1).trim(), setoid.substring(setoid.indexOf("=")+1).trim());  
  68.                 }  
  69.                 org.snmp4j.mp.StatusInformation statusInformation = new org.snmp4j.mp.StatusInformation();  
  70.                 org.snmp4j.mp.StateReference ref = aEvent.getStateReference();  
  71.                 try {  
  72.                     System.out.println("Sending response");  
  73.                     vPDU.setType(PDU.RESPONSE);  
  74.                       
  75.                     OID oid=vPDU.get(0).getOid();  
  76.                     String setoid=vPDU.get(0).toString();  
  77.                     System.out.println("----get------"+setoid.substring(0, setoid.indexOf("=")-1));  
  78.                     System.out.println("-----get-----"+setoid.substring(setoid.indexOf("=")+1));  
  79.                     vPDU.set(0new VariableBinding(oid,  
  80.                             new OctetString(config.getValueByOID(setoid.substring(0, setoid.indexOf("=")-1).trim()))));  
  81.   
  82.                     aEvent.getMessageDispatcher().returnResponsePdu(  
  83.                             aEvent.getMessageProcessingModel(),  
  84.   
  85.                             aEvent.getSecurityModel(),  
  86.                             aEvent.getSecurityName(),  
  87.   
  88.                             aEvent.getSecurityLevel(), vPDU,  
  89.                             aEvent.getMaxSizeResponsePDU(), ref,  
  90.   
  91.                             statusInformation);  
  92.                 } catch (org.snmp4j.MessageException vException) {  
  93.                     System.out.println(vException);  
  94.                 }  
  95.             }  
  96.         }  
  97.     }  
  98.   
  99.     public static void main(String argv[]) {  
  100.         Handler h = new Handler();  
  101.         /** 初始化参数 * */  
  102.         h.configure();  
  103.         h.start();  
  104.         /** Do nothing loop * */  
  105.         while (true) {  
  106.             System.out.println("----------loop-------------");  
  107.             synchronized (OTAAgent.class) {  
  108.                 try {  
  109.                     OTAAgent.class.wait();  
  110.                 } catch (Exception e) {  
  111.                 }  
  112.             }  
  113.         }  
  114.     }  
  115. }  

 

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

 

Java代码  收藏代码
  1. package snmputil;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.FileReader;  
  9. import java.io.IOException;  
  10. import java.util.HashMap;  
  11. import java.util.Hashtable;  
  12. import java.util.Map;  
  13. import java.util.Properties;  
  14.   
  15. public class Config {  
  16.     Properties properties;  
  17.     Map map;  
  18.   
  19.     public Config() {  
  20.         properties = new Properties();  
  21.   
  22.         try {  
  23.             properties.load(new FileInputStream("mib.properties"));  
  24.         } catch (IOException e) {  
  25.             System.out.println("读取properties文件错误");  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  
  29.   
  30.     /** 
  31.      * 根据oid获取value 
  32.      *  
  33.      * @param oid 
  34.      * @return 
  35.      */  
  36.     public String getValueByOID(String oid) {  
  37.   
  38.         return properties.getProperty(oid);  
  39.   
  40.     }  
  41.   
  42.     public void setValueByOID(String oid, String value) {  
  43.           
  44.         properties.setProperty(oid, value);  
  45.         try {  
  46.             properties.store(new FileOutputStream("mib.properties"),"mib.properties");  
  47.         } catch (FileNotFoundException e) {  
  48.             // TODO Auto-generated catch block  
  49.             e.printStackTrace();  
  50.         } catch (IOException e) {  
  51.             // TODO Auto-generated catch block  
  52.             e.printStackTrace();  
  53.         }   
  54.       
  55.   
  56.     }  
  57.   
  58.     //测试主函数  
  59.        public static void main(String[] args) {  
  60.            Config cfg=new Config();  
  61.            String oid="1.3.6.1.2.1.1.8.0";  
  62.            System.out.println("---------"+cfg.getValueByOID(oid));  
  63.              
  64.            cfg.setValueByOID(oid, "test");  
  65.           
  66.              
  67.           
  68.            System.out.println("---------"+cfg.getValueByOID(oid));  
  69.        }  
  70. }  

 

 

  • log4j-1.2.9.jar (344 KB)
  • 下载次数: 445
  • SNMP4J.jar (360.9 KB)
  • 下载次数: 834
0 0