SNMP的安装与使用
- 前言
- SNMP安装
- Windows下安装
- Centos下安装
- SNMP4J的使用
- Centos下SNMPV3配置
前言
SNMP(简单网络管理协议) 是专门设计用于在 IP 网络管理网络节点(服务器、工作站、路由器、交换机及HUBS等)的一种标准协议,它是一种应用层协议。
SNMP协议主要由两大部分构成:SNMP管理站和SNMP代理。SNMP管理站(snmp-server)是一个中心节点,负责收集维护各个SNMP元素的信息,并对这些信息进行处理,最后反馈给网络管理员;
SNMP代理(snmp-agent)是运行在各个被管理的网络节点之上,负责统计该节点的各项信息,并且负责与SNMP管理站交互,接收并执行管理站的命令,上传各种本地的网络信息
SNMP目前共有v1,v2,v3这三个版本:
SNMP v1是SNMP协议的最初版本,不过依然是众多厂家实现SNMP基本方式。
SNMP v2通常被指是基于community的SNMP V2。Community实质上就是密码。
SNMP v3 是最新版本的SNMP。增加了对认证和密文传输的支持。
SNMP安装
Windows下安装
看截图信息,你懂的
**
**
Centos下安装
查看snmp服务是否已安装:
rpm -qa |grep snmp
rpm安装命令:
yum install -y net-snmp net-snmp-utils
snmp安装成功后启动命令:(snmp-agent)
service snmpd start 默认端口161
trap监听服务,获取客户端发送的trap:
service snmptrapd start 默认端口162
或使用
snmptrap -df -Lo
命令监听
内网安装如果无法联网,建议自己配置yum源:
配置方法:
1、拷贝完整版的centos镜像到内网机器
2、挂载镜像到本地目录
mount -o loop -t iso9660 <镜像路径> <挂载目录路径>
3、配置yum源到镜像文件
vim /etc/yum.repos.d/yum.repo
[centos-yum]
name=centosdir
baseurl=file:///centosiso/
enabled=1 #是否开启仓库源
gpgcheck=0 #无需检查
SNMP4J的使用
引入snmp4j
compile 'org.snmp4j:snmp4j:2.8.7'
发送trap给Snmp上层管理系统:“端口是162”
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.SNMP4JSettings;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.Priv3DES;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
/**
* 本类用于发送Trap信息
*
*/
public class SnmpTrapSender {
private Snmp snmp = null;
private Address targetAddress = null;
private TransportMapping<UdpAddress> transport = null;
public static void main(String[] args) {
SnmpTrapSender poc = new SnmpTrapSender();
try {
poc.init();
poc.sendV1Trap();
poc.sendV2cTrap();
} catch (IOException e) {
e.printStackTrace();
}
}
public void init() throws IOException {
//目标主机的ip地址 和 端口号
targetAddress = GenericAddress.parse("udp:127.0.0.1/162");
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
}
public ResponseEvent sendV1Trap() throws IOException {
PDUv1 pdu = new PDUv1();
VariableBinding v = new VariableBinding();
v.setOid(SnmpConstants.sysName);
v.setVariable(new OctetString("SnmpV1 Trap Test"));
pdu.add(v);
pdu.setType(PDU.V1TRAP);
// set target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
// retry times when commuication error
target.setRetries(2);
// timeout
target.setTimeout(1500);
target.setVersion(SnmpConstants.version1);
// send pdu, return response
return snmp.send(pdu, target);
}
public ResponseEvent sendV2cTrap() throws IOException {
PDU pdu = new PDU();
VariableBinding v = new VariableBinding();
v.setOid(SnmpConstants.sysName);
v.setVariable(new OctetString("SnmpV2 Trap"));
pdu.add(v);
pdu.setType(PDU.TRAP);
// set target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
// retry times when commuication error
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
// send pdu, return response
return snmp.send(pdu, target);
}
}
接收trap:“监听端口也是162”
import java.io.IOException;
import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.CommandResponder;
import org.snmp4j.MessageDispatcherImpl;
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.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.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
public class TrapReceiver {
private MultiThreadedMessageDispatcher dispatcher;
private Snmp snmp = null;
private Address listenAddress;
private ThreadPool threadPool;
public TrapReceiver(CommandResponder listener) throws UnknownHostException, IOException {
threadPool = ThreadPool.create("Trap", 2);
dispatcher = new MultiThreadedMessageDispatcher(threadPool,
new MessageDispatcherImpl());
logger.debug("监听的IP和端口是={}",System.getProperty(
"snmp4j.listenAddress", "udp:127.0.0.1/162"));
listenAddress = GenericAddress.parse(System.getProperty(
"snmp4j.listenAddress", "udp:127.0.0.1/162")); // 本地IP与监听端口
// listenAddress = GenericAddress.parse(address); // 本地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();
logger.debug("开始监听={}");
snmp.addCommandResponder(listener);
}
public MultiThreadedMessageDispatcher getDispatcher() {
return dispatcher;
}
public void setDispatcher(MultiThreadedMessageDispatcher dispatcher) {
this.dispatcher = dispatcher;
}
public Snmp getSnmp() {
return snmp;
}
public void setSnmp(Snmp snmp) {
this.snmp = snmp;
}
public Address getListenAddress() {
return listenAddress;
}
public void setListenAddress(Address listenAddress) {
this.listenAddress = listenAddress;
}
public ThreadPool getThreadPool() {
return threadPool;
}
public void setThreadPool(ThreadPool threadPool) {
this.threadPool = threadPool;
}
}
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.smi.VariableBinding;
public class ListenSnmp implements CommandResponder {
public Logger logger = LoggerFactory.getLogger(getClass());
public ListenSnmp() {
logger.debug("监控器初始debug");
logger.info("监控器初始info");
logger.warn("监控器初始warn");
logger.error("监控器初始error");
}
@Override
public void processPdu(CommandResponderEvent event) {
// 解析Response
if (event != null && event.getPDU() != null) {
Vector<? extends VariableBinding> recVBs = (Vector<? extends VariableBinding>) event.getPDU().getVariableBindings();
for (int i = 0; i < recVBs.size(); i++) {
VariableBinding recVB = recVBs.elementAt(i);
logger.error(recVB.getOid() + " : " + recVB.getVariable());
System.out.println(recVB.getOid() + " : " + recVB.getVariable());
}
}
}
}
向snmp-agent发送get请求获取机器名:“端口是161”
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.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SnmpSendUtils {
private Snmp snmp = null;// 该类是SNMP4J中最为核心的类。负责SNMP报文的接受和发送。
private Address targetAddress = null;
String snmpAddr = "udp:127.0.0.1/161";
// 初始化
public void initComm() throws IOException {
// 设置Agent方的IP和端口
targetAddress = GenericAddress.parse(snmpAddr);
// 一般情况下,我们都使用UDP协议作为SNMP的传输层协议,所以我们需要实例化的是一个DefaultUdpTransportMapping接口对象;
TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
// 将DefaultUdpTransportMapping接口作为参数传入Snmp构造器,实例化Snmp对象。
snmp = new Snmp(transport);
// 监听snmp信息
transport.listen();
}
@SuppressWarnings("unchecked")
public void sendPDU() 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);
// 创建 PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 5, 0 })));
// MIB的访问方式
pdu.setType(PDU.GET);
// 向Agent发送PDU,并接收Response
ResponseEvent respEvnt = snmp.send(pdu, target);
// 解析Response
if (respEvnt != null && respEvnt.getResponse() != null) {
Vector<VariableBinding> recVBs = (Vector<VariableBinding>) 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) {
try {
System.out.println("start");
SnmpSendUtils util = new SnmpSendUtils();
util.initComm();
util.sendPDU();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Centos下SNMPV3配置
使用
service snmpd stop
命令停止snmpd服务
输入
net-snmp-config --create-snmpv3-user
命令 按照提示输入用户,密码,验证信息等
最后会提示:
adding the following line to /var/lib/net-snmp/snmpd.conf:
createUser name MD5 “pass” DES “despass”
adding the following line to /etc/snmp/snmpd.conf:
rwuser myname
查看这个两个文件,并保存设置的密码信息
使用
snmpwalk -v3 -u myname -l auth -a MD5 -A mypass 127.0.0.1 if
验证是否配置成功
SNMP4j测试
import java.io.IOException;
import java.util.Vector;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivAES192;
import org.snmp4j.security.PrivAES256;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
@SuppressWarnings("rawtypes")
public class SnmpUtilSendGet {
private Address targetAddress = null;
private OID authProtocol;
private OID privProtocol;
private OctetString privPassphrase;
private OctetString authPassphrase;
private OctetString securityName = new OctetString();
private int version;
private String host;
private Target target;
private OctetString community = new OctetString("public");
private TransportMapping transport;
/**
* 初始化Snmp信息
*
* @param host
* @param user
* @param authProtocol
* @param authPasshrase
* @param privProtocol
* @param privPassphrase
* @param version
*/
public SnmpUtilSendGet(String host, String user, String authProtocol, String authPasshrase
, String privProtocol,String privPassphrase, int version) {
this.authPassphrase = new OctetString(authPasshrase);
this.securityName = new OctetString(user);
this.privPassphrase = new OctetString(privPassphrase);
this.version = version;
this.host = host;
if (authProtocol.equals("MD5")) {
this.authProtocol = AuthMD5.ID;
} else if (authProtocol.equals("SHA")) {
this.authProtocol = AuthSHA.ID;
}
if (privProtocol.equals("DES")) {
this.privProtocol = PrivDES.ID;
} else if ((privProtocol.equals("AES128")) || (privProtocol.equals("AES"))) {
this.privProtocol = PrivAES128.ID;
} else if (privProtocol.equals("AES192")) {
this.privProtocol = PrivAES192.ID;
} else if (privProtocol.equals("AES256")) {
this.privProtocol = PrivAES256.ID;
}
}
/**
* 创建snmp
*
* @throws IOException
*/
@SuppressWarnings("unchecked")
public Snmp createSnmpSession() throws IOException {
// 设置管理进程的IP和端口
targetAddress = GenericAddress.parse(host);
if (targetAddress instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping();
} else {
transport = new DefaultUdpTransportMapping();
}
Snmp snmp = new Snmp(transport);
if (version == SnmpConstants.version3) {
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
// Add the configured user to the USM
addUsmUser(snmp);
}
return snmp;
}
/**
* 加入user信息(snmp3)
*
* @param snmp
*/
private void addUsmUser(Snmp snmp) {
snmp.getUSM().addUser(securityName,
new UsmUser(securityName, authProtocol, authPassphrase
, privProtocol, privPassphrase));
}
/**
* 创建PUD
*
* @param target
* @return
*/
public PDU createPDU(Target target) {
PDU request;
if (target.getVersion() == SnmpConstants.version3) {
request = new ScopedPDU();
} else {
request = new PDU();
}
return request;
}
/**
* 创建Target
*
* @return
*/
private Target createTarget() {
if (version == SnmpConstants.version3) {
UserTarget target = new UserTarget();
if (authPassphrase != null) {
if (privPassphrase != null) {
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
} else {
target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
}
} else {
target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
}
target.setSecurityName(securityName);
return target;
} else {
CommunityTarget target = new CommunityTarget();
target.setCommunity(community);
return target;
}
}
/**
* 向管理进程发送Get报文
*
* @throws IOException
*/
@SuppressWarnings({ "unchecked" })
public String sendPDU(String oids) throws IOException {
String v=null;
Snmp snmp = createSnmpSession();
target = createTarget();// 设置 target
target.setAddress(targetAddress);
target.setRetries(2);// 通信不成功时的重试次数
target.setTimeout(1500);// 超时时间
target.setVersion(version);// snmp版本
transport.listen();
// 创建 PDU
//ScopedPDU pdu = createPDU(target);
PDU pdu = createPDU(target);
OID oid = new OID(oids);
pdu.add(new VariableBinding(oid));
pdu.setType(PDU.GET);
ResponseEvent respEvnt = snmp.send(pdu, target);
if (respEvnt != null && respEvnt.getResponse() != null) {
Vector<VariableBinding> recVBs = (Vector<VariableBinding>) respEvnt.getResponse().getVariableBindings();
//for (int i = 0; i < recVBs.size(); i++) {
VariableBinding recVB = recVBs.elementAt(0);
//System.out.println(recVB.getVariable().toString());
//System.out.println("------------------------------------------");
v=recVB.getVariable().toString();
snmp.close();
}
return v;
//}
}
public static void main(String[] args) throws Throwable {
String Address = "127.0.0.1";
SnmpUtilSendGet util = new SnmpUtilSendGet("udp:" + Address + "/161",
"managerv3", "MD5", "authpassword", "DES",
"pripassword", SnmpConstants.version3);
String v = util.sendPDU("");
System.out.println(v);
}
}