SnmpSharpNet in IronPython

I had a little bit of time today and figured I’ll try to use the library in IronPython.

I have used Python a lot a few years back for an SNMP based project and did like it a lot. It has a clean syntax and is very easy to learn.

It has taken about an hour of googling to find what I needed and in the end I had a fully working Get example:

import clr
clr.AddReference("System.Net")
clr.AddReferenceToFile("SnmpSharpNet.dll")
from SnmpSharpNet import *
from System.Net import *
 
param = AgentParameters()
param.Community.Set("public")
agentIP = IpAddress("127.0.0.1")
agent = UdpTarget(IpAddress.op_Explicit(agentIP), 161, 2000, 1)
pdu = Pdu(PduType.Get)
pdu.VbList.Add("1.3.6.1.2.1.1.1.0") # sysDescr
pdu.VbList.Add("1.3.6.1.2.1.1.2.0") # sysObjectID
pdu.VbList.Add("1.3.6.1.2.1.1.3.0") # sysUpTime
pdu.VbList.Add("1.3.6.1.2.1.1.4.0") # sysContact
pdu.VbList.Add("1.3.6.1.2.1.1.5.0") # sysName
 
result = None
 
try:
  result = agent.Request(pdu, param)
except:
  pass
 
# If result is null then agent didn't reply or we couldn't parse the reply.
if (result != None):
  # ErrorStatus other then 0 is an error returned by
  # the Agent - see SnmpConstants for error definitions
  if (result.Pdu.ErrorStatus != 0):
    # agent reported an error with the request
    print "Error in SNMP reply. Error ", result.Pdu.ErrorStatus, \
      "index ", result.Pdu.ErrorIndex
  else:
    # Reply variables are returned in the same order as they were added
    #  to the VbList
    print "sysDescr(", result.Pdu.VbList[0].Oid.ToString(), ") (", \
      SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type), "): ", \
      result.Pdu.VbList[0].Value.ToString()
    print "sysObjectID(", result.Pdu.VbList[1].Oid.ToString(), ") (", \
      SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type), "): ", \
      result.Pdu.VbList[1].Value.ToString()
    print "sysUpTime(", result.Pdu.VbList[2].Oid.ToString(), ") (", \
      SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) ,"): ", \
      result.Pdu.VbList[2].Value.ToString()
    print "sysContact(", result.Pdu.VbList[3].Oid.ToString(), ") (", \
      SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type) ,"): ", \
      result.Pdu.VbList[3].Value.ToString()
    print "sysName(", result.Pdu.VbList[4].Oid.ToString(), ") (", \
      SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type) ,"): ", \
      result.Pdu.VbList[4].Value.ToString()
else:
  print("No response received from SNMP agent.")
 
agent.Close()

Output is as expected:

c:\>IPythonSnmp.exe
sysDescr( 1.3.6.1.2.1.1.1.0 ) ( OctetString ):  "Dual core Intel notebook"
sysObjectID( 1.3.6.1.2.1.1.2.0 ) ( ObjectId ):  1.3.6.1.9.233233.1.1
sysUpTime( 1.3.6.1.2.1.1.3.0 ) ( TimeTicks ):  0d 7h 54m 1s 460ms
sysContact( 1.3.6.1.2.1.1.4.0 ) ( OctetString ):  "msinadinovic@users.sourceforge.net"
sysName( 1.3.6.1.2.1.1.5.0 ) ( OctetString ):  "milans-nbook"