snmp 서버와 클라이언트 구현, snmp4j 기반
11308 단어 snmp
snmp 프로토콜: 간단한 네트워크 관리 프로토콜로 네트워크 장치를 관리하는 데 자주 사용되며,java 개발에서 snmp4j를 베이스 snmp 구성 요소로 사용하는 것이 인기가 있습니다.
다음 예는 snmp4j를 바탕으로 간단한 snmp 서버와 클라이언트를 구축하는 방법을 간단하게 설명합니다
snmp 서버
package com.gbcom.protocol.snmp;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Vector;
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.MessageDispatcherImpl;
import org.snmp4j.MessageException;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.StateReference;
import org.snmp4j.mp.StatusInformation;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
/**
* Trap
*
* @author syz
*
* @date 3:28:28
* @version v1.0.0
* @see SnmpTrapReceiver
*/
public class SnmpTrapReceiver implements CommandResponder {
private MultiThreadedMessageDispatcher dispatcher;
private Snmp snmp = null;
private Address listenAddress;
private ThreadPool threadPool;
public SnmpTrapReceiver() {
}
// 。
private void init() throws UnknownHostException, IOException {
threadPool = ThreadPool.create("Trap", 2);
dispatcher = new MultiThreadedMessageDispatcher(threadPool,
new MessageDispatcherImpl());
listenAddress = GenericAddress.parse(System.getProperty(
"snmp4j.listenAddress", "udp:127.0.0.1/162")); // IP
TransportMapping transport;
// TCP UDP
if (listenAddress instanceof UdpAddress) {
transport = new DefaultUdpTransportMapping(
(UdpAddress) listenAddress);
} else {
transport = new DefaultTcpTransportMapping(
(TcpAddress) listenAddress);
}
snmp = new Snmp(dispatcher, transport);
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
snmp.listen();
}
public void run() {
try {
init();
snmp.addCommandResponder(this);
System.out.println(" Trap !");
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* CommandResponder processPdu , 、PDU trap ,
*
* @param respEvnt
*
*/
public void processPdu(CommandResponderEvent respEvnt) {
if (respEvnt != null && respEvnt.getPDU() != null) {
PDU src_pdu = respEvnt.getPDU();
// trap
if (src_pdu.getType() == PDU.INFORM) {
PDU responsePDU = new PDU(src_pdu);
responsePDU.setErrorIndex(0);
responsePDU.setErrorStatus(0);
responsePDU.setType(PDU.RESPONSE);
StatusInformation statusInfo = new StatusInformation();
StateReference stateRef = respEvnt.getStateReference();
try {
respEvnt.getMessageDispatcher().returnResponsePdu(
respEvnt.getMessageProcessingModel(),
respEvnt.getSecurityModel(),
respEvnt.getSecurityName(),
respEvnt.getSecurityLevel(), responsePDU,
respEvnt.getMaxSizeResponsePDU(), stateRef,
statusInfo);
} catch (MessageException msgEx) {
msgEx.printStackTrace();
}
}
Vector recVBs = (Vector) respEvnt.getPDU()
.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) {
//
SnmpTrapReceiver multithreadedtrapreceiver = new SnmpTrapReceiver();
multithreadedtrapreceiver.run();
}
}
snmp 클라이언트
봉인 상용 방법
package com.gbcom.protocol.snmp;
import java.io.IOException;
import java.util.Vector;
import org.apache.log4j.Logger;
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;
/**
* {@code Trap GET SET}
*
* @author syz
* @date 5:02:20
* @version v1.0.0
* @see SnmpSender
*/
public class SnmpSender {
private static final Logger LOG = Logger.getLogger(SnmpSender.class);
private Snmp snmp = null;
private Address targetAddress = null;
public void initComm() throws IOException {
// IP
targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
LOG.info("init SNMP object succes !! target = udp:127.0.0.1/161");
}
/**
* Trap
*
* @throws IOException
*/
public void sendTrap() throws IOException { targetAddress = GenericAddress.parse("udp:127.0.0.1/162");
// target
CommunityTarget target = new CommunityTarget();
target.setAddress(targetAddress);
//
target.setRetries(2);
//
target.setTimeout(1500);
// snmp
target.setVersion(SnmpConstants.version2c);
// PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"),
new OctetString("SnmpTrap")));
pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.2"),
new OctetString("JavaEE")));
pdu.setType(PDU.TRAP);
// Agent PDU, Response
ResponseEvent respEvnt = snmp.send(pdu, target);
// Response
readResponse(respEvnt);
// if (respEvnt != null && respEvnt.getResponse() != null) {
// Vector 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 ResponseEvent sendPDU(PDU pdu) throws IOException {
// target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
//
target.setRetries(1);
//
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
// Agent PDU, Response
return snmp.send(pdu, target);
}
public void doSet() throws IOException {
// set PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 5,
0 }), new OctetString("SNMPTEST")));
pdu.setType(PDU.SET);
readResponse(sendPDU(pdu));
}
public void doGet() throws IOException {
// get PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 1,
0 })));
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 2,
0 })));
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 3,
0 })));
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 4,
0 })));
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 5,
0 })));
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 6,
0 })));
pdu.setType(PDU.GET);
readResponse(sendPDU(pdu));
}
private void readResponse(ResponseEvent respEvnt) {
// Response
if (respEvnt != null && respEvnt.getResponse() != null) {
Vector recVBs = (Vector) respEvnt.getResponse()
.getVariableBindings();
for (int i = 0; i < recVBs.size(); i++) {
VariableBinding recVB = recVBs.elementAt(i);
LOG.info("THREAD NUM--"+Thread.currentThread() + recVB.getOid() + " : " + recVB.getVariable());
}
}
}
public void doWork(){
for(int i=0;i<1;i++){
Thread t = new Thread(new WorkThread());
t.start();
}
}
class WorkThread implements Runnable{
@Override
public void run() {
while(!Thread.currentThread().interrupted()){
try {
// doGet();
// doSet();
Thread.sleep(1*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error("THREAD NUM--"+Thread.currentThread() + "InterruptedException",e);
} catch (Exception e) {
e.printStackTrace();
LOG.error("THREAD NUM--"+Thread.currentThread() + "other Exception",e);
continue;
}
}
}
}
public static void main(String[] args) {
try {
SnmpSender util = new SnmpSender();
util.initComm();
// util.sendTrap();
LOG.info("--- DO GET --");
// util.doGet();
LOG.info("----do set---");
// util.doSet();
util.doWork();
} catch (IOException e) {
e.printStackTrace();
}
}
}
sender의 정확한 운행은 에이전트를 열어야 합니다. 일반적인 상황에서 장치 측은 snmp 에이전트를 실현하고 서버는 snmp 서버를 실현합니다.
snmp4j 구성 요소를 snmp 프로토콜로 개발해야 한다면 위의 예를 참고할 수 있습니다
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Prometheus/Grafana에서 Catalyst 트래픽을 수집해 보세요.Cisco의 Catalyst2960-8 트래픽 데이터를 Prometheus에서 가져 가기로 결정했습니다. 예에 따라 환경이지만, ・MacBookPro(macOS10.14.6) ・WS-C2960-8TC-L(12.2(5...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.