public bool sprawdzPolaczenie(string host1, string commun) { /*! *Sprawdza, czy pod wpisanymi danymi istnieje jakiś serwer do obsługi. */ string OID = "1.3.6.1.2.1.6.11.0"; OctetString communityOS = new OctetString(commun); AgentParameters param = new AgentParameters(communityOS); param.Version = SnmpVersion.Ver1; IpAddress agent = new IpAddress(host1); UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add(OID); try { SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); } catch { return false; } host = host1; community = commun; return true; }
public string SNMP_SET(string adres, string value) { // Prepare target UdpTarget target = new UdpTarget((IPAddress)new IpAddress("127.0.0.1")); // Create a SET PDU Pdu pdu = new Pdu(PduType.Set); // Set a value to integer pdu.VbList.Add(new Oid(adres), new SnmpSharpNet.Integer32(int.Parse(value))); // Set Agent security parameters AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new SnmpSharpNet.OctetString("public")); // Response packet SnmpV2Packet response; try { // Send request and wait for response response = target.Request(pdu, aparam) as SnmpV2Packet; } catch (Exception ex) { // If exception happens, it will be returned here target.Close(); return String.Format("Request failed with exception: {0}", ex.Message); } // Make sure we received a response if (response == null) { return ("Error in sending SNMP request."); } else { // Check if we received an SNMP error from the agent if (response.Pdu.ErrorStatus != 0) { return (String.Format("SNMP agent returned ErrorStatus {0} on index {1}", response.Pdu.ErrorStatus, response.Pdu.ErrorIndex)); } else { // Everything is ok. Agent will return the new value for the OID we changed return (String.Format("Agent response {0}: {1}", response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString())); } } }
/// <summary> /// Update Ammo information /// </summary> public void UpdateAmmo() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Get; pdu.VbList.Add(baseTreeOid + ".6.1.1"); //mg ammo 6 pdu.VbList.Add(baseTreeOid + ".6.2.1"); //missile ammo 8 pdu.VbList.Add(baseTreeOid + ".6.3.1"); //rail ammo 10 PrintPacketSend(pdu); Dictionary<Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Set failed."); return; } List<AsnType> list = new List<AsnType>(result.Values); //guns machineGunAmmo = int.Parse(list[0].ToString()); missileLauncherAmmo = int.Parse(list[1].ToString()); railGunAmmo = int.Parse(list[2].ToString()); }
public string get(string ip, string oid) { Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add(oid); OctetString community = new OctetString("public"); AgentParameters param = new AgentParameters(community); param.Version = SnmpVersion.Ver1; { IpAddress agent = new IpAddress(ip); UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus != 0) { return string.Format("Error in SNMP reply. Error {0} index {1} \r\n", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } else { return result.Pdu.VbList[0].Value.ToString(); } } else { return string.Format("No response received from SNMP agent. \r\n"); } target.Dispose(); } }
/// <summary> /// Creates a new UnsuccessAdress. /// </summary> /// <param name="destinationAddressTon">Type of number for destination SME.</param> /// <param name="destinationAddressNpi">Numbering Plan Indicator for destination SME</param> /// <param name="destinationAdress">Destination Address of destination SME</param> /// <param name="ErrorStatusCode">Indicates the success or failure of the submit_multi request /// to this SME address.</param> public UnsuccessAddress( Pdu.TonType destinationAddressTon, Pdu.NpiType destinationAddressNpi, string destinationAdress, UInt32 ErrorStatusCode) { this._DestinationAddressTon = destinationAddressTon; this._DestinationAddressNpi = destinationAddressNpi; this._DestinationAddress = destinationAdress; this._ErrorStatusCode = ErrorStatusCode; }
/// <summary> /// Performs an SNMP get request /// </summary> /// <param name="log_options">Log options</param> /// <param name="ip">IP of target device</param> /// <param name="in_community">Community name</param> /// <param name="oid">OID</param> /// <returns></returns> public static SnmpV1Packet Get(LOG_OPTIONS log_options, IPAddress ip, string in_community, string oid, bool get_next) { // SNMP community name OctetString community = new OctetString(in_community); // Define agent parameters class AgentParameters param = new AgentParameters(community); // Set SNMP version to 1 (or 2) param.Version = SnmpVersion.Ver1; // Construct target UdpTarget target = new UdpTarget(ip, 161, 2000, 1); // Pdu class used for all requests Pdu pdu; if (get_next) { pdu = new Pdu(PduType.GetNext); } else { pdu = new Pdu(PduType.Get); } pdu.VbList.Add(oid); //sysDescr // 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) { // 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 Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus.ToString() + " index " + result.Pdu.ErrorIndex.ToString()); } else { // Reply variables are returned in the same order as they were added // to the VbList Logger.Write(log_options, module, "OID: " + result.Pdu.VbList[0].Oid.ToString() + " Value: " + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + " : " + result.Pdu.VbList[0].Value.ToString()); } } else { Logger.Write(log_options, module, "No response received from SNMP agent."); } target.Close(); return result; }
public Pdu basicInfo() { // Pdu class used for all requests Pdu pdu = new 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 return pdu; }
public SnmpV2Packet getnext(string oid) { Pdu pdu = new Pdu(PduType.GetNext); pdu.VbList.Add(oid); SnmpV2Packet result = null; try { result = (SnmpV2Packet)target.Request(pdu, param); } finally { } return result; }
/// <summary> /// Takes the given PDU and inserts a network error code into the TLV table. /// </summary> /// <param name="pdu">The PDU to operate on.</param> /// <param name="data">The binary encoded error (see spec).</param> public static void SetNetworkErrorCode(Pdu pdu, byte[] data) { const int ERR_CODE_LEN = 3; if (data == null) { pdu.SetOptionalParamBytes(OptionalParamCodes.network_error_code, null); } else if (data.Length != ERR_CODE_LEN) { throw new ArgumentException("network_error_code must have length " + ERR_CODE_LEN); } else { pdu.SetOptionalParamBytes(OptionalParamCodes.network_error_code, data); } }
public void CheckOIDs() { IsOnline(); if (Online) { OctetString community = new OctetString("public"); AgentParameters param = new AgentParameters(community); IpAddress agent = new IpAddress(IP); UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); Pdu pdu = new Pdu(PduType.Get); foreach (var oid in DeviceProps) { pdu.VbList.Add(oid.PropOID); } SnmpPacket result = target.Request(pdu, param); if (result != null) { if (result.Pdu.ErrorStatus != 0) { throw new ArgumentException("Error in SNMP reply. Error {0} " + result.Pdu.ErrorStatus + "index" + result.Pdu.ErrorIndex); } else { for (int i = 0; i < DeviceProps.Count; i++) { try { DeviceProps[i].PropValue = result.Pdu.VbList[i].Value.ToString(); } catch (Exception) { continue; } } } } else { throw new Exception("No response received from SNMP agent."); } target.Close(); } }
private void WaitForCurrentConnectionsToDrain(string farm, string server, string snmpEndpoint, int snmpPort, string snmpCommunity, DateTime timeout) { if (DateTime.Now > timeout) { throw new ConDepLoadBalancerException(string.Format("Timed out while taking {0} offline in load balancer.", server)); } Logger.Verbose("Connecting to snmp using " + snmpEndpoint + " on port " + snmpPort + " with community " + snmpCommunity); var snmp = new SimpleSnmp(snmpEndpoint, snmpPort, snmpCommunity); Logger.Verbose("Getting snmp info about farm " + farm); var farmResult = snmp.Walk(SnmpVersion.Ver2, FARM_NAMES_OID); var farmOid = farmResult.Single(x => x.Value.Clone().ToString() == farm); var id = farmOid.Key.ToString(); var start = farmOid.Key.ToString().LastIndexOf("."); var farmSubId = id.Substring(start + 1, id.Length - start - 1); Logger.Verbose("Getting snmp info about server " + server); var serverResult = snmp.Walk(SnmpVersion.Ver2, SERVER_NAMES_OID + farmSubId); var serverOid = serverResult.Single(x => x.Value.Clone().ToString() == server); var serverId = serverOid.Key.ToString(); start = serverOid.Key.ToString().LastIndexOf("."); var serverSubId = serverId.Substring(start + 1, serverId.Length - start - 1); Logger.Verbose("Getting current server sessions for server " + server); var pdu = Pdu.GetPdu(); pdu.VbList.Add(SERVER_CUR_SESSIONS_OID + farmSubId + "." + serverSubId); var currentSessionsVal = snmp.Get(SnmpVersion.Ver2, pdu); var val = currentSessionsVal.Single().Value.Clone() as Counter64; if (val > 0) { Logger.Verbose("Server " + server + " has " + val + " active sessions."); var waitInterval = 3; Logger.Warn(string.Format("There are still {0} active connections on server {1}. Waiting {2} second before retry.", val, server, waitInterval)); Thread.Sleep(1000 * waitInterval); WaitForCurrentConnectionsToDrain(farm, server, snmpEndpoint, snmpPort, snmpCommunity, timeout); } Logger.Verbose("Server " + server + " has 0 active session and is now offline."); }
private void PreparePackets() { Oid _ifIndex = new Oid(_ifEntryString + ".1"); Oid _ifDescr = new Oid(_ifEntryString + ".2"); Oid _ifType = new Oid(_ifEntryString + ".3"); _index = new Pdu(PduType.GetBulk); _index.VbList.Add(_ifIndex); _index.MaxRepetitions = (int)_expectedIfNr; _descr = new Pdu(PduType.GetBulk); _descr.VbList.Add(_ifDescr); _descr.MaxRepetitions = (int)_expectedIfNr; _type = new Pdu(PduType.GetBulk); _type.VbList.Add(_ifType); _type.MaxRepetitions = (int)_expectedIfNr; }
private void btnSet_Click(object sender, EventArgs e) { IpAddress agent = new IpAddress(this.IP); UdpTarget target = new UdpTarget((IPAddress)agent, 162, 2000, 1); Pdu pdu = new Pdu(PduType.Set); //pdu.VbList.Add(this.OID, new Integer32()); OctetString community = new OctetString(this.comm); AgentParameters param = new AgentParameters(community); param.Version = SnmpVersion.Ver1; SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); }
public void SendPdu(Pdu pdu, Connection connection) { if (!Disposed) { byte[] pdubytes = pdu.ToBytes(); S7OexchangeBlock fdr = new S7OexchangeBlock(); fdr.user = (ushort)connection.ConnectionNumber; fdr.subsystem = 64; fdr.opcode = 6; fdr.response = 255; fdr.fill_length_1 = (byte)pdubytes.Length; fdr.seg_length_1 = (byte)pdubytes.Length; fdr.application_block_opcode = connection.application_block_opcode; //if (!connection.ConnectionConfig.ConnectionToEthernet) fdr.application_block_subsystem = connection.application_block_subsystem; fdr.headerlength = 80; //Length of the Header (always 80) (but the 4 first unkown bytes are not count) fdr.rb_type = 2; //rb_type is always 2 fdr.offset_1 = 80; //Offset of the Begin of userdata (but the 4 first unkown bytes are not count) fdr.user_data_1 = new byte[260]; Array.Copy(pdubytes, fdr.user_data_1, pdubytes.Length); int len = Marshal.SizeOf(fdr); byte[] buffer = new byte[len]; IntPtr ptr = Marshal.AllocHGlobal(len); Marshal.StructureToPtr(fdr, ptr, true); Marshal.Copy(ptr, buffer, 0, len); Marshal.FreeHGlobal(ptr); int ret = SCP_send(_connectionHandle, (ushort)(fdr.seg_length_1 + fdr.headerlength), buffer); if (ret < 0) { throw new S7OnlineException(SCP_get_errno()); } } else { throw new ObjectDisposedException(this.ToString()); } }
public string GetSend(string getOid, string Version, string communityRead, string IP, int Port) { OctetString community = new OctetString(communityRead); AgentParameters param = new AgentParameters(community); if (Version == "V1") { param.Version = SnmpVersion.Ver1; } if (Version == "V2") { param.Version = SnmpVersion.Ver2; } IpAddress agent = new IpAddress(IP); UdpTarget target = new UdpTarget((IPAddress)agent, Port, 2000, 1); Pdu pdu = new Pdu(PduType.Get); try { if (pdu.RequestId != 0) { pdu.RequestId += 1; } pdu.VbList.Clear(); pdu.VbList.Add(getOid); if (Version == "V1") { result = (SnmpV1Packet)target.Request(pdu, param); } if (Version == "V2") { result = (SnmpV2Packet)target.Request(pdu, param); } } catch (Exception e) { } target.Close(); deviceWalkData.UpdateWalkTowerDeviceGetSend(result, getOid, IP); return(result.Pdu.VbList[0].Value.ToString()); }
public static void PrintPdu(TextWriter os, string text, Pdu pdu, bool debug, object id) { lock (os) { os.WriteLine("[{0}]: {1}{2}", id, text, debug ? "\n" + pdu : ""); // another way would be through Pdu.Vbs: // foreach (Vb vb in pdu.Vbs) {...} int i = 0; foreach (Vb vb in pdu) { SnmpSyntax val = vb.Value; SmiSyntax type = val != null ? val.SmiSyntax : SmiSyntax.Null; os.WriteLine("oid [{0}]: {1}\nval [{0}]: {2} ({3})", i, vb.Oid, val, type); i++; } } }
private void ExecuteRequest(UdpTarget _target, AgentParameters _param) { const string _outOctetsString = "1.3.6.1.2.1.2.2.1.16"; Oid _outOctets = new Oid(_outOctetsString + "." + ifEntryNr); Pdu _octets = new Pdu(PduType.Get); _octets.VbList.Add(_outOctets); try { SnmpV2Packet _octetsResult = (SnmpV2Packet)_target.Request(_octets, _param); if (_octetsResult.Pdu.ErrorStatus != 0) { outp.outState = JobOutput.OutState.Failed; Logging.Logger.Log("Something went wrong with reading the traffic. The Error Status of SNMP was not equal 0, but " + _octetsResult.Pdu.ErrorStatus.ToString(), Logging.Logger.MessageType.ERROR); } else { uint _result = (uint)Convert.ToUInt64(_octetsResult.Pdu.VbList[0].Value.ToString()) - _lastRecord; _lastRecord = (uint)Convert.ToUInt64(_octetsResult.Pdu.VbList[0].Value.ToString()); if (firstRun) { outp.GetOutputDesc("Bytes").dataObject = 0; } else { outp.GetOutputDesc("Bytes").dataObject = _result; } outp.outState = JobOutput.OutState.Success; Logging.Logger.Log("Traffic Read reports Success", Logging.Logger.MessageType.DEBUG); } } catch (Exception ex) { outp.outState = JobOutput.OutState.Failed; Logging.Logger.Log("Something went wrong with reading the traffic. The message is: " + ex.Message, Logging.Logger.MessageType.ERROR); } }
/// <summary> /// Takes the given PDU and inserts ITS session info into the TLV table. /// </summary> /// <param name="pdu">The PDU to operate on.</param> /// <param name="val">The value to insert.</param> public static void SetItsSessionInfo(Pdu pdu, string val) { const int MAX_ITS = 16; if (val == null) { pdu.SetOptionalParamString( (ushort)Pdu.OptionalParamCodes.its_session_info, string.Empty); } else if (val.Length == MAX_ITS) { pdu.SetOptionalParamString( (ushort)Pdu.OptionalParamCodes.its_session_info, val); } else { throw new ArgumentException("its_session_info must have length " + MAX_ITS); } }
/// <summary> /// Takes the given PDU and inserts a callback number into the TLV table. /// </summary> /// <param name="pdu">The PDU to operate on.</param> /// <param name="val">The value to insert.</param> public static void SetCallbackNum(Pdu pdu, byte[] val) { const int CALLBACK_NUM_MIN = 4; const int CALLBACK_NUM_MAX = 19; if (val == null) { pdu.SetOptionalParamBytes(OptionalParamCodes.callback_num, null); } else if (val.Length >= CALLBACK_NUM_MIN && val.Length <= CALLBACK_NUM_MAX) { pdu.SetOptionalParamBytes(OptionalParamCodes.callback_num, val); } else { throw new ArgumentException( "callback_num size must be between " + CALLBACK_NUM_MIN + " and " + CALLBACK_NUM_MAX + " characters."); } }
/// <summary> /// Takes the given PDU and inserts a receipted message ID into the TLV table. /// </summary> /// <param name="pdu">The PDU to operate on.</param> /// <param name="val">The value to insert.</param> public static void SetReceiptedMessageId(Pdu pdu, string val) { const int MAX_RECEIPTED_ID_LEN = 65; if (val == null) { pdu.SetOptionalParamString( (ushort)Pdu.OptionalParamCodes.receipted_message_id, string.Empty); } else if (val.Length <= MAX_RECEIPTED_ID_LEN) { pdu.SetOptionalParamString( (ushort)Pdu.OptionalParamCodes.receipted_message_id, val); } else { throw new ArgumentException( "receipted_message_id must have length 1-" + MAX_RECEIPTED_ID_LEN); } }
private void ExecuteRequest(UdpTarget target, AgentParameters param) { Oid _name = new Oid("1.3.6.1.2.1.1.5.0"); Pdu _namePacket = new Pdu(PduType.Get); _namePacket.VbList.Add(_name); try { SnmpV2Packet _nameResult = (SnmpV2Packet)target.Request(_namePacket, param); outp.outState = JobOutput.OutState.Success; } catch (Exception) { Logger.Log("SNMP Service seems to be dead", Logger.MessageType.ERROR); outp.outState = JobOutput.OutState.Failed; } }
/// <summary> /// Takes the given PDU and inserts a callback number into the TLV table. /// </summary> /// <param name="pdu">The PDU to operate on.</param> /// <param name="val">The value to insert.</param> public static void SetCallbackNum(Pdu pdu, byte[] val) { const int callbackNumMin = 4; const int callbackNumMax = 19; if (val == null) { pdu.SetOptionalParamBytes(OptionalParamCodes.CallbackNum, null); } else if (val.Length >= callbackNumMin && val.Length <= callbackNumMax) { pdu.SetOptionalParamBytes(OptionalParamCodes.CallbackNum, val); } else { throw new ArgumentException( "callback_num size must be between " + callbackNumMin + " and " + callbackNumMax + " characters."); } }
private void SNMPRunAgent(OctetString Community, IOIDSettingDTO OIDSetting, ISNMPDeviceDataDTO SNMPDeviceData) { bool nextEntry = true; AgentParameters AgParam; Pdu pdu; SnmpV2Packet Result; Oid indexOid = new Oid(OIDSetting.InitialOID); //Walk control Oid finalOid = new Oid(OIDSetting.FinalOID); AgParam = new AgentParameters(Community); AgParam.Version = SnmpVersion.Ver2; // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3) pdu = new Pdu(PduType.GetBulk); pdu.NonRepeaters = 0; //NonRepeaters tells how many OID asociated values (leafs of this object) get. 0 is all pdu.MaxRepetitions = 5; // MaxRepetitions tells the agent how many Oid/Value pairs to return in the response packet. pdu.RequestId = 1; using (UdpTarget UDPtarget = new UdpTarget(SNMPDeviceData.TargetIP, DefaultPort, DefaultTimeout, DefaultRetries)) { while (nextEntry) { pdu.VbList.Add(indexOid); //Add starting OID for request try { Result = (SnmpV2Packet)UDPtarget.Request(pdu, AgParam); nextEntry = SNMPDecodeData(Result, indexOid, finalOid, OIDSetting.InclusiveInterval, SNMPDeviceData); } catch //(SnmpException e) { throw; } finally { //Prepare PDU object for iteration. Otherwise, wipe contents of pdu pdu.RequestId++; pdu.VbList.Clear(); } } } }
/// <summary> /// Grab SNMP VbCollection results form a array of OIDs /// </summary> /// <param name="ipAddress"></param> /// <param name="snmpParameters"></param> /// <param name="oids"></param> /// <returns></returns> private VbCollection GetSnmp(IPAddress ipAddress, IAgentParameters snmpParameters, IEnumerable <string> oids) { UdpTarget target = new UdpTarget(ipAddress, 161, 2000, config.Settings.SnmpRetries); Pdu pdu = new Pdu(PduType.Get); foreach (string oid in oids) { pdu.VbList.Add(oid); } try { SnmpPacket result; if (snmpParameters.Version == SnmpVersion.Ver2) { result = (SnmpV2Packet)target.Request(pdu, snmpParameters); } else { result = (SnmpV1Packet)target.Request(pdu, snmpParameters); } if (result != null) { if (result.Pdu.ErrorStatus == 0) { return(result.Pdu.VbList); } else { throw new SnmpErrorStatusException("Snmp Error Occured", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } } else { throw new SnmpException("Snmp returned a null value"); } } catch (Exception e) { throw e; } }
private int getStatus(AgentParameters param, UdpTarget target, string OID_Status) { // Pdu class used for all requests Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add(OID_Status); // Make SNMP request SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); string value = result.Pdu.VbList[0].Value.ToString(); try { return(Int32.Parse(value)); } catch (FormatException e) { throw new FormatException(e.Message); } }
public void TestGetNextRequest1() { SNMP_Agent agent = new SNMP_Agent("127.0.0.1", "public"); string oid = "1.3.6.1.2.1.2.2.1.17.1"; IPAddress IP = IPAddress.Parse("127.0.0.1"); var result = agent.GetNextRequest(SnmpVersion.Ver1, oid, IP); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.GetNext); pdu.VbList.Add(oid); //sysDescr Assert.IsNotNull(result); Assert.AreEqual(result.Version, SnmpVersion.Ver1); //VarBindListy pdu zwracanego i wygenerowanego w tym tescie powinny byc inne Assert.AreNotEqual(result.Pdu.VbList, pdu.VbList); Console.WriteLine(result.Pdu.VbList[0].Value.ToString()); }
void timer_Tick(object sender, EventArgs e) { AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(App.snmpCommunity)); param.DisableReplySourceCheck = !App.snmpCheckSrcFlag; target = new UdpTarget((IPAddress)ip, App.snmpPort, App.snmpTimeout, App.snmpRetry); Pdu pdu = new Pdu(PduType.Get); for (int i = 0; i < requestOids.Length; i++) { pdu.VbList.Add(requestOids[i]); } try { target.RequestAsync(pdu, param, new SnmpAsyncResponse(SnmpAsyncResponseCallback)); } catch (System.Exception ex) { TipMessage = "发送数据包异常"; } }
public GetTableState(Snmp snmp, Pdu pdu, SnmpTarget target, Oid[] columnOids, Oid endRowIndex, int maxRows, int rowsPerQuery, Vb[] vbs, AsyncCallback callback, object callbackData, bool sync) { this.snmp = snmp; this.target = target; this.columnOids = columnOids; this.endRowIndex = endRowIndex; this.maxRows = maxRows; this.rowsPerQuery = rowsPerQuery; this.rows = new Hashtable(); this.callback = callback; this.callbackData = callbackData; this.invoke = sync ? new SnmpInvoke(SyncInvoke) : new SnmpInvoke(AsyncInvoke); this.pdu = pdu; this.vbs = vbs; }
/// <summary> /// Send a SNMP get request for the metal gear position /// </summary> public void GetPosition() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Get; //pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); pdu.VbList.Add(baseTreeOid + ".2"); //location 2 PrintPacketSend(pdu); Dictionary <Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1, pdu); //Debug.Log(result); //Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Request failed."); } else { List <AsnType> list = new List <AsnType>(result.Values); location = list[0].ToString(); // send X:--- Y:--- var r = new Regex(@"[0-9]+\.[0-9]+"); var mc = r.Matches(location); var matches = new Match[mc.Count]; mc.CopyTo(matches, 0); var myFloats = new float[matches.Length]; float x = float.Parse(matches[0].Value); float y = float.Parse(matches[1].Value); metalGearMapPosition.rectTransform.anchoredPosition = new Vector2(x, y); } }
/// <summary> /// Обработчик события таймера /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Timer_Elapsed(object sender, ElapsedEventArgs e) { try { // Отключение timer.Enabled = false; // Адрес источника данных по SNMP // Адрес берется из конфигурации IpAddress peer = new IpAddress(Properties.Settings.Default.Host); // Параметры вызова по протоколу SNMP // Вторая версия протокола, community string public - чтение данных AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString("public")); // Точка подключения по SNMP UdpTarget target = new UdpTarget((System.Net.IPAddress)peer, 161, 2000, 1); // Список запрашиваемых данных и режим запроса - GET Pdu pdu = new Pdu(PduType.Get); // 1.3.6.1.2.1.1.1.0 - SysDescr // 1.3.6.1.2.1.1.3.0 - SysUpTime // Добавление OID в список запрашиваемых данных pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); pdu.VbList.Add("1.3.6.1.2.1.1.3.0"); // Выполнение запроса по SNMP SnmpV2Packet res = (SnmpV2Packet)target.Request(pdu, param); foreach (Vb v in res.Pdu.VbList) { EventLog.WriteEntry(v.ToString(), EventLogEntryType.Information, (int)EventID.TimerEvent); } } catch (Exception ex) { WriteException(ex); } finally { // Включение таймера timer.Enabled = true; } }
private void SendPduBase(Pdu pdu) { if (pdu == null) { throw new ArgumentNullException("pdu"); } if (!(CheckState(pdu) && (pdu.AllowedSource & SmppEntityType.Esme) == SmppEntityType.Esme)) { throw new SmppException(SmppErrorCode.EsmeRinvbndsts, "Incorrect bind status for given command"); } try { _vTrans.Send(pdu); } catch (Exception ex) { if (_vTraceSwitch.TraceInfo) { ByteBuffer buffer = new ByteBuffer(pdu.GetBytes()); Trace.WriteLine(string.Format( "200022:PDU send operation failed - {0} {1};", buffer.DumpString(), ex.Message)); } } }
private static void GotTrap(Snmp snmp, Pdu pdu, SnmpTarget target, object cbData) { if ((int)cbData != CB_DATA_) { Console.Error.WriteLine("*** Invalid callback data!"); } if (threadId_ == null) { threadId_ = Interlocked.Increment(ref nextId_); } // Use a lock if you want do not want messages from various threads // to be interleaved ManagerUtilities.PrintPdu(Console.Out, Now() + ": " + pdu.Type + " received from " + target, pdu, true, threadId_); Console.Out.WriteLine( "Enterprise: " + pdu.NotifyEnterprise + "\nNotify OID : " + pdu.NotifyId + "\nV1 generic-trap : " + pdu.V1GenericTrap + "\nV1 specific-trap: " + pdu.V1SpecificTrap + "\nTimestamp : " + pdu.NotifyTimestamp); if (pdu.Type == PduType.V1Trap) { Console.Out.WriteLine("v1TrapAddr: " + pdu.V1TrapAddress); } if (pdu.Type == PduType.Inform) { Vb vb = new Vb("1.3.6.1", new OctetStr("this is the response")); pdu = new Pdu(PduType.Response, vb); snmp.Invoke(pdu, target); ManagerUtilities.PrintPdu(Console.Out, "Response sent to " + target, pdu, true, threadId_); } // Long trap processing follows... Thread.Sleep(5000); }
private static void Walk(Snmp snmp, Pdu pdu, SnmpTarget target, bool asyncSync, bool show, bool debug, ref int ncalls) { Console.WriteLine("Rentre dans le Walk"); string thName = Thread.CurrentThread.Name; Oid rootOid = pdu[0].Oid; while (true) { if (debug) { PrintPdu(Console.Out, "Sending PDU to target " + target, pdu, debug); } Pdu resp = Invoke(snmp, pdu, target, asyncSync); ncalls++; Vb nextVb = resp[0]; Oid nextOid = nextVb.Oid; if (!nextOid.StartsWith(rootOid)) { break; } if (debug) { PrintPdu(Console.Out, "Received PDU:", resp, debug); } else if (show) { SnmpSyntax val = nextVb.Value; SmiSyntax type = val != null ? val.SmiSyntax : SmiSyntax.Null; Console.WriteLine("[{0}]: {1},{2},{3}", thName, nextOid, val, type); } pdu = pdu.Clone(new Vb(nextOid)); } }
/// <summary> /// Ask the agent for all the health status /// </summary> public void UpdateHealth() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Get; pdu.VbList.Add(baseTreeOid + ".13.1.1"); //head health 17 pdu.VbList.Add(baseTreeOid + ".13.1.2"); //head armor 18 pdu.VbList.Add(baseTreeOid + ".13.2.1"); // arm healt 13 pdu.VbList.Add(baseTreeOid + ".13.2.2"); // arm armor 20 pdu.VbList.Add(baseTreeOid + ".13.3.1"); //legs healt 21 pdu.VbList.Add(baseTreeOid + ".13.3.2"); //legs armor 22 PrintPacketSend(pdu); Dictionary <Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Get failed."); return; } List <AsnType> list = new List <AsnType>(result.Values); //bodie ArmHealth = int.Parse(list[0].ToString()); ArmArmor = int.Parse(list[1].ToString()); LegsHealth = int.Parse(list[2].ToString()); LegsArmor = int.Parse(list[3].ToString()); HeadHealth = int.Parse(list[4].ToString()); HeadArmor = int.Parse(list[5].ToString()); ChangeBodyColors(); }
public string getHostname(string ip) { string hostname = null; try { OctetString comm = new OctetString(_community); AgentParameters param = new AgentParameters(comm); param.Version = SnmpVersion.Ver1; IpAddress agent = new IpAddress(ip); UdpTarget target = new UdpTarget((IPAddress)agent,161,2000,1); Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); if (result!=null) { if (result.Pdu.ErrorStatus!= 0) { hostname = null; } else { string[] cutPdu = Regex.Split(result.Pdu.VbList[0].Value.ToString(),@"\."); hostname = cutPdu[0]; } } else { hostname = null; } } catch (Exception) { hostname = null; } return hostname; }
private static Hashtable DoSnmp(Snmp snmp, SnmpTarget target, Pdu pdu, OperType operType, ref TableReader.GetTableOptions tableOptions, uint repeat, bool asyncSync, bool debug) { int ncalls = 0; Hashtable htResult = new Hashtable(); for (uint i = 0; i < repeat; i++) { using (IMemoryManager mgr = MemoryManager.GetMemoryManager()) { bool show = (i % 1000) == 0; if (show || debug) { //PrintPdu(Console.Out, "Sending PDU to target " + target, pdu, debug); } Pdu resPdu = DoSnmp(snmp, target, pdu, operType, ref tableOptions, asyncSync, show, debug, ref ncalls); if ((show || debug) && resPdu != null) { //**********OLI***********// //PrintPdu(Console.Out, "Received PDU:", resPdu, debug); //************************// htResult = ManagerUtilities.getValues(resPdu); } if (debug) { Console.WriteLine("Removing " + mgr.Count + " objects"); } } } htResult.Add("count", ncalls); return(htResult); //return ncalls; }
private static Pdu DoSnmp(Snmp snmp, SnmpTarget target, Pdu pdu, OperType operType, ref TableReader.GetTableOptions tableOptions, bool asyncSync, bool show, bool debug, ref int ncalls) { switch (operType) { case OperType.Walk: Walk(snmp, pdu, target, asyncSync, show, debug, ref ncalls); pdu = null; break; case OperType.Table: Table(snmp, pdu, target, ref tableOptions, show, debug, ref ncalls); pdu = null; break; default: pdu = Invoke(snmp, pdu, target, asyncSync); ncalls++; break; } return(pdu); }
/// <summary> /// when button is clicked send the GoTo with the data from the input fields /// </summary> public void SetGoTo() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Set; //pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); pdu.VbList.Add(new Oid(baseTreeOid + ".3"), new Integer32(MoveToXInput)); pdu.VbList.Add(new Oid(baseTreeOid + ".4"), new Integer32(MoveToYInput)); PrintPacketSend(pdu); Dictionary <Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, pdu); //Debug.Log(result); //Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Set failed."); } }
/// <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)PduType.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); }
public Dictionary<string, string> getResult( UdpTarget target, Pdu pdu ) { Dictionary<string, string> Res = new Dictionary<string, string> (); // 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) { // 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 Console.WriteLine("Error in SNMP reply. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } else { // Reply variables are returned in the same order as they were added // to the VbList Console.WriteLine("sysDescr({0}) ({1}): {2}", result.Pdu.VbList[0].Oid.ToString(), SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type), result.Pdu.VbList[0].Value.ToString()); Console.WriteLine("sysObjectID({0}) ({1}): {2}", result.Pdu.VbList[1].Oid.ToString(), SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type), result.Pdu.VbList[1].Value.ToString()); Console.WriteLine("sysUpTime({0}) ({1}): {2}", result.Pdu.VbList[2].Oid.ToString(), SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type), result.Pdu.VbList[2].Value.ToString()); Console.WriteLine("sysContact({0}) ({1}): {2}", result.Pdu.VbList[3].Oid.ToString(), SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type), result.Pdu.VbList[3].Value.ToString()); Console.WriteLine("sysName({0}) ({1}): {2}", result.Pdu.VbList[4].Oid.ToString(), SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type), result.Pdu.VbList[4].Value.ToString()); } } else { Console.WriteLine("No response received from SNMP agent."); } return Res; // FIXME not sure if going to need this method }
public Dictionary<string, string> walk(UdpTarget target, string oid) { Dictionary<string, string> Output = new Dictionary<string, string>(); // 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); if (useCache == true ) { Dictionary<string, string> data = getCache(target, oid); if (data.Count > 0 ) { return data; } } // 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 Console.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)) { /* Console.WriteLine("{0} ({1}): {2}", v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()); */ // keep the result Output.Add(v.Oid.ToString(), v.Value.ToString()); lastOid = v.Oid; } else { // we have reached the end of the requested // MIB tree. Set lastOid to null and exit loop lastOid = null; } } } } else { Console.WriteLine("No response received from SNMP agent."); } } if (useCache == true || overrideCache == true ) { setCache(target, oid, Output); } return Output; }
/// <summary> /// Fires an event off based on what Pdu is received in. /// </summary> /// <param name="response">The response to fire an event for.</param> private void FireEvents(Pdu response) { //here we go... if(response is SmppBindResp) { if(OnBindResp != null) { OnBindResp(this, new BindRespEventArgs((SmppBindResp)response)); } } else if(response is SmppUnbindResp) { //disconnect asClient.Disconnect(); if(OnUnboundResp != null) { OnUnboundResp(this, new UnbindRespEventArgs((SmppUnbindResp)response)); } } else if(response is SmppAlertNotification) { if(OnAlert != null) { OnAlert(this, new AlertEventArgs((SmppAlertNotification)response)); } } else if(response is SmppSubmitSmResp) { if(OnSubmitSmResp != null) { OnSubmitSmResp(this, new SubmitSmRespEventArgs((SmppSubmitSmResp)response)); } } else if(response is SmppEnquireLinkResp) { if(OnEnquireLinkResp != null) { OnEnquireLinkResp(this, new EnquireLinkRespEventArgs((SmppEnquireLinkResp)response)); } } else if(response is SmppSubmitSm) { if(OnSubmitSm != null) { OnSubmitSm(this, new SubmitSmEventArgs((SmppSubmitSm)response)); } else { //default a response SmppSubmitSmResp pdu = new SmppSubmitSmResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.MessageId = System.Guid.NewGuid().ToString().Substring(0, 10); pdu.CommandStatus = 0; SendPdu(pdu); } } else if(response is SmppQuerySm) { if(OnQuerySm != null) { OnQuerySm(this, new QuerySmEventArgs((SmppQuerySm)response)); } else { //default a response SmppQuerySmResp pdu = new SmppQuerySmResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; SendPdu(pdu); } } else if(response is SmppGenericNack) { if(OnGenericNack != null) { OnGenericNack(this, new GenericNackEventArgs((SmppGenericNack)response)); } } else if(response is SmppEnquireLink) { if(OnEnquireLink != null) { OnEnquireLink(this, new EnquireLinkEventArgs((SmppEnquireLink)response)); } //send a response back SmppEnquireLinkResp pdu = new SmppEnquireLinkResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; SendPdu(pdu); } else if(response is SmppUnbind) { if(OnUnbind != null) { OnUnbind(this, new UnbindEventArgs((SmppUnbind)response)); } else { //default a response SmppUnbindResp pdu = new SmppUnbindResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; SendPdu(pdu); } } else if(response is SmppBind) { if(OnBind != null) { OnBind(this, new BindEventArgs((SmppBind)response)); } else { //default a response SmppBindResp pdu = new SmppBindResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; pdu.SystemId = "Generic"; SendPdu(pdu); } } else if(response is SmppCancelSm) { if(OnCancelSm != null) { OnCancelSm(this, new CancelSmEventArgs((SmppCancelSm)response)); } else { //default a response SmppCancelSmResp pdu = new SmppCancelSmResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; SendPdu(pdu); } } else if(response is SmppCancelSmResp) { if(OnCancelSmResp != null) { OnCancelSmResp(this, new CancelSmRespEventArgs((SmppCancelSmResp)response)); } } else if(response is SmppCancelSmResp) { if(OnCancelSmResp != null) { OnCancelSmResp(this, new CancelSmRespEventArgs((SmppCancelSmResp)response)); } } else if(response is SmppQuerySmResp) { if(OnQuerySmResp != null) { OnQuerySmResp(this, new QuerySmRespEventArgs((SmppQuerySmResp)response)); } } else if(response is SmppDataSm) { if(OnDataSm != null) { OnDataSm(this, new DataSmEventArgs((SmppDataSm)response)); } else { //default a response SmppDataSmResp pdu = new SmppDataSmResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; pdu.MessageId = "Generic"; SendPdu(pdu); } } else if(response is SmppDataSmResp) { if(OnDataSmResp != null) { OnDataSmResp(this, new DataSmRespEventArgs((SmppDataSmResp)response)); } } else if(response is SmppDeliverSm) { if(OnDeliverSm != null) { OnDeliverSm(this, new DeliverSmEventArgs((SmppDeliverSm)response)); } else { //default a response SmppDeliverSmResp pdu = new SmppDeliverSmResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; SendPdu(pdu); } } else if(response is SmppDeliverSmResp) { if(OnDeliverSmResp != null) { OnDeliverSmResp(this, new DeliverSmRespEventArgs((SmppDeliverSmResp)response)); } } else if(response is SmppReplaceSm) { if(OnReplaceSm != null) { OnReplaceSm(this, new ReplaceSmEventArgs((SmppReplaceSm)response)); } else { //default a response SmppReplaceSmResp pdu = new SmppReplaceSmResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; SendPdu(pdu); } } else if(response is SmppReplaceSmResp) { if(OnReplaceSmResp != null) { OnReplaceSmResp(this, new ReplaceSmRespEventArgs((SmppReplaceSmResp)response)); } } else if(response is SmppSubmitMulti) { if(OnSubmitMulti != null) { OnSubmitMulti(this, new SubmitMultiEventArgs((SmppSubmitMulti)response)); } else { //default a response SmppSubmitMultiResp pdu = new SmppSubmitMultiResp(); pdu.SequenceNumber = response.SequenceNumber; pdu.CommandStatus = 0; SendPdu(pdu); } } else if(response is SmppSubmitMultiResp) { if(OnSubmitMultiResp != null) { OnSubmitMultiResp(this, new SubmitMultiRespEventArgs((SmppSubmitMultiResp)response)); } } }
/// <summary> /// Prints the packets /// </summary> /// <param name="result"></param> public void PrintPacketSend(Pdu result) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (result.Type == PduType.Set) { PacketPrinterSend.text = "Set "; } if (result.Type == PduType.Get) { PacketPrinterSend.text = "Get "; } if (result.ErrorStatus != 0) { // agent reported an error with the request PacketPrinterSend.text = "Error: status " + result.ErrorStatus + " Index " + result.ErrorIndex; } else { // Reply variables are returned in the same order as they were added // to the VbList foreach (Vb VarBind in result.VbList) { PacketPrinterSend.text = "Request OID: " + VarBind.Oid.ToString() + " Type " + SnmpConstants.GetTypeName(VarBind.Value.Type) + " Value " + VarBind.Value.ToString(); } } }
/// <summary> /// Ask the agent for all the health status /// </summary> public void UpdateHealth() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Get; pdu.VbList.Add(baseTreeOid + ".13.1.1"); //head health 17 pdu.VbList.Add(baseTreeOid + ".13.1.2"); //head armor 18 pdu.VbList.Add(baseTreeOid + ".13.2.1"); // arm healt 13 pdu.VbList.Add(baseTreeOid + ".13.2.2"); // arm armor 20 pdu.VbList.Add(baseTreeOid + ".13.3.1"); //legs healt 21 pdu.VbList.Add(baseTreeOid + ".13.3.2"); //legs armor 22 PrintPacketSend(pdu); Dictionary<Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Get failed."); return; } List<AsnType> list = new List<AsnType>(result.Values); //bodie ArmHealth = int.Parse(list[0].ToString()); ArmArmor = int.Parse(list[1].ToString()); LegsHealth = int.Parse(list[2].ToString()); LegsArmor = int.Parse(list[3].ToString()); HeadHealth = int.Parse(list[4].ToString()); HeadArmor = int.Parse(list[5].ToString()); ChangeBodyColors(); }
//genN 一次下发多个vb,agent可能会不支持 public void v2(string ip, string port, string rc) { init(); bool isSupported = true; string msg = ""; for (int i = 0; i < oids.Length; i++) { string name = oids[i][0]; isSupported = true; Console.Write("is " + name + "?"); Pdu pdu = new Pdu(PduType.GetNext); for (int j = 1; j < oids[i].Length; j++) { pdu.VbList.Add(oids[i][j]); } SnmpV2Packet result = null; try { Console.Write("."); result = (SnmpV2Packet)target.Request(pdu, param); } finally { } if (result == null) { Console.Write("Agent连不上,请检查配置,输入q退出:"); while (!Console.ReadLine().StartsWith("q")) { Console.Write("Agent连不上,请检查配置,输入q退出:"); } return; } for (int z = 0; z < result.Pdu.VbList.Count; z++) { Vb vb = result.Pdu.VbList[z]; if (result.Pdu.ErrorStatus != 0 || !vb.Oid.ToString().Contains(oids[i][z]) || vb.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW || vb.Value == null) { isSupported = false; break; } } if (isSupported) { msg = "该AC可识别,生产商是:" + name; break; } else { Console.WriteLine(" No!"); } } target.Close(); if (!isSupported) { msg = "该AC不支持!"; } Console.Write(msg + " 输入q退出:"); while (!Console.ReadLine().StartsWith("q")) { Console.Write(msg + " 输入q退出:"); } }
/// <summary> /// Send a SNMP get request for the metal gear position /// </summary> public void GetPosition() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Get; //pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); pdu.VbList.Add(baseTreeOid + ".2"); //location 2 PrintPacketSend(pdu); Dictionary<Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1, pdu); //Debug.Log(result); //Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Request failed."); } else { List<AsnType> list = new List<AsnType>(result.Values); location = list[0].ToString(); // send X:--- Y:--- var r = new Regex(@"[0-9]+\.[0-9]+"); var mc = r.Matches(location); var matches = new Match[mc.Count]; mc.CopyTo(matches, 0); var myFloats = new float[matches.Length]; float x = float.Parse(matches[0].Value); float y = float.Parse(matches[1].Value); metalGearMapPosition.rectTransform.anchoredPosition = new Vector2( x , y ); } }
/// <summary> /// when button is clicked send the GoTo with the data from the input fields /// </summary> public void SetGoTo() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Set; //pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); pdu.VbList.Add(new Oid(baseTreeOid + ".3"), new Integer32(MoveToXInput)); pdu.VbList.Add(new Oid(baseTreeOid + ".4"), new Integer32(MoveToYInput)); PrintPacketSend(pdu); Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, pdu); //Debug.Log(result); //Dictionary<Oid, AsnType> result = snmp.GetNext(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Set failed."); } }
public SendErrorEventArgs(Pdu packet, byte[] data, Exception exception) : base(exception) { Packet = packet; _data = data; }
void getSNMP(string ip,out float ValueA,out float ValueB,out string Status) { ValueA = 0; ValueB = 0; Status = ""; // SNMP community name OctetString community = new OctetString("PUBLIC"); // Define agent parameters class AgentParameters param = new AgentParameters(community); // Set SNMP version to 1 (or 2) param.Version = SnmpVersion.Ver1; IpAddress agent = new IpAddress(ip); // Construct target UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add("1.3.6.1.4.1.33826.1.1.5.1.2.1"); //a pdu.VbList.Add("1.3.6.1.4.1.33826.1.1.5.1.2.2"); //b Application.DoEvents(); // Make SNMP request try{ SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); Application.DoEvents(); // 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 Console.WriteLine("Error in SNMP reply. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); Status = "false"; } else { // Reply variables are returned in the same order as they were added // to the VbList // MessageBox.Show(result.Pdu.VbList[0].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + ") " + result.Pdu.VbList[0].Value.ToString()); // MessageBox.Show(result.Pdu.VbList[1].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + ") " + result.Pdu.VbList[1].Value.ToString()); // MessageBox.Show(result.Pdu.VbList[2].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + ") " + result.Pdu.VbList[2].Value.ToString()); ValueA = float.Parse(result.Pdu.VbList[0].Value.ToString()) / 10; ValueB = float.Parse(result.Pdu.VbList[1].Value.ToString()) / 10; Status = "done"; } } else { Console.WriteLine("No response received from SNMP agent."); } target.Close(); } catch { Status = "false"; } }
protected void btnReset_Click(object sender, EventArgs e) { string IP = _Ip; try { if (IP.Trim() != "") { if (IP.Trim() != "0.0.0.0") { UdpTarget target = new UdpTarget((IPAddress)new IpAddress(IP)); // Create a SET PDU Pdu pdu = new Pdu(PduType.Set); // Set sysLocation.0 to a new string // pdu.VbList.Add(new Oid("1.3.6.1.2.1.1.6.0"), new OctetString("Some other value")); // Set a value to integer pdu.VbList.Add(new Oid(".1.3.6.1.2.1.69.1.1.3.0"), new Integer32(1)); // Set a value to unsigned integer // pdu.VbList.Add(new Oid("1.3.6.1.2.1.67.1.1.1.1.6.0"), new UInteger32(101)); // Set Agent security parameters AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString("LBC")); // Response packet SnmpV2Packet response; try { // Send request and wait for response response = target.Request(pdu, aparam) as SnmpV2Packet; } catch (Exception ex) { // If exception happens, it will be returned here Console.WriteLine(String.Format("Request failed with exception: {0}", ex.Message)); target.Close(); return; } // Make sure we received a response if (response == null) { Console.WriteLine("Error in sending SNMP request."); } else { // Check if we received an SNMP error from the agent if (response.Pdu.ErrorStatus != 0) { Console.WriteLine(String.Format("SNMP agent returned ErrorStatus {0} on index {1}", response.Pdu.ErrorStatus, response.Pdu.ErrorIndex)); } else { // Everything is ok. Agent will return the new value for the OID we changed Console.WriteLine(String.Format("Agent response {0}: {1}", response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString())); } } } } Response.Write("<script>alert('Reset Modem OK !')</script>"); } catch { Response.Write("<script>alert('Chưa reset được Modem. Có thể modem đang offline !')</script>"); } }
/// <summary> /// Send a SetRequest to the agent to start attacking /// </summary> /// <param name="selected"></param> public void SetAttacking(int selected) { String snmpAgent = "127.0.0.1"; String snmpCommunity = "public"; SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a set Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Set; pdu.VbList.Add(new Oid(baseTreeOid + ".16"), new Counter32((uint)selected)); PrintPacketSend(pdu); Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Set failed."); } else { foreach (KeyValuePair<Oid, AsnType> entry in result) { attacking = int.Parse(entry.Value.ToString()); } } }
/// <summary> /// Send a SetRequest to the agent to select a target /// </summary> /// <param name="selected"></param> public void SetTarget(int selected) { String snmpAgent = "127.0.0.1"; String snmpCommunity = "public"; SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a set Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Set; pdu.VbList.Add(new Oid(baseTreeOid + ".14"), new Counter32((uint)selected)); PrintPacketSend(pdu); Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Set failed."); } else { foreach (KeyValuePair<Oid, AsnType> entry in result) { selectedTarget = int.Parse(entry.Value.ToString()); } } if(selected == 0) { Enemy1.transform.GetChild(1).gameObject.SetActive(true); } else { Enemy1.transform.GetChild(1).gameObject.SetActive(false); } if (selected == 1) { Enemy2.transform.GetChild(1).gameObject.SetActive(true); } else { Enemy2.transform.GetChild(1).gameObject.SetActive(false); } if (selected == 2) { Enemy3.transform.GetChild(1).gameObject.SetActive(true); } else { Enemy3.transform.GetChild(1).gameObject.SetActive(false); } }
protected void Page_Load(object sender, EventArgs e) { if (Request.Form["key"] != null) { txtCommand.Visible = false; btnSubmit.Visible = false; string _key = Request.Form["key"].ToString().Trim(); if (_key.IndexOf("168.") > 0) { // kiem tra neu key la IP thi log thang vao modem _key = _key.Trim(); try { string IP = _key; if (IP.Trim() != "") { if (IP.Trim() != "0.0.0.0") { // SNMP community name OctetString community = new OctetString("LBC"); // Define agent parameters class AgentParameters param = new AgentParameters(community); // Set SNMP version to 1 (or 2) param.Version = SnmpVersion.Ver1; IpAddress agent = new IpAddress(IP); // Construct target UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add("1.3.6.1.2.1.10.127.1.1.4.1.5.3"); //Noise -- value1 pdu.VbList.Add("1.3.6.1.2.1.10.127.1.2.2.1.3.2"); //US Power Level --- value2 pdu.VbList.Add("1.3.6.1.2.1.10.127.1.1.1.1.6.3"); //DS Power level -- value3 // 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) { // 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 Console.WriteLine("Error in SNMP reply. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); lblKQ.Text = "Device Offline"; } else { // Reply variables are returned in the same order as they were added // to the VbList lblKQ.Text += "DS SNR: " + (float.Parse(result.Pdu.VbList[0].Value.ToString()) / 10).ToString() + " \r\n"; lblKQ.Text += "US Tx: " + (float.Parse(result.Pdu.VbList[1].Value.ToString()) / 10).ToString() + " \r\n"; lblKQ.Text += "DS Rx: " + (float.Parse(result.Pdu.VbList[2].Value.ToString()) / 10).ToString() + " \n\r"; // gridItemDetail.SetRowCellValue(gridItemDetail.FocusedRowHandle, colValue1, (float.Parse(result.Pdu.VbList[0].Value.ToString()) / 10).ToString()); // gridItemDetail.SetRowCellValue(gridItemDetail.FocusedRowHandle, colValue2, (float.Parse(result.Pdu.VbList[1].Value.ToString()) / 10).ToString()); // gridItemDetail.SetRowCellValue(gridItemDetail.FocusedRowHandle, colValue3, (float.Parse(result.Pdu.VbList[2].Value.ToString()) / 10).ToString()); } } else { Console.WriteLine("No response received from SNMP agent."); lblKQ.Text = "Device Offline"; } target.Close(); } } } catch { lblKQ.Text = "Device Offline"; } // lblKQ.Text = _key; } else { if (Request.Form["mode"] != null) { if (Request.Form["mode"].ToString().Trim() == "phy") { string result = ShowCable(_key, "phy"); string[] sp = result.Split('|'); result = ""; for (int i = 0; i < sp.Length; i++) { string _mac = ""; if (sp[i].Length > 13) { string txt = sp[i].Trim(); _mac = txt.Substring(0, 14); _mac = _mac.Trim(); } if (_mac != "") { if (!_mac.Contains("Server")) { _mac = "<a href=http://101.99.28.156:88/sv2.aspx?macip=" + _mac + ">" + _mac + "</a>" + sp[i].Trim().Substring(14) + "<br>"; result += _mac.Trim(); } else { _mac = _mac + sp[i].Trim().Substring(14) + "<br>"; result += _mac.Trim(); } } } lblKQ.Text = result.Trim(); } else { lblKQ.Text = ShowCable(_key, "remote"); } } else { string result = ShowCable(_key, "phy"); string[] sp = result.Split('|'); result = ""; for (int i = 0; i < sp.Length; i++) { string _mac = ""; if (sp[i].Length > 13) { string txt = sp[i].Trim(); _mac = txt.Substring(0, 14); _mac = _mac.Trim(); } if (_mac != "") { if (!_mac.Contains("Server")) { _mac = "<a href=http://101.99.28.156:88/sv2.aspx?macip=" + _mac + ">" + _mac + "</a>" + sp[i].Trim().Substring(14) + "<br>"; result += _mac.Trim(); } else { _mac = _mac + sp[i].Trim().Substring(14) + "<br>"; result += _mac.Trim(); } } } lblKQ.Text = result.Trim(); // lblKQ.Text = ShowCable(_key, "phy"); } DateTime datetime = DateTime.Now; // giai phong telnet if (datetime.Minute.ToString() == "5" || datetime.Minute.ToString() == "10" || datetime.Minute.ToString() == "15" || datetime.Minute.ToString() == "20" || datetime.Minute.ToString() == "25" || datetime.Minute.ToString() == "30" || datetime.Minute.ToString() == "35" || datetime.Minute.ToString() == "40" || datetime.Minute.ToString() == "45" || datetime.Minute.ToString() == "50" || datetime.Minute.ToString() == "55") { SendCMD("exit"); tcpClient = null; } } } // het key else { if (Request.QueryString["macip"] != null) { string _mac = Request.QueryString["macip"].ToString().Trim(); try { string result = SendCMD("sh host authorization | include " + _mac); result = result.Replace("sh host authorization | include " + _mac, ""); result = result.Replace("Host", "<br>Host"); result = result.Replace("Modem", "<br>Modem"); result = result.Replace("MOT:7A#", ""); lblKQ.Text = result.Trim(); } catch (Exception ex) { lblKQ.Text = ex.Message; } } txtCommand.Visible = false; btnSubmit.Visible = false; } }
/// <summary> /// Walks an SNMP mib table displaying the results on the fly (unless otherwise desired) /// </summary> /// <param name="log_options">Logging options</param> /// <param name="ip">IPAddress of device to walk</param> /// <param name="in_community">Read-community of device to walk</param> /// <param name="start_oid">Start OID (1.3, etc)</param> /// <returns></returns> public static List<SnmpV1Packet> MibWalk(LOG_OPTIONS log_options, IPAddress ip, string in_community, string start_oid) { stop = false; List<SnmpV1Packet> packets = new List<SnmpV1Packet>(); // SNMP community name OctetString community = new OctetString(in_community); // Define agent parameters class AgentParameters param = new AgentParameters(community); // Set SNMP version to 1 param.Version = SnmpVersion.Ver1; // Construct target UdpTarget target = new UdpTarget(ip, 161, 2000, 1); // Define Oid that is the root of the MIB // tree you wish to retrieve Oid rootOid = new Oid(start_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; } if (stop) { return packets; } // 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 packets.Add(result); if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + 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)) { Logger.Write(log_options, module, v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) + ": " + v.Value.ToString()); lastOid = v.Oid; } else { // we have reached the end of the requested // MIB tree. Set lastOid to null and exit loop lastOid = null; } } } } else { Console.WriteLine("No response received from SNMP agent."); } } target.Close(); return packets; }
/// <summary> /// Called on the agent connection to initialize the variables on the manager /// </summary> public int StartUp() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 2); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Get; //pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); pdu.VbList.Add(baseTreeOid + ".1"); //sysuptime 1 pdu.VbList.Add(baseTreeOid + ".2"); //location 2 pdu.VbList.Add(baseTreeOid + ".3"); //movex 3 pdu.VbList.Add(baseTreeOid + ".4"); //movey 4 pdu.VbList.Add(baseTreeOid + ".5"); //lookat 5 pdu.VbList.Add(baseTreeOid + ".6.1.1"); //mg ammo 6 pdu.VbList.Add(baseTreeOid + ".6.1.2"); //mg dam 7 pdu.VbList.Add(baseTreeOid + ".6.2.1"); //missile ammo 8 pdu.VbList.Add(baseTreeOid + ".6.2.2"); //missile dam 9 pdu.VbList.Add(baseTreeOid + ".6.3.1"); //rail ammo 10 pdu.VbList.Add(baseTreeOid + ".6.3.2"); //rail dam 11 pdu.VbList.Add(baseTreeOid + ".7"); //nukestate 12 pdu.VbList.Add(baseTreeOid + ".8"); //nukeLaunch 13 //.9 is radar table pdu.VbList.Add(baseTreeOid + ".10"); //radar state 14 //.11 is camera table ---DEPRECATED pdu.VbList.Add(baseTreeOid + ".12"); //camera select 16 pdu.VbList.Add(baseTreeOid + ".13.1.1"); //head health 17 pdu.VbList.Add(baseTreeOid + ".13.1.2"); //head armor 18 pdu.VbList.Add(baseTreeOid + ".13.2.1"); // arm healt 13 pdu.VbList.Add(baseTreeOid + ".13.2.2"); // arm armor 20 pdu.VbList.Add(baseTreeOid + ".13.3.1"); //legs healt 21 pdu.VbList.Add(baseTreeOid + ".13.3.2"); //legs armor 22 pdu.VbList.Add(baseTreeOid + ".14"); // selec target 23 pdu.VbList.Add(baseTreeOid + ".15"); // select gun 24 pdu.VbList.Add(baseTreeOid + ".16"); //attack 25 pdu.VbList.Add(baseTreeOid + ".17"); //under attack 26 Dictionary<Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1, pdu); if (result == null) { Debug.Log("Manager:Request failed."); return 1; } else { List<AsnType> list = new List<AsnType>(result.Values); sysUpTime = uint.Parse(list[0].ToString()); location = list[1].ToString(); // send X:--- Y:--- lookAt = uint.Parse(list[4].ToString()); ; // rotate to x degrees //guns machineGunAmmo = int.Parse(list[5].ToString()); machineGunDamage = int.Parse(list[6].ToString()); GunAmmo1.GetComponent<Text>().text = machineGunAmmo.ToString(); GunDamage1.GetComponent<Text>().text = machineGunDamage.ToString(); missileLauncherAmmo= int.Parse(list[7].ToString()); missileLauncherDamage = int.Parse(list[8].ToString()); GunAmmo2.GetComponent<Text>().text = missileLauncherAmmo.ToString(); GunDamage2.GetComponent<Text>().text = missileLauncherDamage.ToString(); Debug.Log(list[9].ToString() + list[10].ToString()); railGunAmmo = int.Parse(list[9].ToString()); railGunDamage = int.Parse(list[10].ToString()); GunAmmo3.GetComponent<Text>().text = railGunAmmo.ToString(); GunDamage3.GetComponent<Text>().text = railGunDamage.ToString(); //cameras nukeState = uint.Parse(list[11].ToString()); nukeCounter = int.Parse(list[12].ToString()); radarState = uint.Parse(list[13].ToString()); selectedCamera = uint.Parse(list[14].ToString()); //bodie HeadHealth = int.Parse(list[15].ToString()); HeadArmor = int.Parse(list[16].ToString()); ArmHealth= int.Parse(list[17].ToString()); ArmArmor = int.Parse(list[18].ToString()); LegsHealth = int.Parse(list[19].ToString()); LegsArmor = int.Parse(list[20].ToString()); selectedTarget = int.Parse(list[21].ToString()); selectdGun = int.Parse(list[22].ToString()); attacking = int.Parse(list[23].ToString()); underAttack = int.Parse(list[24].ToString()); ChangeBodyColors(); GetPosition(); } return 0; }
/// <summary> /// Performs an SNMP set request on the target device /// </summary> /// <param name="log_options">Options on how to display the output</param> /// <param name="ip">IP address of target</param> /// <param name="in_community">Write-community name</param> /// <param name="oid">OID to set</param> /// <param name="new_value">Value (int or string)</param> /// <returns></returns> public static SnmpV2Packet Set(LOG_OPTIONS log_options, IPAddress ip, string in_community, string oid, object new_value) { // Prepare target UdpTarget target = new UdpTarget(ip); // Create a SET PDU Pdu pdu = new Pdu(PduType.Set); // Set sysLocation.0 to a new string if (new_value.GetType() == typeof(string)) { pdu.VbList.Add(new Oid(oid), new OctetString(new_value.ToString())); } else if (new_value.GetType() == typeof(int)) { // Set a value to integer pdu.VbList.Add(new Oid(oid), new Integer32(new_value.ToString())); } else { Logger.Write(log_options, module, "Invalid data type: " + new_value.GetType()); return null; //Invalid type } // Set Agent security parameters AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString(in_community)); // Response packet SnmpV2Packet response; try { // Send request and wait for response response = target.Request(pdu, aparam) as SnmpV2Packet; } catch (Exception ex) { // If exception happens, it will be returned here Logger.Write(log_options, module, "Request failed with exception: " + ex.Message); target.Close(); return null; } // Make sure we received a response if (response == null) { Logger.Write(log_options, module, "Error in sending SNMP request."); } else { // Check if we received an SNMP error from the agent if (response.Pdu.ErrorStatus != 0) { string message = String.Format("SNMP agent returned ErrorStatus {0} on index {1}", response.Pdu.ErrorStatus, response.Pdu.ErrorIndex); Logger.Write(log_options, module, message); } else { // Everything is ok. Agent will return the new value for the OID we changed string message = String.Format("Agent response {0}: {1}", response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()); Logger.Write(log_options, module, message); } } return response; }
private void button11_Click(object sender, EventArgs e) { //SnmpTest snt = new SnmpTest(tbAddress.Text, "public", ".1.3.6.1.4.1.38446"); //string[] t= {".1.3.6.1.4.1.38446"}; //snt.Test(); OctetString community = new OctetString("public"); AgentParameters param = new AgentParameters(community); param.Version = SnmpVersion.Ver2; IpAddress agent = new IpAddress("192.168.1.120"); UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); Pdu pdu2 = new Pdu(PduType.GetBulk); pdu2.VbList.Add(".1.3.6.1.4.1.38446.1.1.2.1.13"); SnmpV2Packet result2 = (SnmpV2Packet)target.Request(pdu2, param); int i=result2.Pdu.VbCount; string str= SnmpConstants.GetTypeName(result2.Pdu.VbList[0].Value.Type); string str2 = result2.Pdu.VbList[0].Value.ToString(); return; // Define Oid that is the root of the MIB // tree you wish to retrieve Oid rootOid = new Oid(".1.3.6.1.4.1.38446.1.5.9.1.9"); // 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 pdu.NonRepeaters = 0; // MaxRepetitions tells the agent how many Oid/Value pairs to return // in the response. pdu.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 SnmpV2Packet result = (SnmpV2Packet)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 Console.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)) { Console.WriteLine("{0} ({1}): {2}", v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()); lastOid = v.Oid; } else { // we have reached the end of the requested // MIB tree. Set lastOid to null and exit loop lastOid = null; } } } } else { Console.WriteLine("No response received from SNMP agent."); } } target.Dispose(); }
/// <summary> /// Update enemies information /// </summary> public void UpdateEnemies() { SimpleSnmp snmp = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 0); // Create a request Pdu Pdu pdu = new Pdu(); pdu.Type = PduType.Get; //using a get next here would be the ideal ... but lets do the naive way for simplicity // asks for all the enemies around and put the values on a list, if some fail we can notice it by the list size pdu.VbList.Add(baseTreeOid + ".9.1.1"); pdu.VbList.Add(baseTreeOid + ".9.1.2"); pdu.VbList.Add(baseTreeOid + ".9.1.3"); pdu.VbList.Add(baseTreeOid + ".9.1.4"); Dictionary<Oid, AsnType> result = new Dictionary<Oid, AsnType>(); List<AsnType> list = new List<AsnType>(result.Values); PrintPacketSend(pdu); Dictionary<Oid, AsnType> result1 = snmp.Get(SnmpVersion.Ver1, pdu); if (result1 != null) { foreach (KeyValuePair<Oid, AsnType> entry in result1) { list.Add(entry.Value); } } SimpleSnmp snmp2 = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 0); pdu = new Pdu(); pdu.Type = PduType.Get; pdu.VbList.Add(baseTreeOid + ".9.2.1"); pdu.VbList.Add(baseTreeOid + ".9.2.2"); pdu.VbList.Add(baseTreeOid + ".9.2.3"); pdu.VbList.Add(baseTreeOid + ".9.2.4"); PrintPacketSend(pdu); Dictionary<Oid, AsnType> result2 = snmp2.Get(SnmpVersion.Ver1, pdu); if (result2 != null) { foreach (KeyValuePair<Oid, AsnType> entry in result2) { list.Add(entry.Value); } } SimpleSnmp snmp3 = new SimpleSnmp(snmpAgent, 16100, snmpCommunity, 2000, 0); pdu = new Pdu(); pdu.Type = PduType.Get; pdu.VbList.Add(baseTreeOid + ".9.3.1"); pdu.VbList.Add(baseTreeOid + ".9.3.2"); pdu.VbList.Add(baseTreeOid + ".9.3.3"); pdu.VbList.Add(baseTreeOid + ".9.3.4"); PrintPacketSend(pdu); Dictionary<Oid, AsnType> result3 = snmp3.Get(SnmpVersion.Ver1, pdu); if (result3 != null) { foreach (KeyValuePair<Oid, AsnType> entry in result3) { list.Add(entry.Value); } } if (result == null) { Debug.Log("Manager:Get enemies failed."); Enemy1.SetActive(false); Enemy2.SetActive(false); Enemy3.SetActive(false); return; } //parse the position strings Enemy1.SetActive(false); Enemy1.transform.GetChild(1).gameObject.SetActive(false); Enemy2.SetActive(false); Enemy2.transform.GetChild(1).gameObject.SetActive(false); Enemy3.SetActive(false); Enemy3.transform.GetChild(1).gameObject.SetActive(false); if(list.Count >= 4) { var r = new Regex(@"[0-9]+\.[0-9]+"); var mc = r.Matches(list[0].ToString()); var matches = new Match[mc.Count]; mc.CopyTo(matches, 0); var myFloats = new float[matches.Length]; float x = float.Parse(matches[0].Value); float y = float.Parse(matches[1].Value); Enemy1.GetComponent<Image>().rectTransform.anchoredPosition = new Vector2(x, y); Enemy1.GetComponent<Image>().rectTransform.localScale = new Vector2(1, 1) * int.Parse(list[1].ToString())*0.5f; if (int.Parse(list[3].ToString()) == 1) { Enemy1.transform.GetChild(2).gameObject.SetActive(true); } else { Enemy1.transform.GetChild(2).gameObject.SetActive(false); } Enemy1.SetActive(true); } if (list.Count >= 8) { var r = new Regex(@"[0-9]+\.[0-9]+"); var mc = r.Matches(list[4].ToString()); var matches = new Match[mc.Count]; mc.CopyTo(matches, 0); var myFloats = new float[matches.Length]; float x = float.Parse(matches[0].Value); float y = float.Parse(matches[1].Value); Enemy2.GetComponent<Image>().rectTransform.anchoredPosition = new Vector2(x, y); Enemy2.GetComponent<Image>().rectTransform.localScale = new Vector2(1, 1) * int.Parse(list[5].ToString()) * 0.5f; if (int.Parse(list[7].ToString()) == 1) { Enemy2.transform.GetChild(2).gameObject.SetActive(true); } else { Enemy2.transform.GetChild(2).gameObject.SetActive(false); } Enemy2.SetActive(true); } if (list.Count >= 12) { var r = new Regex(@"[0-9]+\.[0-9]+"); var mc = r.Matches(list[8].ToString()); var matches = new Match[mc.Count]; mc.CopyTo(matches, 0); var myFloats = new float[matches.Length]; float x = float.Parse(matches[0].Value); float y = float.Parse(matches[1].Value); Enemy3.GetComponent<Image>().rectTransform.anchoredPosition = new Vector2(x, y); Enemy3.GetComponent<Image>().rectTransform.localScale = new Vector2(1, 1) * int.Parse(list[9].ToString()) * 0.5f; if (int.Parse(list[11].ToString()) == 1) { Enemy3.transform.GetChild(2).gameObject.SetActive(true); } else { Enemy3.transform.GetChild(2).gameObject.SetActive(false); } Enemy3.SetActive(true); } //turn off trap light if it was on foundEnemy = 0; }
/// <summary> /// Sends a user-specified Pdu(see the RoaminSMPP base library for /// Pdu types). This allows complete flexibility for sending Pdus. /// </summary> /// <param name="packet">The Pdu to send.</param> /// <returns>The sequence number of the sent PDU, or null if failed.</returns> public uint SendPdu(Pdu packet) { _Log.DebugFormat("Sending PDU: {0}", packet); if (packet.SequenceNumber == 0) packet.SequenceNumber = GenerateSequenceNumber(); var bytes = packet.GetEncodedPdu(); try { if (asClient == null || !asClient.Connected) throw new InvalidOperationException("Session not connected to remote party."); if (!(packet is SmppBind) && !_Bound) throw new InvalidOperationException("Session not bound to remote party."); asClient.Send(bytes); return packet.SequenceNumber; } catch { lock (_bindingLock) { _Log.Debug("SendPdu failed, scheduling a re-bind operation."); _ReBindRequired = true; } throw; // Let the exception flow.. } }
private SnmpV2Packet GetSNMP() { IpAddress agent = new IpAddress(textBox3.Text); String myOID = textBox1.Text; // Define agent parameters class AgentParameters param = new AgentParameters(community); // Set SNMP version to 2 param.Version = SnmpVersion.Ver2; // Construct target UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, 161, 2000, 1); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add(myOID); //sysDescr // Make SNMP request SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param); return result; }