一、给服务器和pc端安装SNMP
注意:电脑只有专业版和企业版才有SNMP服务
https://blog.csdn.net/weixin_40720438/article/details/79740839
二、使用 mibbrowser工具进行SNMP测试
工具下载(内涵部分oid使用):https://pan.baidu.com/s/1Gvy3F9TPawnRoXWcPiavUQ 提取码:syq1
解压后打开文件
win10打开SNMP服务和部分Oid 文档 里面具体操作步骤
三、Unity获取内存占用率
导入Snmp所需的dll
https://pan.baidu.com/s/1dlUWDMd-HMPcJtjCg-Ta6A 提取码:syq1
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using SnmpSharpNet;
public class Test : MonoBehaviour {
static string ip= "127.0.0.1";
public InputField ipField;
public Text txt;
public Button btn;
// Use this for initialization
void Start () {
btn.onClick.AddListener(BtnEvent);
}
void BtnEvent()
{
ip = ipField.text;
string text = GetUsePhysicalMemoryOfSNMP().ToString();
txt.text = text;
Debug.Log("内存使用:" + text);
}
/// <summary>
/// snmp获取本地当前win电脑内存使用
/// snmp端口号161 团体名称:public
/// 注意电脑上要开启snmp服务
/// 获取数据具有延迟性,win的snmp机制所致
/// </summary>
/// <returns>返回系统物理内存使用(单位:G)</returns>
public static float GetUsePhysicalMemoryOfSNMP()
{
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ip);
UdpTarget SnmpSender = new UdpTarget(ipAdd, 161, 2000, 1);
Pdu tempSendPdu = new Pdu(PduType.Get);
float memoryF = float.MinValue;
AgentParameters AgentParam = new AgentParameters(SnmpVersion.Ver2, new OctetString("public"));
string oidRoot = ".1.3.6.1.2.1.25.2.3.1.3.";
int idx = 1;
SnmpV2Packet result = null;
while (true)
{
if (idx > 1000)
{
return float.MinValue;
}
string curRepOid = oidRoot + idx;
//Debug.Log("curRepOid:" + curRepOid);
tempSendPdu.VbList.Clear();
tempSendPdu.VbList.Add(curRepOid);
result = SnmpSender.Request(tempSendPdu, AgentParam) as SnmpV2Packet;
if (result != null && result.Pdu.ErrorIndex == 0)
{
string recVal = result.Pdu.VbList[0].Value.ToString();
if (recVal.ToLower().Replace(" ", "") == "physicalmemory")
{
break;
}
else
{
tempSendPdu.VbList.Clear();
idx++;
}
}
else
{
break;
}
}
string replayOID = "1.3.6.1.2.1.25.2.3.1.6." + idx;
tempSendPdu.VbList.Clear();
tempSendPdu.VbList.Add(replayOID);
result = SnmpSender.Request(tempSendPdu, AgentParam) as SnmpV2Packet;
if (result != null && result.Pdu.ErrorIndex == 0)
{
bool flag = float.TryParse(result.Pdu.VbList[0].Value.ToString(), out memoryF);
if (flag)
{
memoryF = memoryF * 65536 / 1024 / 1024 / 1024;
}
}
return memoryF;
}
}
输入服务器地址 运行:
只要在同一个局域网中,服务器安装了Snmp服务,都可访问到
这里分享几个通用oid,如果获取不到,因为不同设备MIB的oid可能不同,需要从设备厂家要MIB库查找对应oid
1.3.6.1.2.1.1.5.0 设备名称:
1.3.6.1.2.1.25.3.3.1.2.1 cpu占用率:
1.3.6.1.2.1.25.2.2.0 系统物理内存: 获取值/1024 ----- (计算方式)
1.3.6.1.2.1.25.2.3.1.6.8 内存占用率: 获取值* 65536 / 1024 / 1024 / 1024 ----(计算方式)1.3.6.1.2.1.25.1.6.0 系统进程数量: 本身卡顿3秒