/// <summary> /// SNMP GET-NEXT request /// </summary> /// <example>SNMP GET-NEXT request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "1.3.6.1.2.1.1" }); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair<Oid, AsnType> entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// </code> /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="oidList">List of request OIDs in string dotted decimal format.</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> GetNext(SnmpVersion version, string[] oidList) { if (!Valid) { return(null); } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { return(null); } Pdu pdu = new Pdu(PduType.GetNext); foreach (string s in oidList) { pdu.VbList.Add(s); } return(GetNext(version, pdu)); }
/// <summary> /// SNMP SET request /// </summary> /// <example>Set operation in SNMP version 1: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// List<Vb> vbList = new List<Vb>(); /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0 /// OctetString setValue = new OctetString("My personal toy"); /// vbList.Add(new Vb(setOid, setValue)); /// Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, list.ToArray()); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// Console.WriteLine("Success!"); /// } /// </code> /// /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2. /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="vbs">Vb array containing Oid/AsnValue pairs for the SET operation</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> Set(SnmpVersion version, Vb[] vbs) { if (!Valid) { return(null); } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { return(null); } Pdu pdu = new Pdu(PduType.Set); foreach (Vb vb in vbs) { pdu.VbList.Add(vb); } return(Set(version, pdu)); }
/// <summary> /// SNMP GET-BULK request /// </summary> /// <remarks> /// Performs a GetBulk SNMP v2 operation on a list of OIDs. This is a convenience function that /// calls GetBulk(Pdu) method. /// </remarks> /// <example>SNMP GET-BULK request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// Dictionary<Oid, AsnType> result = snmp.GetBulk(new string[] { "1.3.6.1.2.1.1" }); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair<Oid, AsnType> entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// </example> /// <param name="oidList">List of request OIDs in string dotted decimal format.</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> GetBulk(string[] oidList) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return(null); } Pdu pdu = new Pdu(PduType.GetBulk); pdu.MaxRepetitions = _maxRepetitions; pdu.NonRepeaters = _nonRepeaters; foreach (string s in oidList) { pdu.VbList.Add(s); } return(GetBulk(pdu)); }
/// <summary> /// Clone this object /// </summary> /// <returns>Copy of this object cast as type System.Object</returns> public override object Clone() { Pdu p = new Pdu(_vbs, Type, _requestId); if (Type == PduType.GetBulk) { p.NonRepeaters = _errorStatus; p.MaxRepetitions = _errorIndex; } else { p.ErrorIndex = ErrorIndex; p.ErrorStatus = ErrorStatus; } if (Type == PduType.V2Trap) { p.TrapObjectID.Set(TrapObjectID); p.TrapSysUpTime.Value = TrapSysUpTime.Value; } return(p); }
/// <summary> /// SNMP SET request /// </summary> /// <example>Set operation in SNMP version 1: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.SET; // type SET /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0 /// OctetString setValue = new OctetString("My personal toy"); /// pdu.VbList.Add(setOid, setValue); /// Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// Console.WriteLine("Success!"); /// } /// </code> /// /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2. /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> Set(SnmpVersion version, Pdu pdu) { if (!Valid) { return(null); // class is not fully initialized. } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { return(null); } try { _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); AgentParameters param = new AgentParameters(version, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { res.Add(v.Oid, v.Value); } _target.Close(); _target = null; return(res); } } } catch { } _target.Close(); _target = null; return(null); }
/// <summary> /// Check class equality with argument. /// /// Accepted argument types are: /// * Integer32 - compared against the request id /// * Pdu - compared against PduType, request id and contents of VarBind list /// </summary> /// <param name="obj">Integer32 or Pdu to compare</param> /// <returns>True if equal, otherwise false</returns> public bool Equals(Pdu obj) { if (obj == null) { return(false); } Pdu p = (Pdu)obj; if (p.Type != this.Type) { return(false); } if (p.RequestId != this.RequestId) { return(false); } if (p.VbCount != this.VbCount) { return(false); } foreach (Vb v in VbList) { if (!p.VbList.ContainsOid(v.Oid)) { return(false); } } foreach (Vb v in p.VbList) { if (!VbList.ContainsOid(v.Oid)) { return(false); } } return(true); }
public static AsnType Get(IPAddress agent, string community, string oid) { // Define agent parameters class AgentParameters agentParameters = new AgentParameters(SnmpVersion.Ver2, new OctetString(community)); // Construct target UdpTarget target = new UdpTarget(agent, 161, 2000, 1); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add(oid); //sysDescr // Make SNMP request var snmpResponse = target.Request(pdu, agentParameters) as SnmpV2Packet; AsnType result = null; // If result is null then agent didn't reply or we couldn't parse the reply. if (snmpResponse != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (snmpResponse.Pdu.ErrorStatus != 0) { // agent reported an error with the request throw new Exception($"Error in SNMP reply. Error {snmpResponse.Pdu.ErrorStatus} index {snmpResponse.Pdu.ErrorIndex}"); } else { result = snmpResponse.Pdu.VbList[0].Value; } } target.Close(); return(result); }
/// <summary> /// Decode received packet. This method overrides the base implementation that cannot be used with this type of the packet. /// </summary> /// <param name="buffer">Packet buffer</param> /// <param name="length">Buffer length</param> public override int Decode(byte[] buffer, int length) { int offset = 0; MutableByte buf = new MutableByte(buffer, length); offset = base.Decode(buffer, length); // parse community offset = snmpCommunity.Decode(buf, offset); // look ahead to make sure this is a TRAP packet int tmpOffset = offset; byte tmpAsnType = AsnType.ParseHeader(buffer, ref tmpOffset, out int headerLen); if (tmpAsnType != (byte)EPduType.Trap) { throw new SnmpException(string.Format("Invalid SNMP ASN.1 type. Received: {0:x2}", tmpAsnType)); } // decode protocol data unit offset = Pdu.Decode(buf, offset); return(offset); }
/// <summary> /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET, /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you /// are using). /// /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown. /// </summary> /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param> /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/> /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3 /// requests.</param> /// <param name="responseCallback">Callback that receives the result of the async operation.</param> /// <returns>True if async request was successfully initiated, otherwise false.</returns> public bool RequestAsync(Pdu pdu, IAgentParameters agentParameters, SnmpAsyncResponse responseCallback) { if (IsBusy) { return(false); // class is busy } _response = null; _response += responseCallback; _agentParameters = agentParameters; byte[] outPacket; if (agentParameters.Version == SnmpVersion.Ver3) { SecureAgentParameters secparams = (SecureAgentParameters)agentParameters; if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0) { // _response(AsyncRequestResult.AuthenticationError, null); return(false); } if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0) { // _response(AsyncRequestResult.PrivacyError, null); return(false); } _noSourceCheck = false; // this option is not valid for SNMP v3 requests ScopedPdu outPdu = new ScopedPdu(pdu); outPdu.ContextEngineId.Set(secparams.EngineId); outPdu.ContextName.Set(secparams.ContextName); SnmpV3Packet packet = new SnmpV3Packet(outPdu); secparams.InitializePacket(packet); try { if (secparams.HasCachedKeys) { outPacket = packet.encode(secparams.AuthenticationKey, secparams.PrivacyKey); } else { outPacket = packet.encode(); } } catch (Exception ex) { ex.GetType(); _response(AsyncRequestResult.EncodeError, packet); return(false); } } else if (agentParameters.Version == (int)SnmpVersion.Ver1) { AgentParameters param = (AgentParameters)agentParameters; _noSourceCheck = param.DisableReplySourceCheck; SnmpV1Packet packet = new SnmpV1Packet(); packet.Pdu.Set(pdu); packet.Community.Set(param.Community); try { outPacket = packet.encode(); } catch (Exception ex) { ex.GetType(); _response(AsyncRequestResult.EncodeError, packet); return(false); } } else if (agentParameters.Version == SnmpVersion.Ver2) { AgentParameters param = (AgentParameters)agentParameters; _noSourceCheck = param.DisableReplySourceCheck; SnmpV2Packet packet = new SnmpV2Packet(); packet.Pdu.Set(pdu); packet.Community.Set(param.Community); try { outPacket = packet.encode(); } catch (Exception ex) { ex.GetType(); _response(AsyncRequestResult.EncodeError, packet); return(false); } } else { throw new SnmpInvalidVersionException("Unsupported SNMP version."); } if (!base.RequestAsync(_address, _port, outPacket, outPacket.Length, _timeout, _retry, new SnmpAsyncCallback(AsyncResponse))) { return(false); } return(true); }
/// <summary> /// Make an async discovery request for protocol version 3. /// </summary> /// <param name="param">Agent parameters</param> /// <param name="callback">Callback method</param> /// <returns>True if operation was correctly initiated, otherwise false.</returns> public bool DiscoveryAsync(SecureAgentParameters param, SnmpAsyncResponse callback) { Pdu p = new Pdu(); return(RequestAsync(p, param, callback)); }
internal void AsyncResponse(AsyncRequestResult result, IPEndPoint peer, byte[] buffer, int buflen) { if (result != AsyncRequestResult.NoError) { _response(result, null); } else { if (buffer == null || buffer.Length <= 0 || buflen <= 0) { _response(AsyncRequestResult.NoDataReceived, null); return; } // verify packet if (_agentParameters.Version == (int)SnmpVersion.Ver1) { SnmpV1Packet packet = new SnmpV1Packet(); try { packet.Decode(buffer, buflen); } catch (Exception ex) { ex.GetType(); // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString()); _response(AsyncRequestResult.DecodeError, packet); return; } _response(AsyncRequestResult.NoError, packet); return; } else if (_agentParameters.Version == SnmpVersion.Ver2) { SnmpV2Packet packet = new SnmpV2Packet(); try { packet.Decode(buffer, buflen); } catch (Exception ex) { ex.GetType(); // Console.WriteLine("Exception while decoding SNMP packet: " + ex.ToString()); // MutableByte b = new MutableByte(buffer, buflen); // Console.WriteLine("Buffer length {0}", buflen); // SnmpConstants.DumpHex(b); _response(AsyncRequestResult.DecodeError, packet); return; } _response(AsyncRequestResult.NoError, packet); } else if (_agentParameters.Version == SnmpVersion.Ver3) { SnmpV3Packet packet = new SnmpV3Packet(); SecureAgentParameters secparams = (SecureAgentParameters)_agentParameters; secparams.InitializePacket(packet); try { if (secparams.HasCachedKeys) { packet.Decode(buffer, buflen, secparams.AuthenticationKey, secparams.PrivacyKey); } else { packet.Decode(buffer, buflen); } } catch { _response(AsyncRequestResult.DecodeError, packet); return; } if (!secparams.ValidateIncomingPacket(packet)) { _response(AsyncRequestResult.AuthenticationError, packet); } else { secparams.UpdateDiscoveryValues(packet); // update time, etc. values if (packet.USM.EngineId.Length > 0 && packet.USM.EngineBoots == 0 && packet.USM.EngineTime == 0) { Pdu p = new Pdu(); RequestAsync(p, _agentParameters, _response); } else { _response(AsyncRequestResult.NoError, packet); } } } } }
/// <summary>Make SNMP Request</summary> /// <remarks> /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET, /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you /// are using). /// /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown. /// </remarks> /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param> /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/> /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3 /// requests.</param> /// <returns>Appropriate SNMP packet class for the reply received (<see cref="SnmpV1Packet"/>, /// <see cref="SnmpV2Packet"/>, or <see cref="SnmpV3Packet"/>. Null value if there was an error /// with the request.</returns> /// <exception cref="SnmpAuthenticationException">Thrown on SNMPv3 requests when authentication password /// is not specified on authNoPriv or authPriv requests in SecureAgentParameters or if incoming packet /// authentication check failed. /// /// With SNMP ver1 and ver2c, authentication check fails when invalid community name is parsed in the reply.</exception> /// <exception cref="SnmpPrivacyException">Thrown on SNMPv3 requests when privacy password is not /// specified in SecureAgentParameters on authPriv requests.</exception> /// <exception cref="SnmpException">Thrown in following cases: /// /// * IAgentParameters.Valid() returned false. SnmpException.ErrorCode is set to SnmpException.InvalidIAgentParameters /// * No data received on request. SnmpException.ErrorCode is set to SnmpException.NoDataReceived /// * Invalid RequestId in reply. SnmpException.ErrorCode is set to SnmpException.InvalidRequestId /// </exception> public SnmpPacket Request(Pdu pdu, IAgentParameters agentParameters) { byte[] outPacket; if (agentParameters.Version == SnmpVersion.Ver3) { SecureAgentParameters secparams = (SecureAgentParameters)agentParameters; if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0) { throw new SnmpAuthenticationException("Authentication password not specified."); } if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0) { throw new SnmpPrivacyException("Privacy password not specified."); } _noSourceCheck = false; // this option is not valid for SNMP v3 requests ScopedPdu outPdu = new ScopedPdu(pdu); SnmpV3Packet packet = new SnmpV3Packet(outPdu); secparams.InitializePacket(packet); if (secparams.HasCachedKeys) { outPacket = packet.encode(secparams.AuthenticationKey, secparams.PrivacyKey); } else { outPacket = packet.encode(); } } else if (agentParameters.Version == SnmpVersion.Ver1) { AgentParameters param = (AgentParameters)agentParameters; if (!param.Valid()) { throw new SnmpException(SnmpException.InvalidIAgentParameters, "Invalid AgentParameters. Unable to process request."); } SnmpV1Packet packet = new SnmpV1Packet(); packet.Pdu.Set(pdu); packet.Community.Set(param.Community); outPacket = packet.encode(); _noSourceCheck = param.DisableReplySourceCheck; } else if (agentParameters.Version == SnmpVersion.Ver2) { AgentParameters param = (AgentParameters)agentParameters; if (!param.Valid()) { throw new SnmpException(SnmpException.InvalidIAgentParameters, "Invalid AgentParameters. Unable to process request."); } SnmpV2Packet packet = new SnmpV2Packet(); packet.Pdu.Set(pdu); packet.Community.Set(param.Community); _noSourceCheck = param.DisableReplySourceCheck; outPacket = packet.encode(); } else { throw new SnmpInvalidVersionException("Unsupported SNMP version."); } byte[] inBuffer = base.Request(_address, _port, outPacket, outPacket.Length, _timeout, _retry); if (inBuffer == null || inBuffer.Length <= 0) { throw new SnmpException(SnmpException.NoDataReceived, "No data received on request."); } // verify packet if (agentParameters.Version == SnmpVersion.Ver1) { SnmpV1Packet packet = new SnmpV1Packet(); AgentParameters param = (AgentParameters)agentParameters; packet.decode(inBuffer, inBuffer.Length); if (packet.Community != param.Community) { // invalid community name received. Ignore the rest of the packet throw new SnmpAuthenticationException("Invalid community name in reply."); } if (packet.Pdu.RequestId != pdu.RequestId) { // invalid request id. unmatched response ignored throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply."); } return(packet); } else if (agentParameters.Version == SnmpVersion.Ver2) { SnmpV2Packet packet = new SnmpV2Packet(); AgentParameters param = (AgentParameters)agentParameters; packet.decode(inBuffer, inBuffer.Length); if (packet.Community != param.Community) { // invalid community name received. Ignore the rest of the packet throw new SnmpAuthenticationException("Invalid community name in reply."); } if (packet.Pdu.RequestId != pdu.RequestId) { // invalid request id. unmatched response ignored throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply."); } return(packet); } else if (agentParameters.Version == SnmpVersion.Ver3) { SnmpV3Packet packet = new SnmpV3Packet(); SecureAgentParameters secparams = (SecureAgentParameters)agentParameters; secparams.InitializePacket(packet); if (secparams.HasCachedKeys) { packet.decode(inBuffer, inBuffer.Length, secparams.AuthenticationKey, secparams.PrivacyKey); } else { packet.decode(inBuffer, inBuffer.Length); } // first check if packet is a discovery response and process it if (packet.Pdu.Type == PduType.Report && packet.Pdu.VbCount > 0 && packet.Pdu.VbList[0].Oid.Equals(SnmpConstants.usmStatsUnknownEngineIDs)) { secparams.UpdateDiscoveryValues(packet); return(packet); } else { if (!secparams.ValidateIncomingPacket(packet)) { return(null); } else { secparams.UpdateDiscoveryValues(packet); // update time, etc. values return(packet); } } } return(null); }
/// <summary> /// Constructor. /// </summary> /// <param name="pdu">Initialize class from this <see cref="Pdu" /> class</param> public ScopedPdu(Pdu pdu) : base(pdu) { _contextEngineId = new OctetString(); _contextName = new OctetString(); }
/// <summary> /// Standard constructor. /// </summary> public SnmpV1Packet() : base(SnmpVersion.Ver1) { _snmpCommunity = new OctetString(); _pdu = new Pdu(); }
/// <summary>SNMP GET-BULK request</summary> /// <remarks> /// GetBulk request type is only available with SNMP v2c agents. SNMP v3 also supports the request itself /// but that version of the protocol is not supported by SimpleSnmp. /// /// GetBulk method will return a dictionary of Oid to value mapped values as returned form a /// single GetBulk request to the agent. You can change how the request itself is made by changing the /// SimpleSnmp.NonRepeaters and SimpleSnmp.MaxRepetitions values. SimpleSnmp properties are only used /// when values in the parameter Pdu are set to 0. /// </remarks> /// <example>SNMP GET-BULK request: /// <code> /// string snmpAgent = "10.10.10.1"; /// string snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.GETBULK; // type GETBULK /// pdu.VbList.Add("1.3.6.1.2.1.1"); /// pdu.NonRepeaters = 0; /// pdu.MaxRepetitions = 10; /// Dictionary<Oid, AsnType> result = snmp.GetBulk(pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair<Oid, AsnType> entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1 /// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms /// 1.3.6.1.2.1.1.4.0 = OctetString: "*****@*****.**" /// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook" /// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home" /// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms /// </code> /// </example> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> GetBulk(Pdu pdu) { if (!Valid) { if (!suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return(null); // class is not fully initialized. } try { pdu.NonRepeaters = nonRepeaters; pdu.MaxRepetitions = maxRepetitions; target = new UdpTarget(peerIP, peerPort, timeout, retry); } catch (System.Exception ex) { target = null; if (!suppressExceptions) { throw ex; } } if (target == null) { return(null); } try { AgentParameters param = new AgentParameters(ESnmpVersion.Ver2, new OctetString(community)); SnmpPacket result = target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if ( (v.Value.Type == SnmpConstants.SmiEndOfMIBView) || (v.Value.Type == SnmpConstants.SmiNoSuchInstance) || (v.Value.Type == SnmpConstants.SmiNoSuchObject)) { break; } if (res.ContainsKey(v.Oid)) { if (res[v.Oid].Type != v.Value.Type) { throw new SnmpException(SnmpException.EErrorCode.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString()); } else { res[v.Oid] = v.Value; } } else { res.Add(v.Oid, v.Value); } } target.Close(); target = null; return(res); } if (!suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } catch (System.Exception ex) { if (!suppressExceptions) { target.Close(); target = null; throw ex; } } target.Close(); target = null; return(null); }
/// <summary> /// SNMP SET request /// </summary> /// <example>Set operation in SNMP version 1: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.SET; // type SET /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0 /// OctetString setValue = new OctetString("My personal toy"); /// pdu.VbList.Add(setOid, setValue); /// Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// Console.WriteLine("Success!"); /// } /// </code> /// /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2. /// </example> /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> Set(SnmpVersion version, Pdu pdu) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return(null); // class is not fully initialized. } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return(null); } try { _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); } catch (Exception ex) { _target = null; if (!_suppressExceptions) { throw ex; } } if (_target == null) { return(null); } try { AgentParameters param = new AgentParameters(version, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if (res.ContainsKey(v.Oid)) { if (res[v.Oid].Type != v.Value.Type) { throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString()); } else { res[v.Oid] = v.Value; } } else { res.Add(v.Oid, v.Value); } } _target.Close(); _target = null; return(res); } else { if (!_suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } } catch (Exception ex) { if (!_suppressExceptions) { _target.Close(); _target = null; throw ex; } } _target.Close(); _target = null; return(null); }
/// <summary> /// SNMP GET request /// </summary> /// <example>SNMP GET request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "public"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.GET; // type GET /// pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); /// Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair<Oid, AsnType> entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// </code> /// </example> /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> Get(SnmpVersion version, Pdu pdu) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return(null); // class is not fully initialized. } // function only works on SNMP version 1 and SNMP version 2 requests if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2) { if (!_suppressExceptions) { throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only."); } return(null); } try { _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); } catch (Exception ex) { _target = null; if (!_suppressExceptions) { throw ex; } } if (_target == null) { return(null); } try { AgentParameters param = new AgentParameters(version, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if (version == SnmpVersion.Ver2 && (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE || v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT)) { if (!res.ContainsKey(v.Oid)) { res.Add(v.Oid, new Null()); } else { res.Add(Oid.NullOid(), v.Value); } } else { if (!res.ContainsKey(v.Oid)) { res.Add(v.Oid, v.Value); } else { if (res[v.Oid].Type == v.Value.Type) { res[v.Oid] = v.Value; // update value of the existing Oid entry } else { throw new SnmpException(SnmpException.OidValueTypeChanged, string.Format("Value type changed from {0} to {1}", res[v.Oid].Type, v.Value.Type)); } } } } _target.Close(); _target = null; return(res); } else { if (!_suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } } catch (Exception ex) { if (!_suppressExceptions) { _target.Close(); _target = null; throw ex; } } _target.Close(); _target = null; return(null); }
/// <summary> /// SNMP GET-BULK request /// </summary> /// <remarks> /// GetBulk request type is only available with SNMP v2c agents. SNMP v3 also supports the request itself /// but that version of the protocol is not supported by SimpleSnmp. /// /// GetBulk method will return a dictionary of Oid to value mapped values as returned form a /// single GetBulk request to the agent. You can change how the request itself is made by changing the /// SimpleSnmp.NonRepeaters and SimpleSnmp.MaxRepetitions values. SimpleSnmp properties are only used /// when values in the parameter Pdu are set to 0. /// </remarks> /// <example>SNMP GET-BULK request: /// <code> /// String snmpAgent = "10.10.10.1"; /// String snmpCommunity = "private"; /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity); /// // Create a request Pdu /// Pdu pdu = new Pdu(); /// pdu.Type = SnmpConstants.GETBULK; // type GETBULK /// pdu.VbList.Add("1.3.6.1.2.1.1"); /// pdu.NonRepeaters = 0; /// pdu.MaxRepetitions = 10; /// Dictionary<Oid, AsnType> result = snmp.GetBulk(pdu); /// if( result == null ) { /// Console.WriteLine("Request failed."); /// } else { /// foreach (KeyValuePair<Oid, AsnType> entry in result) /// { /// Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type), /// entry.Value.ToString()); /// } /// } /// </code> /// Will return: /// <code> /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook" /// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1 /// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms /// 1.3.6.1.2.1.1.4.0 = OctetString: "*****@*****.**" /// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook" /// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home" /// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms /// </code> /// </example> /// <param name="pdu">Request Protocol Data Unit</param> /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns> public Dictionary <Oid, AsnType> GetBulk(Pdu pdu) { if (!Valid) { if (!_suppressExceptions) { throw new SnmpException("SimpleSnmp class is not valid."); } return(null); // class is not fully initialized. } try { pdu.NonRepeaters = _nonRepeaters; pdu.MaxRepetitions = _maxRepetitions; _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry); } catch (Exception ex) { _target = null; if (!_suppressExceptions) { throw ex; } } if (_target == null) { return(null); } try { AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(_community)); SnmpPacket result = _target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus == 0) { Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>(); foreach (Vb v in result.Pdu.VbList) { if ( (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW) || (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE) || (v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT) ) { break; } if (res.ContainsKey(v.Oid)) { if (res[v.Oid].Type != v.Value.Type) { throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString()); } else { res[v.Oid] = v.Value; } } else { res.Add(v.Oid, v.Value); } } _target.Close(); _target = null; return(res); } else { if (!_suppressExceptions) { throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } } } catch (Exception ex) { if (!_suppressExceptions) { _target.Close(); _target = null; throw ex; } } _target.Close(); _target = null; return(null); }
private static bool WalkGetNext(IPAddress agent, string community, string oid, Func <Vb, bool> handleValue) { // SNMP community name OctetString communityString = new OctetString(community); // Define agent parameters class AgentParameters param = new AgentParameters(communityString) { // Set SNMP version to 1 Version = SnmpVersion.Ver1 }; // Construct target UdpTarget target = new UdpTarget(agent, 161, 2000, 1); // Define Oid that is the root of the MIB // tree you wish to retrieve Oid rootOid = new Oid(oid); // ifDescr // This Oid represents last Oid returned by // the SNMP agent Oid lastOid = (Oid)rootOid.Clone(); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.GetNext); // Loop through results while (lastOid != null) { // When Pdu class is first constructed, RequestId is set to a random value // that needs to be incremented on subsequent requests made using the // same instance of the Pdu class. if (pdu.RequestId != 0) { pdu.RequestId += 1; } // Clear Oids from the Pdu class. pdu.VbList.Clear(); // Initialize request PDU with the last retrieved Oid pdu.VbList.Add(lastOid); // Make SNMP request SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); // You should catch exceptions in the Request if using in real application. // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // 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 //System.Diagnostics.Debug.WriteLine("Error in SNMP reply. Error {0} index {1}", // result.Pdu.ErrorStatus, // result.Pdu.ErrorIndex); lastOid = null; break; } else { // Walk through returned variable bindings foreach (Vb v in result.Pdu.VbList) { // Check that retrieved Oid is "child" of the root OID if (rootOid.IsRootOf(v.Oid)) { //System.Diagnostics.Debug.WriteLine("{0} ({1}): {2}", // v.Oid.ToString(), // SnmpConstants.GetTypeName(v.Value.Type), // v.Value.ToString()); handleValue(v); lastOid = v.Oid; } else { // we have reached the end of the requested // MIB tree. Set lastOid to null and exit loop lastOid = null; } } } } else { //System.Diagnostics.Debug.WriteLine("No response received from SNMP agent."); } } target.Close(); return(true); }
private static async Task <bool> WalkGetBulkAsync(IPAddress agent, string community, string oid, Func <Vb, bool> handleValue) { OctetString communityString = new OctetString(community); // Define agent parameters class AgentParameters param = new AgentParameters(communityString); // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3) param.Version = SnmpVersion.Ver2; // Construct target UdpTarget target = new UdpTarget(agent, 161, 2000, 1); // Define Oid that is the root of the MIB // tree you wish to retrieve Oid rootOid = new Oid(oid); // ifDescr // This Oid represents last Oid returned by // the SNMP agent Oid lastOid = (Oid)rootOid.Clone(); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.GetBulk) { // In this example, set NonRepeaters value to 0 NonRepeaters = 0, // MaxRepetitions tells the agent how many Oid/Value pairs to return // in the response. MaxRepetitions = 5 }; // Loop through results while (lastOid != null) { // When Pdu class is first constructed, RequestId is set to 0 // and during encoding id will be set to the random value // for subsequent requests, id will be set to a value that // needs to be incremented to have unique request ids for each // packet if (pdu.RequestId != 0) { pdu.RequestId += 1; } // Clear Oids from the Pdu class. pdu.VbList.Clear(); // Initialize request PDU with the last retrieved Oid pdu.VbList.Add(lastOid); // Make SNMP request //var result = (SnmpV1Packet)target.Request(pdu, param); SnmpV2Packet result = (SnmpV2Packet)(await target.RequestAsync(pdu, param)); // You should catch exceptions in the Request if using in real application. // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // 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 //System.Diagnostics.Debug.WriteLine("Error in SNMP reply. Error {0} index {1}", // result.Pdu.ErrorStatus, // result.Pdu.ErrorIndex); lastOid = null; break; } else { // Walk through returned variable bindings foreach (Vb v in result.Pdu.VbList) { // Check that retrieved Oid is "child" of the root OID if (rootOid.IsRootOf(v.Oid)) { //System.Diagnostics.Debug.WriteLine("{0} ({1}): {2}", // v.Oid.ToString(), // SnmpConstants.GetTypeName(v.Value.Type), // v.Value.ToString()); handleValue(v); if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW) { lastOid = null; } else { lastOid = v.Oid; } } else { // we have reached the end of the requested // MIB tree. Set lastOid to null and exit loop lastOid = null; } } } } else { //System.Diagnostics.Debug.WriteLine("No response received from SNMP agent."); } } target.Close(); return(true); }
/// <summary>Standard constructor.</summary> public SnmpV1Packet() : base(ESnmpVersion.Ver1) { Community = new OctetString(); pdu = new Pdu(); }