最近项目上需要使用SNMP协议进行通信,在网上找了好多资料。由于SNMP协议版本比较多 ,故找到的好多都不能兼容现在我需要的SNMPV1版本,然后需要的通信的产品的厂家提供的协议, 也没有提供太多的资料,就自己到网上找资料。走了许多的弯路,故记录一下。 首先是在网上找到了调试助手,参考了下面这篇文章
通过里面的操作我确定了我的通信协议是V1版本。
然后又找了下面这篇文章
里面使用的是v1版本的通信协议,能获取值,但是没有写如何设置Oid。我在chartgpt、文言一心和百度中找了好久都没发现。然后我灵光乍现,能不能将里面的获取修改为设置呢。然后进行了实验就成功了
nuget包
下面是代码
public static Dictionary<string, string> Set(string host, Dictionary<string, string> data)
{
//返回变量
Dictionary<string, string> dic = new Dictionary<string, string>();
OctetString community = new OctetString("private");
AgentParameters param = new AgentParameters(community);
param.Version = SnmpVersion.Ver1;
IpAddress agent = new IpAddress(host);
// Construct target
UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
// Pdu class used for all requests
Pdu pdu = new Pdu(PduType.Set);
foreach (var item in data)
{
Vb vb = new Vb();
vb.Oid = new Oid { item.Key };
vb.Value = new Integer32(item.Value);
pdu.VbList.Add(vb);
}
// Make SNMP request
SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
// If result is null then agent didn't reply or we couldn't parse the reply.
if (result != null)
{
if (result.Pdu.ErrorStatus == 0)
{
for (int i = 0; i < result.Pdu.VbList.Count; i++)
{
dic.Add(result.Pdu.VbList[i].Oid.ToString(), result.Pdu.VbList[i].Value.ToString());
}
}
}
target.Close();
return dic;
}