1. Introduction to SNMP
SNMP is a protocol used to manage network devices. It is a standardized protocol used to monitor and manage network devices, including routers, switches, servers, printers and other devices.
The basic components of the SNMP protocol include:
Management Station: Usually a PC or server that monitors and manages network devices.
Management Agent: Software running on network devices is responsible for managing and monitoring network devices and providing information to management stations.
MIB (Management Information Base): A hierarchical database containing information about network devices. Each node of the MIB corresponds to an attribute or state of the network device.
SNMP protocol: a protocol used to transmit information between a management station and a management agent. The SNMP message contains the operation type, object identifier, and value. The SNMP protocol defines a series of operations through which the properties and status of network devices can be obtained, set and monitored. These operations include:
- 1. GET: Get the value of an attribute or state.
- 2. SET: Set the value of an attribute or state.
- 3. GETNEXT: Get the value of the next node.
- 4. GETBULK: Get the values of a set of nodes.
- 5. TRAP: Send a warning or notification to the management station.
The latest version of the SNMP protocol is SNMPv3, which provides security and access control mechanisms to protect the security and confidentiality of network devices.
Why use SNMP
With the rapid development of network technology, while the network is constantly popularizing, it has also brought some problems to network management: the number of network devices has increased in geometric ranges, making it increasingly difficult for network administrators to manage devices; at the same time, as a complex distributed system, the network has been continuously expanding its coverage area, which also makes it extremely difficult to conduct real-time monitoring and troubleshooting of these devices.
There are many types of network equipment, and the management interfaces (such as command line interfaces) provided by different equipment manufacturers vary, which makes network management more complicated.
In this context, SNMP came into being, a network management standard protocol widely used in TCP/IP networks. This protocol can support network management systems to monitor whether devices connected to the network have any management concerns. Through the method of "using networks to manage networks": network administrators can use the SNMP platform to complete information query, information modification and troubleshooting on any node on the network, and their work efficiency is improved.
Blocking the physical differences between devices, SNMP only provides the most basic function set, making management tasks independent of the physical characteristics and network types of managed devices, so that unified management of different devices can be achieved, with low management costs.
The design is simple and the operation cost is low. SNMP adopts the "simple as possible" design idea. The software/hardware added to the device, the type of packets and the format of packets are all simple, so the impact and cost of running SNMP on the device are minimized.
Basic components of SNMP
The basic components of SNMP include the network management system NMS (Network Management System), agent processes (Agent), managed objects (Managed Objects) and management information base.
Advantages
- 1. Simple and easy to use: SNMP protocol is a simple and easy to use protocol, which is easy to use and easy to manage.
- 2. Standardization: The SNMP protocol is a standardized protocol that is widely used in the field of network management.
- 3. Real-time monitoring: The SNMP protocol can monitor the performance and status of network equipment in real time, and promptly discover and solve problems.
- 4. Centralized management: The SNMP protocol can uniformly manage network equipment through centralized management tools to improve management efficiency and management level.
- 5. Scalability: The SNMP protocol has good scalability and can adapt to different network management needs and application scenarios.
application
Network device management: SNMP protocol is a commonly used network device management protocol used to monitor and manage network devices such as routers, switches, servers and printers.
Network performance monitoring: The SNMP protocol can monitor the performance indicators of network equipment in real time, such as CPU utilization, memory utilization, network traffic, etc., help administrators discover and solve performance problems in a timely manner.
Security Management: The SNMP protocol can be used to monitor and manage operating systems, databases, applications and other systems and software to ensure the normal operation and efficient management of the system.
Cloud computing management: The SNMP protocol can be used for network management and monitoring in cloud computing environments, helping administrators to discover and solve problems in cloud environments in a timely manner.
2. Development integration
<!-- /artifact/org.snmp4j/snmp4j --> <dependency> <groupId>org.snmp4j</groupId> <artifactId>snmp4j</artifactId> <version>2.7.0</version> </dependency>
/artifact/org.snmp4j/snmp4j
The latest version is currently 3.7.7, and currently, version 2.7.0 is used as an example.
3. Basic OID
import ; /** * snmp protocol tool class configuration file */ public class SnmpConfig { private SnmpConfig(){} /** * get cpu description information */ public static final String SNMPGET_CPUDESC=".1.3.6.1.2.1.1.1.0.255.1"; /** * walk network interface description */ public static final String SNMPWALK_IFDESCR=".1.3.6.1.2.1.2.2.1.2"; /** * walk interface physical address */ public static final String SNMPWALK_IFPHYSADDRESS=".1.3.6.1.2.1.2.2.1.6"; /** * get IO load */ public static final String SNMPGET_IOLOAD=".1.3.6.1.2.1.1.1.0.255.0"; /** * Hard disk size */ public static final String SNMPGET_DSKTOTAL=".1.3.6.1.4.1.2021.9.1.6"; /** * walk cpu load */ public static final String SNMPWALK_HRPROCESSLOAD=".1.3.6.1.2.1.25.3.3.1.2"; /** * walk cpu idle rate */ public static final String SNMPWALK_SSCPUIDLE=".1.3.6.1.4.1.2021.11.11.0"; /** * walk storage device description */ public static final String SNMPWALK_HRSTORAGEDESCR=".1.3.6.1.2.1.25.2.3.1.3"; /** * walk storage device description */ public static final String SNMPWALK_AHU=".1.3.6.1.2.1.25.2.3.1.4"; /** * walk storage device description */ public static final String SNMPWALK_AUR=".1.3.6.1.2.1.25.2.3.1.5"; /** *walk storage device usage size * How much memory is used, divided by the total capacity is the occupancy rate */ public static final String SNMPWALK_HRSTORAGEUSED=".1.3.6.1.2.1.25.2.3.1.6"; /** *walk memory usage * Memory occupied by each process */ public static final String SNMPWALK_MEMORY_WIN=".1.3.6.1.2.1.25.5.1.1.2"; /** *walk storage device usage * */ public static final String SNMPWALK_DSKPERCENT=".1.3.6.1.4.1.2021.9.1.9"; /** * get get memory size */ public static final String SNMPGET_HRMEMORYSIZE=".1.3.6.1.2.1.25.2.2.0"; /** * Get the machine name */ public static final String SNMPWALK_SYSNAME=".1.3.6.1.2.1.1.5"; /** * Performance parameter ID-cpu usage rate */ public static final Integer PERFORMANCE_PARAM_CPUUSAGE=1; /** * Performance parameter ID - memory usage */ public static final Integer PERFORMANCE_PARAM_MEMORYUSAGE=2; /** * Performance parameter ID-io bandwidth occupancy rate */ public static final Integer PERFORMANCE_PARAM_IOUSAGE=3; /** * decimal type 1024, used for division calculation */ public static final BigDecimal DEVIDE_NUM=new BigDecimal("1024"); /** * Get the memory size */ public static final String GET_MEMORY="1.3.6.1.2.1.25.2.2.0"; /** * Get the system description */ public static final String SYS_DSC="1.3.6.1.2.1.1.1.0"; /** * Get the number of network interfaces */ public static final String IF_NUM="1.3.6.1.2.1.2.1.0"; /** * Get the CPU core number */ public static final String CPU_NUM="1.3.6.1.2.1.25.3.3.1.2"; }
4. SNMP information collection tool category
import .; import .; import org.; import org.; import org.; import org.; import org.; import org.; import org.; import org.; import org.; import org.; import org.; import org.; import org.; import ; import ; import ; import ; import ; /** * snmp protocol tool class * Get server CPU, memory, and hard disk usage */ public class SnmpUtil { private static Logger logger = (); private static Snmp snmp = null; private CommunityTarget target; @SuppressWarnings("squid:S3010") public SnmpUtil(String intranetDeviceIp, Integer snmpPort) throws IOException { if (snmp == null) { snmp = new Snmp(new DefaultUdpTransportMapping()); (); } //Initialize CommunityTarget target = new CommunityTarget(); (new OctetString("public")); (SnmpConstants.version2c); (new UdpAddress(intranetDeviceIp + "/" + snmpPort)); (1000); (1); } private ResponseEvent snmpGet(String oid) { PDU pdu = new PDU(); (new VariableBinding(new OID(oid))); ResponseEvent re=null; try { re = (pdu, target); }catch (Exception e){ ("snmpGet Exception"+()); } return re; } private List<TableEvent> snmpWalk(String oid) { TableUtils utils = new TableUtils(snmp, new DefaultPDUFactory()); OID[] columnOid = new OID[]{new OID(oid)}; return (target, columnOid, null, null); } /** * Get the CPU load * @return */ public BigDecimal getCpuUsage() { List<TableEvent> list = snmpWalk(SnmpConfig.SNMPWALK_HRPROCESSLOAD); BigDecimal usage = new BigDecimal("0"); for (TableEvent tableEvent : list) { try { String s=().split("=")[3].split("]")[0].trim(); if (!"-4,exception".equals(s)){ usage=(new BigDecimal(().split("=")[3].split("]")[0].trim())); }else { return new BigDecimal("-1"); } } catch (Exception e) { ("Failed to get the CPU load"+()); return new BigDecimal("-1"); } } usage = (new BigDecimal(()),2,BigDecimal.ROUND_HALF_UP); return usage; } /** * Get CPU usage rate * @return */ public BigDecimal getCpu() { BigDecimal totalSize; ResponseEvent responseEvent = snmpGet(SnmpConfig.SNMPWALK_SSCPUIDLE); if(responseEvent!=null&&()!=null){ totalSize=new BigDecimal(().toString().split("=")[4].split("]")[0].trim()); }else { return new BigDecimal("-1"); } return new BigDecimal("100").subtract(totalSize); } /** * Get disk occupancy * @return */ public BigDecimal getDiskUsageForWindows() { BigDecimal multiply=new BigDecimal("-1"); try { BigDecimal diskSize = getDiskSize(); BigDecimal diskUsed = getDiskUsed(); if ((diskSize)<0&&(diskUsed)<0){ multiply = getDiskUsed().divide(getDiskSize(), 3, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)); } }catch (Exception e){ ("Get windows disk occupation exception"+()); } return multiply; } /** * Get disk occupancy * @return */ public BigDecimal getDiskUsage() { BigDecimal totalSize=null; //org.[index=null,vbs=null,status=-1,exception=null,report=null] List<TableEvent> tableEvents = snmpWalk(SnmpConfig.SNMPWALK_DSKPERCENT); if(()){ totalSize = getDiskUsageForWindows(); return totalSize; } for(int i=0;i<();i++){ if ("-1,exception".equals((i).toString().split("=")[3].split("]")[0].trim())){ return new BigDecimal("-1"); } String s=(i).toString().split("=")[3].split("]")[0].trim(); if (!"-4,exception".equals(s)){ totalSize= new BigDecimal((i).toString().split("=")[3].split("]")[0].trim()); }else { return new BigDecimal("-1"); } } return totalSize; } /** * Get memory usage * @return */ public BigDecimal getMemoryUsage(){ BigDecimal usage; BigDecimal totalSize; try { ResponseEvent event = snmpGet(SnmpConfig.SNMPGET_HRMEMORYSIZE); if (event != null && () != null) { totalSize = new BigDecimal(().toString().split("=")[4].split("]")[0].trim()); usage = getMemoryUsed(); return (new BigDecimal("100")).divide(totalSize, 0, BigDecimal.ROUND_HALF_UP); } else { return new BigDecimal("-1"); } }catch (Exception e){ ("Failed to get memory usage"+()); return new BigDecimal("-1"); } } /** * Get memory used * @return */ public BigDecimal getMemoryUsed(){ List<TableEvent> list=snmpWalk(SnmpConfig.SNMPWALK_HRSTORAGEDESCR); int index=0; BigDecimal usedMemory=new BigDecimal("0"); for(int i=0;i<();i++){ String trim = (i).toString().split("=")[3].split("]")[0].trim(); if(("Physical memory")){ //Linux system index=i; List<TableEvent> usedList=snmpWalk(SnmpConfig.SNMPWALK_HRSTORAGEUSED); usedMemory= new BigDecimal((index).toString().split("=")[3].split("]")[0].trim()); }else if (("Physical Memory")){ //windows system List<TableEvent> list1=snmpWalk(SnmpConfig.SNMPWALK_MEMORY_WIN); BigDecimal re=new BigDecimal("0"); for (int j=0;j<();j++){ String trim1 = (j).toString().split("=")[3].split("]")[0].trim(); BigDecimal b = new BigDecimal(trim1); re=(b); } return re; }else if(("Memory buffers")){ //Linux system index=i; List<TableEvent> usedList=snmpWalk(SnmpConfig.SNMPWALK_HRSTORAGEUSED); usedMemory= (new BigDecimal((index).toString().split("=")[3].split("]")[0].trim())); }else if(("Cached memory")){ //Linux system index=i; List<TableEvent> usedList=snmpWalk(SnmpConfig.SNMPWALK_HRSTORAGEUSED); usedMemory= (new BigDecimal((index).toString().split("=")[3].split("]")[0].trim())); } } return usedMemory; } /** * Get disk * @return */ public BigDecimal getDiskSize(){ List<TableEvent> list=snmpWalk(SnmpConfig.SNMPWALK_HRSTORAGEDESCR); BigDecimal diskSize=new BigDecimal(-1); if (!()){ diskSize=new BigDecimal("0"); List<TableEvent> usedList1=snmpWalk(SnmpConfig.SNMPWALK_AHU); List<TableEvent> usedList2=snmpWalk(SnmpConfig.SNMPWALK_AUR); for(int i=0;i<();i++){ boolean re=(i).toString().split("=")[3].split("]")[0].trim().contains(":")||(i).toString().split("=")[3].split("]")[0].trim().contains("/"); if(re){ diskSize=(new BigDecimal((i).toString().split("=")[3].split("]")[0].trim()).multiply(new BigDecimal((i).toString().split("=")[3].split("]")[0].trim())).divide(new BigDecimal("1073741824"),2,BigDecimal.ROUND_HALF_UP)); } } } return diskSize; } /** * Get disk used * @return */ public BigDecimal getDiskUsed(){ List<TableEvent> list=snmpWalk(SnmpConfig.SNMPWALK_HRSTORAGEDESCR); BigDecimal diskSize=new BigDecimal(-1); if (!()){ diskSize=new BigDecimal("0"); List<TableEvent> usedList1=snmpWalk(SnmpConfig.SNMPWALK_AHU); List<TableEvent> usedList2=snmpWalk(SnmpConfig.SNMPWALK_HRSTORAGEUSED); for(int i=0;i<();i++){ boolean re=(i).toString().split("=")[3].split("]")[0].trim().contains(":")||(i).toString().split("=")[3].split("]")[0].trim().contains("/"); if(re){ diskSize=(new BigDecimal((i).toString().split("=")[3].split("]")[0].trim()).multiply(new BigDecimal((i).toString().split("=")[3].split("]")[0].trim())).divide(new BigDecimal("1073741824"),2,BigDecimal.ROUND_HALF_UP)); } } } return diskSize; } /** * Get IO load * @return */ public Float getIOUsage(){ ResponseEvent event=snmpGet(SnmpConfig.SNMPGET_IOLOAD); if(event!=null&&()!=null){ float usage=(().toString().split("=")[4].split("]")[0].trim()); if(usage>1){ return usage; }else{ return usage*100; } } return null; } /** * Get the data of certain performance parameters * @param parameterId * @return */ public Object getData(Integer parameterId) { Object data=null; try{ if((SnmpConfig.PERFORMANCE_PARAM_CPUUSAGE)){ data=getCpuUsage(); }else if((SnmpConfig.PERFORMANCE_PARAM_MEMORYUSAGE)){ data=getMemoryUsage(); }else if((SnmpConfig.PERFORMANCE_PARAM_IOUSAGE)){ data=getIOUsage(); } }catch(Exception e){ ("Get performance parameters exception"+()); } return data; } /** * Get the device physical address * @return */ public String getMacAddress(){ try { List<TableEvent> list = snmpWalk(SnmpConfig.SNMPWALK_IFDESCR); int index = 0; for (int i = 0; i < (); i++) { if ((i).toString().split("=")[3].split("]")[0].trim().contains("eth")) { index = i; } } List<TableEvent> ifAddressList = snmpWalk(SnmpConfig.SNMPWALK_IFPHYSADDRESS); return (index).toString().split("=")[3].split("]")[0].trim(); }catch (Exception e){ ("Failed to obtain physical address"+()); return "failure"; } } /** * Get the device memory size Unit in GB * @return */ public String getMemoryDesc() { ResponseEvent event =snmpGet(SnmpConfig.SNMPGET_HRMEMORYSIZE); Long bytes =(event==null?"0":().toString().split("=")[4].split("]")[0].trim()); float gb =bytes/1024.0f/1024.0f; DecimalFormat decimalFormat =new DecimalFormat(".00"); return (gb)+"GB"; } /** * @throws IOException * Get CPU description information * @return */ public String getCpuDesc() throws IOException { ResponseEvent event=snmpGet(SnmpConfig.SNMPGET_CPUDESC); return event==null? "":().toString().split("=")[4].split("]")[0].trim().split(":")[1].trim(); } /** * Get the storage device size (the empty disk space is less than 100%) * @param deviceCode * @return */ public BigDecimal getDiskSize(String deviceCode){ List<TableEvent> list = snmpWalk(SnmpConfig.SNMPGET_DSKTOTAL); BigDecimal diskSize=new BigDecimal(-1); if (list!=null){ try { for (TableEvent tableEvent:list){ diskSize=new BigDecimal(().split("=")[3].split("]")[0].trim()).divide(SnmpConfig.DEVIDE_NUM).divide(SnmpConfig.DEVIDE_NUM,2,RoundingMode.HALF_UP); } }catch (Exception e){ ("Failed to get disk size"+()); } } if ((diskSize)>0){ diskSize = getDiskSize(); } return diskSize; } /** * Get the disk description * @param deviceCode * @return * @throws IOException */ public BigDecimal getDiskDesc(String deviceCode) { return getDiskSize(deviceCode).divide(SnmpConfig.DEVIDE_NUM,2,RoundingMode.HALF_UP).divide(SnmpConfig.DEVIDE_NUM,2,RoundingMode.HALF_UP); } /** * snmp protocol detection */ public boolean snmpCheck() { ResponseEvent re=snmpGet(".1.3.6.1.4.1.2021.255.1"); return re == null || () != null; } /** * Get the machine name * @return */ public String getSysName(){ String name=null; try{ List<TableEvent> list = snmpWalk(SnmpConfig.SNMPWALK_SYSNAME); if (list!=null){ for (TableEvent tableEvent:list){ name=(().split("=")[3].split("]")[0].trim()); } } }catch (Exception e){ ("Failed to obtain the machine name"+()); } return name; } /** * Get the total memory size (actual value) * @return */ public BigDecimal getMemoryTotalSize(){ try { ResponseEvent event = snmpGet(SnmpConfig.GET_MEMORY); if (event!=null&&()!=null){ String trim = ().toString().split("=")[4].split("]")[0].trim(); return new BigDecimal(trim).divide(SnmpConfig.DEVIDE_NUM,2, RoundingMode.HALF_UP).divide(SnmpConfig.DEVIDE_NUM,2, RoundingMode.HALF_UP); }else { throw new RuntimeException("Failed to obtain memory information"); } } catch (Exception e) { ("Failed to get the total memory size"+()); } return new BigDecimal("-1"); } /** * Get the system description * @return */ public String getSysDsc(){ try { ResponseEvent event = snmpGet(SnmpConfig.SYS_DSC); if (event!=null&&()!=null){ return ().toString().split("=")[4].split("]")[0].trim(); }else { throw new RuntimeException("Failed to obtain system description information"); } } catch (Exception e) { ("Failed to obtain system description information"+()); } return "failure"; } /** * Get the number of interfaces * @return */ public Integer getIfNumber(){ try { ResponseEvent event = snmpGet(SnmpConfig.IF_NUM); if (event!=null&&()!=null){ String trim = ().toString().split("=")[4].split("]")[0].trim(); return (trim); }else { throw new RuntimeException("Failed to obtain interface information"); } } catch (Exception e) { ("Failed to get the number of interfaces"+()); } return -1; } /** * Get the number of CPU cores (n CPUs have n data) * @return */ public Integer getCpuNum(){ List<TableEvent> list = snmpWalk(SnmpConfig.CPU_NUM); Integer num=-1; if (list!=null){ num=(); } return num; } public static void main(String[] args) throws IOException { String snmpIp = "127.0.0.1"; Integer snmpPort = 161; SnmpUtil snmpUtil = new SnmpUtil(snmpIp, snmpPort); ("Machine Name"+()); ("Disk Size"+ ("devide")); ("Physical Address"+()); ("cpu "+()); } }
This is the article about Java using the snmp protocol to collect server information. For more information about Java snmp collection server information, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!