docker方式搭建:包含了ldap服务和ldap admin图形化界面服务
参考ldap服务:http://127.0.0.1:81
用户名:CN=admin,DC=ldap,DC=com 密码:123456
docker-compose.yml文件内容如下
version: '3'
services:
ldap:
image: osixia/openldap:latest
container_name: ldap
environment:
- TZ=Asia/Shanghai
- LDAP_ORGANISATION=ldap
- LDAP_DOMAIN=ldap.com
- LDAP_ADMIN_PASSWORD=Admin100%
ports:
- 389:389
- 636:636
networks:
- ldap-net
ldapui:
image: osixia/phpldapadmin:latest
container_name: ldapui
privileged: true
environment:
- TZ=Asia/Shanghai
- PHPLDAPADMIN_HTTPS=false
- PHPLDAPADMIN_LDAP_HOSTS=ldap
ports:
- 1443:443
- 81:80
depends_on:
- ldap
networks:
- ldap-net
networks:
ldap-net:
driver: bridge
pom.xml引入
org.springframework.boot
spring-boot-starter-data-ldap
java文件
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.ldap.query.LdapQueryBuilder;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
public class LdapConfig {
private static LdapConfig instance;
private LdapConfig() {}
public static LdapConfig getInstance() {
if (instance == null) {
synchronized (LdapConfig.class) {
if (instance == null) {
instance = new LdapConfig();
}
}
}
return instance;
}
private LdapTemplate ldapTemplate;
/**
* String ldapUrl = "ldap://127.0.0.1:389";
* String ldapBase = "dc=ldap,dc=com";
* String ldapUsername = "cn=admin,dc=ldap,dc=com";
* String ldapPassword = "123456";
*
*/
private void init() {
try {
SettingDao settingDao = (SettingDao) SpringContextUtil.getBean("settingDao");
Map dataMap = getSettingByKeys(settingDao,"ldapUrl","ldapBase","ldapUsername","ldapPassword");
String ldapUrl = (String)dataMap.get("ldapUrl");
String ldapBase = (String)dataMap.get("ldapBase");
String ldapUsername = (String)dataMap.get("ldapUsername");
String ldapPassword = (String)dataMap.get("ldapPassword");
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(ldapUrl);
contextSource.setBase(ldapBase);
contextSource.setUserDn(ldapUsername);
contextSource.setPassword(ldapPassword);
contextSource.setPooled(true);
contextSource.afterPropertiesSet();
Map config = new HashMap<>(1);
config.put("java.naming.ldap.attributes.binary", "objectGUID");
contextSource.setBaseEnvironmentProperties(config);
this.ldapTemplate = new LdapTemplate(contextSource);
ldapTemplate.setIgnorePartialResultException(true);
} catch (Exception e) {
log.error("LDAP 服务连接异常", e);
throw new I18nServerEndException("common.tips_32");
}
}
public boolean verifyUser(String userName, String password) {
EqualsFilter ef = new EqualsFilter("uid", userName);
try {
return getLdapTemplate().authenticate("", ef.toString(), password);
} catch (Exception e) {
log.error("LDAP 服务连接异常", e);
throw new I18nServerEndException("common.tips_32");
}
}
public List
docker-compose方式搭建
version: '3'
services:
sftp:
image: atmoz/sftp
volumes:
- ./test/:/home/foo/
ports:
- "2222:22"
privileged: true
command: foo:123456:1002
镜像作者的设定应该是把映射目录作为根目录(监狱),根目录(./test)是不能有写权限的,需要在下面再建一个子目录.
./test文件夹授权755,在test目录下再新建一个文件夹,比如upload, 把需要上传的文件放置在upload中,并且修改upload权限为777,例如:
mkdir upload
chmod 777 upload
pom.xml引入
com.jcraft
jsch
0.1.55
commons-io
commons-io
2.8.0
java文件
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.Vector;
@Slf4j
public class SFTPUtils {
public static ChannelSftp newInstance() throws IOException{
String nbiFtpIp = String.valueOf(DeviceConstants.cacheMap.get("nbiFtpIp"));
String userName = String.valueOf(DeviceConstants.cacheMap.get("nbiFtpUsername"));
String password = String.valueOf(DeviceConstants.cacheMap.get("nbiFtpPassword"));
String[] split = nbiFtpIp.split(":");
String host = split[0];
int port = split.length == 2 ? Integer.parseInt(split[1]) : 22;
return newInstance(nbiFtpIp, userName, password, port);
}
public static ChannelSftp newInstance(String hostname,String username,String password,int port) throws IOException {
//创建JSch对象
JSch jsch = new JSch();
Channel channel = null;
Session session = null;
int retryCount = 5;
int connectTimeout = 10000;//10 seconds
boolean connected = false;
while (retryCount > 0 && !connected) {
try {
session = jsch.getSession(username, hostname, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 为Session对象设置properties
session.connect(connectTimeout); // 通过Session建立链接
channel = session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
connected = true;
} catch (Exception e) {
retryCount--;
log.warn("Failed to connect to SFTP server. Retrying in 5 seconds...");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
log.error("",ex);
}
}
}
if (connected) {
log.info("Connect to SFTP server {} successfully.",hostname);
return (ChannelSftp) channel;
} else {
log.error("Failed to connect to SFTP server after 5 retries.");
throw new IOException("Failed to connect to SFTP server.");
}
}
/**
* 上传文件到FTP
*/
public static void upload(ChannelSftp chSftp,String fileName, InputStream inputStream) throws IOException {
try {
chSftp.put(inputStream, fileName);
log.info("上传文件{}成功。", fileName);
} catch (Exception e) {
log.error("上传文件{}失败({})。", fileName, e.getMessage(),e);
} finally {
try {
inputStream.close();
} catch (Exception ex) {
log.error("上传文件失败",ex);
}
}
}
public static void downLoad(ChannelSftp chSftp, String fullFileName,OutputStream outputStream) {
try {
chSftp.get(fullFileName, outputStream);
log.info("下载文件{}成功。", fullFileName);
} catch (Exception e) {
log.error("下载文件{}失败({})。", fullFileName, e.getMessage(),e);
}
}
/**
* 级联创建目录
* @param chSftp
* @param workingDirectory
* @throws Exception
*/
public static void changeWorkingDirectory(ChannelSftp chSftp, String workingDirectory) throws Exception {
String[] directories = workingDirectory.split("/");
for (String directory : directories) {
if (StringUtils.isBlank(directory)) {
continue;
}
try{
chSftp.cd(directory);
}catch(SftpException ex){
chSftp.mkdir(directory);
chSftp.cd(directory);
}
log.info("创建 {} 成功",directory);
}
}
//退出sftp
public static void closeChannel(Channel channel){
try {
if (channel != null) {
if (channel.isConnected()) {
Session session = channel.getSession();
if (session.isConnected()) {
session.disconnect();
}
channel.disconnect();
}
}
} catch (JSchException e) {
}
}
public static Vector listFiles(ChannelSftp chSftp, String workingDirectory){
try{
return chSftp.ls(workingDirectory);
}catch(SftpException ex){
return null;
}
}
public static boolean deleteFile(ChannelSftp chSftp, String fullPathName){
try {
chSftp.rm(fullPathName);
return true;
} catch (SftpException e) {
return false;
}
}
public static boolean removeDirectory(ChannelSftp chSftp, String pathName){
try {
Vector lsEntries = listFiles(chSftp, pathName);
if(lsEntries != null && !lsEntries.isEmpty()){
for (ChannelSftp.LsEntry lsEntry : lsEntries) {
if (!lsEntry.getAttrs().isDir()) {
deleteFile(chSftp, pathName + "/" + lsEntry.getFilename());
} else if (!lsEntry.getFilename().equals(".") && !lsEntry.getFilename().equals("..")) {
removeDirectory(chSftp, pathName + "/" + lsEntry.getFilename());
}
}
}
chSftp.rmdir(pathName);
return true;
} catch (SftpException e) {
return false;
}
}
public static void main(String[] args) {
ChannelSftp channelSftp = null;
try {
channelSftp = newInstance("127.0.0.1", "test", "123456", 2222);
System.out.println(channelSftp.pwd());
// changeWorkingDirectory(channelSftp, "xxx/test/1");
// upload(channelSftp, "1.txt", new ByteArrayInputStream("hello world".getBytes()));
// channelSftp.rm("xxx/test/1/1.txt");
// channelSftp.rmdir("xxx/test/1");
System.out.println(removeDirectory(channelSftp, "xxx/test/1"));
// System.out.println(channelSftp.ls("xxx/test/1"));
} catch (Exception e) {
e.printStackTrace();
} finally {
closeChannel(channelSftp);
}
}
}
分v1,v2c,v3版本
yum install net-snmp net-snmp-utils
systemctl enable snmpd.service
systemctl start snmpd.service
netstat -anp | grep 161
systemctl status snmpd.service
//增加两个配置项
cd /etc/snmp/snmpd.conf
rwuser test2
cd /etc/snmp/
mkdir snmptrapd.conf
# Example configuration file for snmptrapd
#
# No traps are handled by default, you must edit this file!
#
authCommunity log,execute,net public
# traphandle SNMPv2-MIB::coldStart /usr/bin/bin/my_great_script cold
#traphandle SNMPv2-SMI::enterprises /etc/snmp/lognotify
createUser -e 0x8000137001C0A842D64CE2B7CF test2 MD5 "12345678" DES "12345678"
authUser log,execute,net test2
snmptrapd -df -C -c /etc/snmp/snmptrapd.conf -Lo
pom.xml引入
org.snmp4j
snmp4j
2.7.0
java文件
接口ISnmpService 和SnmpInfo 实体类
import com.omc.nbi.dto.SnmpInfo;
import org.snmp4j.PDU;
import org.snmp4j.Target;
import org.snmp4j.smi.VariableBinding;
import java.util.List;
public interface ISnmpService {
VariableBinding getVariableBinding(String key, String value);
Target createTarget(SnmpInfo snmpInfo);
PDU createPDU(List variableBindings, int type);
void sendTrapRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception;
void sendInformRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception;
}
@Data
public class SnmpInfo {
private String ip;
private String port;
private String community = "public";
private int retries = 0;
private long timeout = 1000;
private String version = "v2c";
//add parameters for snmp v3
private String securityName;
private String authProtocol = AuthProtocol.MD5.toString();
private String authKey;
private String privProtocol = PrivProtocol.DES.toString();
private String privKey;
}
BaseSnmpService 基础接口实现
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public abstract class BaseSnmpService implements ISnmpService{
//iso(1).org(3).dod(6).internet(1).private(4).enterprises(1).imap(9955).omctr(11).northbound(2).northboundfault(1).northboundfaultnotification(1).snmpv2(2).
public static String snmpTrapPreFix = "1.3.6.1.4.1.9955.11.2.1.1.2.";
public static Map snmpTrapMap = new HashMap<>();
static {
snmpTrapMap.put("alarmSeq", 11);
snmpTrapMap.put("deviceObjectId", 12);
snmpTrapMap.put("domain", 13);
snmpTrapMap.put("alarmIdentifier", 14);
snmpTrapMap.put("alarmRaisedTime", 15);
snmpTrapMap.put("alarmChangedTime", 16);
snmpTrapMap.put("faultLocation", 17);
snmpTrapMap.put("managedObjectInstance", 18);
snmpTrapMap.put("eventType", 19);
snmpTrapMap.put("probableCause", 20);
snmpTrapMap.put("specificProblem", 21);
snmpTrapMap.put("additionalText", 22);
snmpTrapMap.put("additionalInformation", 23);
snmpTrapMap.put("perceivedSeverity", 24);
snmpTrapMap.put("alarmConfirm", 25);
snmpTrapMap.put("alarmCategory", 26);
}
protected static TransportMapping transport = null;
protected static Snmp snmp = null;
@Override
public PDU createPDU(List variableBindings, int type) {
PDU pdu = new PDU();
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID("1.3.6.1.4.1")));
for (VariableBinding vb : variableBindings) {
pdu.add(vb);
}
pdu.setType(type);
return pdu;
}
@Override
public VariableBinding getVariableBinding(String key, String value){
Integer index = snmpTrapMap.get(key);
if(index == null) return null;
return new VariableBinding(
new OID(snmpTrapPreFix.concat(String.valueOf(index))),
new OctetString(value)
);
}
protected static Snmp initSnmp() throws Exception {
if(snmp != null) return snmp;
try {
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
} catch (Exception e) {
log.error("snmp初始化失败:", e);
throw new Exception("访问snmp错误:snmp初始化失败");
}
return snmp;
}
public static void closeSnmp() throws Exception {
if (transport != null) transport.close();
if (snmp != null) snmp.close();
}
@Override
public void sendTrapRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception {
throw new UnsupportedOperationException("snmp "+snmpInfo.getVersion()+" trap request not supported");
}
@Override
public void sendInformRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception {
throw new UnsupportedOperationException("snmp "+snmpInfo.getVersion()+" inform request not supported");
}
}
import cn.hutool.json.JSONUtil;
import com.omc.nbi.dto.SnmpInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.Target;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import java.util.List;
@Slf4j
public class SnmpV1Service extends BaseSnmpService {
static {
try {
snmp = initSnmp();
} catch (Exception e) {
log.error("snmp 对象初始化失败:", e);
}
}
@Override
public PDU createPDU(List variableBindings, int type) {
PDUv1 pdu = new PDUv1();
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID("1.3.6.1.4.1")));
for (VariableBinding vb : variableBindings) {
pdu.add(vb);
}
pdu.setType(type);
return pdu;
}
@Override
public Target createTarget(SnmpInfo snmpInfo) {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(snmpInfo.getCommunity()));
// Address address = GenericAddress.parse(listenAddress);
UdpAddress udpAddress = new UdpAddress(snmpInfo.getIp().concat("/").concat(snmpInfo.getPort()));
target.setAddress(udpAddress);
// 通信不成功时的重试次数
target.setRetries(snmpInfo.getRetries());
// 超时时间
target.setTimeout(snmpInfo.getTimeout());
// snmp版本
target.setVersion(SnmpConstants.version1);
return target;
}
@Override
public void sendTrapRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception {
Target target = createTarget(snmpInfo);
// 创建 PDU
PDU pdu = createPDU(variableBindings, PDU.V1TRAP);
log.info("==================================");
log.info(JSONUtil.toJsonStr(pdu));
log.info("==================================");
try {
snmp.send(pdu, target);
} catch (Exception e) {
log.error("trap报文发送失败:", e);
throw new Exception("访问snmp错误:trap报文发送失败");
}
}
}
import cn.hutool.json.JSONUtil;
import com.omc.nbi.dto.SnmpInfo;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import java.util.List;
@Slf4j
public class SnmpV2cService extends BaseSnmpService{
static {
try {
snmp = initSnmp();
} catch (Exception e) {
log.error("snmp 对象初始化失败:", e);
}
}
@Override
public Target createTarget(SnmpInfo snmpInfo) {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(snmpInfo.getCommunity()));
// Address address = GenericAddress.parse(listenAddress);
UdpAddress udpAddress = new UdpAddress(snmpInfo.getIp().concat("/").concat(snmpInfo.getPort()));
target.setAddress(udpAddress);
// 通信不成功时的重试次数
target.setRetries(snmpInfo.getRetries());
// 超时时间
target.setTimeout(snmpInfo.getTimeout());
// snmp版本
target.setVersion(SnmpConstants.version2c);
return target;
}
@Override
public void sendTrapRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception {
Target target = createTarget(snmpInfo);
// 创建 PDU
PDU pdu = createPDU(variableBindings, PDU.TRAP);
log.info("==================================");
log.info(JSONUtil.toJsonStr(pdu));
log.info("==================================");
try {
snmp.send(pdu, target);
} catch (Exception e) {
log.error("trap报文发送失败:", e);
throw new Exception("访问snmp错误:trap报文发送失败");
}
}
@Override
public void sendInformRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception {
Target target = createTarget(snmpInfo);
// 创建 PDU
PDU pdu = createPDU(variableBindings, PDU.INFORM);
log.info("==================================");
log.info(JSONUtil.toJsonStr(pdu));
try {
ResponseEvent responseEvent = snmp.inform(pdu, target);
log.info("responseEvent:{}", JSONUtil.toJsonStr(responseEvent));
if(responseEvent == null || responseEvent.getResponse() == null || responseEvent.getResponse().getErrorStatus() != PDU.noError){
throw new Exception("访问snmp错误:inform报文响应失败,响应数据:"+JSONUtil.toJsonStr(responseEvent));
}
} catch (Exception e) {
log.error("inform报文发送失败:", e);
throw new Exception("访问snmp错误:inform报文发送失败");
}
}
}
import cn.hutool.json.JSONUtil;
import com.omc.nbi.dto.SnmpInfo;
import com.omc.nbi.service.snmp.common.AuthProtocol;
import com.omc.nbi.service.snmp.common.PrivProtocol;
import com.omc.nbi.util.SHA256Util;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Target;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import java.util.List;
@Slf4j
public class SnmpV3Service extends BaseSnmpService{
private static USM usm;
private static OctetString engineId;
static {
if(SnmpServiceFactory.v3Flag){
engineId = new OctetString(MPv3.createLocalEngineID());
} else {
String data = "80:00:13:70:01:C0:A8:42:D6:4C:E2:B7:CF";
engineId = new OctetString(data);
}
log.info("SnmpV3Service engineId:{}",engineId);
usm = new USM(SecurityProtocols.getInstance(), engineId, 0);
SecurityModels.getInstance().addSecurityModel(usm);
try {
snmp = initSnmp();
byte[] value = SHA256Util.hex2Byte(engineId.toString().replaceAll(":", ""));
snmp.setLocalEngine(value, 0, 0);
log.info("SnmpV3Service localEngineID:{}", SHA256Util.byte2Hex(snmp.getLocalEngineID()));
} catch (Exception e) {
log.error("snmp 对象初始化失败:", e);
}
}
@Override
public Target createTarget(SnmpInfo snmpInfo) {
UserTarget target = new UserTarget();
//SecurityLevel.NOAUTH_NOPRIV无认证与加密 SecurityLevel.AUTH_NOPRIV 有认证无加密 SecurityLevel.AUTH_PRIV有认证有加密
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
// target.setSecurityName(new OctetString(username)); //稍后添加
UdpAddress udpAddress = new UdpAddress(snmpInfo.getIp().concat("/").concat(snmpInfo.getPort()));
target.setAddress(udpAddress);
target.setVersion(SnmpConstants.version3);
target.setTimeout(snmpInfo.getTimeout());
target.setRetries(snmpInfo.getRetries());
return target;
}
@Override
public PDU createPDU(List variableBindings, int type) {
ScopedPDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID("1.3.6.1.4.1")));
for (VariableBinding vb : variableBindings) {
pdu.add(vb);
}
pdu.setType(type);
pdu.setContextEngineID(engineId);
return pdu;
}
/**
* 创建snmpv3用户:net-snmp-create-v3-user -a SHA -A abcd1234 -x AES -X abcd1234 watcher
* 参数详解:
* -a:密码加密方式,可选MD5|SHA|SHA-512|SHA-384|SHA-256|SHA-224
* -A:密码
* -x:设置隐私协议(DES | AES)
* -X:设置隐私协议密码短语
* 最后输入要创建的用户名
* 注意:密码长度至少要有8位
* @param variableBindings
* @param snmpInfo
* @throws Exception
*/
@Override
public void sendTrapRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception {
Target target = createTarget(snmpInfo);
target.setSecurityName(new OctetString(snmpInfo.getSecurityName()));
// 创建 PDU
PDU pdu = createPDU(variableBindings, PDU.TRAP);
log.info("==================================");
log.info(JSONUtil.toJsonStr(pdu));
log.info("==================================");
try {
UsmUser usmUser = getUsemUser(snmpInfo);
snmp.getUSM().addUser(new OctetString(snmpInfo.getSecurityName()), usmUser);
snmp.send(pdu, target);
} catch (Exception e) {
log.error("trap报文发送失败:", e);
throw new Exception("访问snmp错误:trap报文发送失败");
}
// finally {
// closeSnmp();
// }
}
@Override
public void sendInformRequest(List variableBindings, SnmpInfo snmpInfo) throws Exception {
Target target = createTarget(snmpInfo);
target.setSecurityName(new OctetString(snmpInfo.getSecurityName()));
// 创建 PDU
PDU pdu = createPDU(variableBindings, PDU.INFORM);
log.info("==================================");
log.info(JSONUtil.toJsonStr(pdu));
log.info("==================================");
try {
UsmUser usmUser = getUsemUser(snmpInfo);
snmp.getUSM().addUser(new OctetString(snmpInfo.getSecurityName()), usmUser);
snmp.inform(pdu, target);
} catch (Exception e) {
log.error("inform报文发送失败:", e);
throw new Exception("访问snmp错误:inform报文发送失败");
}
// finally {
// closeSnmp();
// }
}
private UsmUser getUsemUser(SnmpInfo snmpInfo){
AuthProtocol authProtocol = Enum.valueOf(AuthProtocol.class,snmpInfo.getAuthProtocol());
OID authenticationProtocol = null;
switch (authProtocol) {
case SHA:
authenticationProtocol = AuthSHA.ID;
break;
case SHA224:
authenticationProtocol = AuthHMAC128SHA224.ID;
break;
case SHA256:
authenticationProtocol = AuthHMAC192SHA256.ID;
break;
case SHA384:
authenticationProtocol = AuthHMAC256SHA384.ID;
break;
case SHA512:
authenticationProtocol = AuthHMAC384SHA512.ID;
break;
default:
authenticationProtocol = AuthMD5.ID;
break;
};
OID privacyProtocol = null;
PrivProtocol privProtocol = Enum.valueOf(PrivProtocol.class, snmpInfo.getPrivProtocol());
switch (privProtocol) {
case TRIPLEDES:
privacyProtocol = Priv3DES.ID;
break;
case AES128:
privacyProtocol = PrivAES128.ID;
break;
case AES192:
privacyProtocol = PrivAES192.ID;
break;
case AES256:
privacyProtocol = PrivAES256.ID;
break;
default:
privacyProtocol = PrivDES.ID;
break;
};
UsmUser usmUser = new UsmUser(
new OctetString(snmpInfo.getSecurityName()),
authenticationProtocol,
new OctetString(snmpInfo.getAuthKey()),
privacyProtocol,
new OctetString(snmpInfo.getPrivKey())
);
return usmUser;
}
}
snmptrap -v 3 -e 0x8000137001C0A842D64CE2B7CF00000000 -u test2 -l authPriv -a MD5 -A 12345678 -x DES -X 12345678 127.0.0.1 -C i
snmptrap -v 3 -e 0x8000137001C0A842D64CE2B7CF00000000 -a MD5 -A 12345678 -x DES -X 12345678 -l authPriv -u test2 127.0.0.1 0 linkUp.0
参考:
CentOS7下简单配置SNMPv3实践-腾讯云开发者社区-腾讯云
https://blog.itpub.net/9034054/viewspace-1974330/
使用MIB Builder 生成MIB文件_mlbb creator base-CSDN博客
规范网址:RFC 7515 - JSON Web Signature (JWS)
测试代码如下:
public static void main(String[] args) {
String hd = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
byte[] decode = cn.hutool.core.codec.Base64.decode(hd.getBytes());
System.out.println(new String(decode));
System.out.println(cn.hutool.core.codec.Base64.encodeUrlSafe(decode));
String pl = "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
decode = cn.hutool.core.codec.Base64.decode(pl.getBytes());
System.out.println(new String(decode));
System.out.println(cn.hutool.core.codec.Base64.encodeUrlSafe(decode));
//eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ
String enKey = "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow";
decode = cn.hutool.core.codec.Base64.decode(enKey.getBytes());
// System.out.println(new String(decode,StandardCharsets.UTF_8));
String sn = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
String token = hd + "." + pl + "." + sn;
boolean verify = JWT.of(token).setKey(decode).verify();
System.out.println(token);
System.out.println(verify);
String token = JWT.create().setKey(decode)
.setHeader("typ", "JWT")
.setHeader("alg", "HS256")
.setPayload("iss", "joe")
.setPayload("exp", 1300819380)
.setPayload("http://example.com/is_root", true)
.sign();
System.out.println(token);
verify = JWT.of("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.lliDzOlRAdGUCfCHCPx_uisb6ZfZ1LRQa0OJLeYTTpY").setKey(decode).verify();
System.out.println(verify);
System.out.println("===========hs256 签名1====================");
String sign = JWTSignerUtil.hs256(decode).sign(hd, pl);
System.out.println(sign);
System.out.println("===========hs256 签名2====================");
sign = JWTSignerUtil.createSigner("HS256", decode).sign(hd, pl);
System.out.println(sign);
System.out.println("===========es256 签名3====================");
String id = "ES256";
KeyPair keyPair = KeyUtil.generateKeyPair(AlgorithmUtil.getAlgorithm(id));
PrivateKey privateKey = keyPair.getPrivate();
String publicKey = keyPair.getPublic().toString();
System.out.println("privateKey: " + privateKey + ",publicKey: " + publicKey);
sign = JWTSignerUtil.createSigner(id, keyPair).sign(hd, pl);
System.out.println(sign);
*
*/
String STANDARD_DATE_FORMAT_UTC = "yyyy-MM-dd HH:mm:ss";
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(STANDARD_DATE_FORMAT_UTC);
String format = simpleDateFormat.format(date);
System.out.println(format);
}