package com.lk.util;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
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.Variable;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import com.lk.list.HashListMap;
/**
* Snmp4j发送消息相关帮助类
*
* @author LiuKun
*
*/
public class Snmp4jSendUtil {
private static final Logger logger = Logger.getLogger(Snmp4jSendUtil.class);
public static Logger getLogger() {
return logger;
}
/**
* 发送消息
*
* @param serverIp
* 服务器ip
* @param port
* 服务器端口
* @param message
* 发送消息
*/
public static void sendMessage(String serverIp, int port, String message) {
HashListMap<String, String> oidMessageMap = new HashListMap<String, String>();
// 系统名,定义为常量
String oid_SJ = "1.3.6.1.2.1.1.6.0";
String message_SJ = "SJ";
oidMessageMap.put(oid_SJ, message_SJ);
// String oid = "1.2.3.4.5.6";
String oid = "1.3.6.1.2.1.1.6.1";
oidMessageMap.put(oid, message);
String oid_Unique = "1.3.6.1.2.1.1.6.2";
String message_Unique = getKeyForUUID();
oidMessageMap.put(oid_Unique, message_Unique);
String oid_Timestamp = "1.3.6.1.2.1.1.6.3";
String message_Timestamp = getFullText(new Date());
oidMessageMap.put(oid_Timestamp, message_Timestamp);
sendMessage(serverIp, port, oidMessageMap);
}
/**
* 发送消息
*
* @param serverIp
* 服务器ip
* @param port
* 服务器端口
* @param oidMessageMap
* Map<oid,OctetString>如:1.2.3.4.5.6=priv
* @throws Exception
*/
public static void sendMessage(String serverIp, int port,
HashListMap<String, String> oidMessageMap) {
String addr = "udp:" + serverIp + "/" + port;
sendMessage(addr, oidMessageMap);
}
/**
* 使用Snmp4j的UDP协议发送消息
*
* @param addr
* 通讯地址,如:udp:127.0.0.1/162
* @param oidMessageMap
* Map<oid,OctetString>如:1.2.3.4.5.6=priv
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void sendMessage(String addr,
HashListMap<String, String> oidMessageMap) {
if (logger.isDebugEnabled()) {
logger.debug("===start:sendMessage===");
}
if (logger.isDebugEnabled()) {
logger.debug("===start:sendMessage:content===");
for (int i = 0; null != oidMessageMap && i < oidMessageMap.size(); i++) {
String oid = oidMessageMap.getKey(i);
String message = oidMessageMap.getValue(i);
logger.debug(oid + "=" + message);
}
logger.debug("===end:sendMessage:content===");
}
try {
// 设置Agent方的IP和端口
Address targetAddress = GenericAddress.parse(addr);
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// PDU 对象
PDU pdu = new PDU();
for (int i = 0; null != oidMessageMap && i < oidMessageMap.size(); i++) {
String oid = oidMessageMap.getKey(i);
String message = oidMessageMap.getValue(i);
pdu.add(new VariableBinding(new OID(oid), new OctetString(
message)));
}
// 操作类型
// pdu.setType(PDU.GET);//会获取响应消息
// pdu.setType(PDU.SET);
pdu.setType(PDU.TRAP);
// 设置 目标
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
// 通信不成功时的重试次数 N+1次
// target.setRetries(2);
target.setRetries(0);
// 超时时间
target.setTimeout(2 * 1000);
// SNMP 版本
target.setVersion(SnmpConstants.version2c);
// 向Agent发送PDU,并返回Response
ResponseEvent revent = snmp.send(pdu, target);
if (null != revent) {
readResponse(revent);
}
// 释放资源
if (null != transport) {
if (transport.isListening()) {
transport.close();
}
transport = null;
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (logger.isDebugEnabled()) {
logger.debug("===end:sendMessage===");
}
}
/**
* 读取相应信息
*
* @param respEvnt
*/
@SuppressWarnings("unchecked")
public static void readResponse(ResponseEvent respEvnt) {
if (logger.isDebugEnabled()) {
logger.debug("start:readResponse");
}
// 解析Response
if (logger.isDebugEnabled()) {
logger.debug("------------>解析Response<-------------");
}
try {
if (respEvnt != null && respEvnt.getResponse() != null) {
Vector<VariableBinding> recVBs = (Vector<VariableBinding>) respEvnt
.getResponse().getVariableBindings();
for (int i = 0; null != recVBs && i < recVBs.size(); i++) {
VariableBinding recVB = recVBs.elementAt(i);
if (logger.isDebugEnabled()) {
logger.debug(recVB.getOid() + ":"
+ recVB.getVariable().toString());
Variable variable = recVB.getVariable();
OctetString octetString = (OctetString) variable;
String message = new String(octetString.getValue());
logger.debug("接收到服务端反馈的消息为[" + message + "]");
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (logger.isDebugEnabled()) {
logger.debug("end:readResponse");
}
}
/**
* 获取本机地址
*/
@SuppressWarnings("static-access")
public static String getLocalHost() {
try {
return java.net.InetAddress.getLocalHost().getLocalHost()
.getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
/**
* 提取uuidhex的唯一编号值(java.util.UUID.randomUUID())
*
* @return 32位字符码
* @author LiuKun
* @created 2014-8-21 上午9:54:25
*/
// synchronized:使用生成uuidhex时不需要同步控制
public static String getUUIDhex() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* 提取uuidhex的唯一编号值(java.util.UUID.randomUUID())(集群高并发存在冲突,而且性能差)
*
* @return 32位字符码
* @author LiuKun
* @created 2014-8-21 上午9:57:28
*/
// synchronized:使用生成uuidhex时不需要同步控制
public static String getKeyForUUID() {
// SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssS");
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// if (SystemUtil.isPrintStackTrace()) {
// e.printStackTrace();
// }
// if (SystemUtil.isLoggerError()) {
// logger.error(e);
// }
// }
// return format.format(new Date());
return getUUIDhex();
}
private static SimpleDateFormat fullFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
/**
* 以"yyyy-MM-dd HH:mm:ss.SSS"格式转换给定日期对象
*
* @param date
* 给定日期对象
* @return "yyyy-MM-dd HH:mm:ss.SSS"格式的日期字串
*/
public static String getFullText(Date date) {
return fullFormat.format(date);
}
public static void main(String[] args) throws Exception {
String serverIp = "127.0.0.1";
Integer port = 162;
Date nowDate = new Date();
String message1 = "Hi, I'm the client:[" + getLocalHost()
+ "],Hello World![" + getFullText(nowDate) + "]";
String message2 = "你好,我是客户端:[" + getLocalHost() + "],Hello World!["
+ getFullText(nowDate) + "]";
sendMessage(serverIp, port, message1);
sendMessage(serverIp, port, message2);
System.out.println("finish");
}
}
评论0
最新资源