Utility class to enable simplified access to SNMP version 1 and version 2 requests and replies.
Use this class if you are not looking for "deep" SNMP functionality. Design of the class is based around providing simplest possible access to SNMP operations without getting stack into details. If you are using the simplest way, you will leave SuppressExceptions flag to true and get all errors causing methods to return "null" result which will not tell you why operation failed. You can change the SuppressExceptions flag to false and catch any and all exception throwing errors. Either way, have fun.
コード例 #1
1
    /// <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());
    }
コード例 #2
0
        /// 
        /// <summary>
        /// Executes the installation process on the SNMP agent.
        /// </summary>
        /// <param name="ts">Target's settings</param>
        /// <param name="uploadFolder">Path of folder with exe update within it</param>
        /// <returns>True if installation was executed successfully</returns>
        public static bool setExecute(TargetSettings ts, string uploadFolder)
        {
            SimpleSnmp snmp = new SimpleSnmp(ts.TargetServer, ts.Community);

              if(!snmp.Valid)
              {
            return false;
              }

              string d = ts.DestinationFolder.Substring(1);
              int i = uploadFolder.LastIndexOf("\\") + 1;
              string relativePath = uploadFolder.Substring(i);
              string destination = d.Replace("/", "\\");
              string batFile = ts.RootPath + destination + relativePath + "\\UpdateVersion.bat";

              Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver2,
                                                    new Vb[] {
                                                    new Vb(new Oid("1.3.6.1.4.1.2566.127.1.1.157.3.1.1.10.0"),
                                                           new OctetString(batFile))});

              if(result != null)
              {
            return true;
              }
              return false;
        }
コード例 #3
0
        ///
        /// <summary>
        /// Finds the site name of the SNMP Agent.  If site name is retreived, then SNMP commands can be issued.
        /// First tries a DVM command, then if it is not DVM, uses a DVMS command to see if it is instead a DVMS device.
        /// </summary>
        /// <param name="strHost">IP address</param>
        /// <param name="strComm">Community String</param>
        /// <returns>SNMP agent's Site Name</returns>
        public static string getSiteName(string strHost, string strComm)
        {
            SimpleSnmp snmp = new SimpleSnmp(strHost, strComm);

              if(!snmp.Valid)
              {
            return null;
              }

              Dictionary<Oid, AsnType> resultDVM = snmp.Get(SnmpVersion.Ver1, new string[] {".1.3.6.1.4.1.2566.127.1.1.157.3.1.1.1.0"});

              if(resultDVM != null)
              {
            foreach(KeyValuePair<Oid, AsnType> kvp in resultDVM)
            {
              return kvp.Value.ToString();
            }
              }

              //Now tries DVMS command
              Dictionary<Oid, AsnType> resultDVMs = snmp.Get(SnmpVersion.Ver1, new string[] { ".1.3.6.1.4.1.2566.127.1.1.152.3.1.1.1.0" });

              if(resultDVMs != null)
              {
            foreach(KeyValuePair<Oid, AsnType> kvp in resultDVMs)
            {
              return kvp.Value.ToString();
            }
              }
              return null;
        }
コード例 #4
0
       public bool SnmpSetTest(string host, string community, string oid,string octetStromg)
       {

           try
           {
               SimpleSnmp snmp = new SimpleSnmp(host, community);
               if (!snmp.Valid)
               {
                   return false;
               }
               Dictionary<Oid, AsnType> result = snmp.Set(SnmpVersion.Ver1,
                                                           new Vb[] { 
                                                    new Vb(new Oid(oid), 
                                                           new OctetString(octetStromg))
                                                    });
               if (result == null)
               {
                   return false;
               }

               LogResult(result);
               return true;
           }
           catch (Exception ex)
           {
               return false;
           }
       }
コード例 #5
0
       public bool SnmpGetTest(string host, string community, string oid)
       {

           try
           {
               SimpleSnmp snmp = new SimpleSnmp(host, community);
               if (!snmp.Valid)
               {
                   return false;
               }
               Dictionary<Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1,
                                                         new string[] { oid });
               if (result == null)
               {
                   return false;
               }

               LogResult(result);
               return true;
           }
           catch (Exception ex)
           {
               return false;
           }
       }
コード例 #6
0
        private static string GetDeviceMessage(SimpleSnmp snmp)
        {
            //.1.3.6.1.2.1.25.3.2.1.5.1
            var deviceStatus = Convert.ToInt32(snmp.Get(SnmpVersion.Ver2, new[] {".1.3.6.1.2.1.25.3.2.1.5.1"})
                                               	[new Oid(".1.3.6.1.2.1.25.3.2.1.5.1")].ToString());

            string deviceMessage = null;
            switch (deviceStatus)
            {
                case 1: //nieznany
                    deviceMessage = "Nieznany";
                    break;

                case 2: //pracuje
                    deviceMessage = "Pracuje";
                    break;

                case 3: //ostrzeżenie
                    deviceMessage = "Ostrzeżenie";
                    break;

                case 4: //testowy
                    deviceMessage = "Stan testowy";
                    break;

                case 5: //wyłączony
                    deviceMessage = "Niedostępny";
                    break;
            }

            return deviceMessage;
        }
コード例 #7
0
       public bool SnmpBulkGetTest(string host, string community, string[] oids)
       {

           try
           {
               SimpleSnmp snmp = new SimpleSnmp(host, community);
               if (!snmp.Valid)
               {
                   return false;
               }
               Dictionary<Oid, AsnType> result = snmp.GetBulk(oids);
               if (result == null)
               {
                   return false;
               }

               LogResult(result);
               return true;
           }
           catch (Exception)
           {
               return false;
           }
       }
コード例 #8
0
ファイル: EASYSNMP.cs プロジェクト: hw901013/hw901013
        /// <summary>
        /// 读取根节点
        /// </summary>
        /// <param name="Ip">ip地址</param>
        /// <param name="outinfo">输出到那个字典</param>
        public void SnmpAgent(Dictionary<string, List<string>> Ip_OID, Dictionary<string, Dictionary<string, string>> outinfo)
        {
            #region 新方法

            foreach (KeyValuePair<string, List<string>> MyKVP in Ip_OID)
            {
                try
                {
                    SimpleSnmp snmp = new SimpleSnmp(MyKVP.Key, "public");
                    if (!snmp.Valid)
                    {
                        continue;
                    }
                    Dictionary<string, string> Info = new Dictionary<string, string>();
                    VbCollection col = new VbCollection();
                    TrapAgent agent = new TrapAgent();
                    foreach (string bc in MyKVP.Value)
                    {
                        Dictionary<Oid, AsnType> result = snmp.Walk(SnmpVersion.Ver2, bc);
                        if (result == null)
                        {
                            continue;
                        }
                        foreach (KeyValuePair<Oid, AsnType> kvp in result)
                        {
                            try
                            {
                                if (!Info.ContainsKey(kvp.Key.ToString()))
                                {
                                    Info.Add(kvp.Key.ToString(), kvp.Value.ToString());
                                }
                                else
                                {
                                    Info.Remove(kvp.Key.ToString());
                                    Info.Add(kvp.Key.ToString(), kvp.Value.ToString());
                                }

                            }
                            catch (Exception ex)
                            {
                                msg.SaveTempMessage(ex.Source.ToString(), ex.Message.ToString(), DateTime.Now.ToString());
                            }
                        }
                    }
                    if (!outinfo.ContainsKey(MyKVP.Key))
                    {
                        outinfo.Add(MyKVP.Key, Info);
                    }
                    else
                    {
                        outinfo.Remove(MyKVP.Key);
                        outinfo[MyKVP.Key] = Info;
                    }
                }
                catch (Exception ex)
                {
                    msg.SaveTempMessage(ex.Source.ToString(), ex.Message.ToString(), DateTime.Now.ToString());
                }
            }
            #endregion
        }
コード例 #9
0
        private static string GetPrinterMessage(SimpleSnmp snmp)
        {
            //.1.3.6.1.2.1.25.3.5.1.1.1
            var printerStatus = Convert.ToInt32(snmp.Get(SnmpVersion.Ver2, new[] {".1.3.6.1.2.1.25.3.5.1.1.1"})
                                                    [new Oid(".1.3.6.1.2.1.25.3.5.1.1.1")].ToString());

            string printerMessageStatus = null;
            switch (printerStatus)
            {
                case 1: //inny
                    printerMessageStatus = "Inny";
                    break;

                case 2: //nieznany
                    printerMessageStatus = "Nieznany";
                    break;

                case 3: //zajęta
                    printerMessageStatus = "Zajęta";
                    break;

                case 4: //drukuje
                    printerMessageStatus = "Drukuje";
                    break;

                case 5: //rozgrzewa się
                    printerMessageStatus = "Rozgrzewa się";
                    break;
            }
            return printerMessageStatus;
        }
コード例 #10
0
    /// <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.");
        }
			
    }
コード例 #11
0
    /// <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);
        }
    }
コード例 #12
0
    /// <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;

    }
コード例 #13
0
        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var bg = (BackgroundWorker) sender;
            var database = new PrinterDatabaseEntities();
            var arguments = e.Argument as object[];

            var community = "";
            var ipFrom = "";
            var ipTo = "";
            var scan = false;

            if (arguments != null)
            {
                community = (string) arguments[0];
                scan = (bool) arguments[1];
                ipFrom = (string) arguments[2];
                ipTo = (string) arguments[3];
            }

            var snmp = new SimpleSnmp("", community)
            {
                PeerPort = 161,
                Timeout = 25,
                MaxRepetitions = 20
            };

            if (scan)
            {
                #region
                CleanDatabase(database);

                var ipFromSplit = ipFrom.Split('.');
                var ipToSplit = ipTo.Split('.');
                var ipFromLastOctet = Convert.ToInt32(ipFromSplit[3]);
                var ipToLastOctet = Convert.ToInt32(ipToSplit[3]);

                var ipRestOctets = string.Format("{0}.{1}.{2}.", ipFromSplit[0], ipFromSplit[1], ipFromSplit[2]);

                if (ipToLastOctet - ipFromLastOctet == 0)
                    bg.ReportProgress(0, 1);
                else
                    bg.ReportProgress(0, ipToLastOctet - ipFromLastOctet + 1);

                for (var i = ipFromLastOctet; i <= ipToLastOctet; i++)
                {
                    var ipAddress = string.Format("{0}{1}", ipRestOctets, i);

                    snmp.PeerIP = IPAddress.Parse(string.Format("{0}{1}", ipRestOctets, i));

                    try
                    {
                        var printerFound = new Printer
                                           	{
                                           		ID = Guid.NewGuid(),
                                           		IpAddress = ipAddress,
                                           		LastStatus = GetPrinterStatus(snmp),
                                           		MacAddress = GetMac(ipAddress)
                                           	};

                        database.Printers.AddObject(printerFound);
                    }
            // ReSharper disable EmptyGeneralCatchClause
                    catch{ }
            // ReSharper restore EmptyGeneralCatchClause

                    bg.ReportProgress(0);
                }
                database.SaveChanges();
                #endregion
            }
            else
            {
                #region
                bg.ReportProgress(0, 1);
                var tempPrintersList = new List<Printer>();
                foreach (var printer in database.Printers)
                {
                    snmp.PeerIP = IPAddress.Parse(printer.IpAddress);
                    tempPrintersList.Add(new Printer
                                            {
                                                ID = Guid.NewGuid(),
                                                IpAddress = printer.IpAddress,
                                                LastStatus = GetPrinterStatus(snmp),
                                                MacAddress = GetMac(printer.IpAddress),
                                            });

                    bg.ReportProgress(0);
                }

                //usuwanie z bazy
                CleanDatabase(database);

                //dodawanie do bazy
                foreach (var printer in tempPrintersList)
                {
                    database.Printers.AddObject(printer);
                }
                database.SaveChanges();
                #endregion
            }
        }
コード例 #14
0
        private static string GetRestOfMessages(SimpleSnmp snmp)
        {
            var otherStatuses = Encoding.ASCII.GetBytes(snmp.Get(SnmpVersion.Ver2, new[] { ".1.3.6.1.2.1.25.3.5.1.2.1" })
                                                        [new Oid(".1.3.6.1.2.1.25.3.5.1.2.1")].ToString());

            var otherStatus = otherStatuses[0];

            var setFlags = Enum.ToObject(typeof (OtherEnum), otherStatus).ToString();

            var flagsList = new List<string>();
            if(setFlags.Contains(","))
            {
                flagsList = setFlags.Replace(" ", string.Empty).Split(',').ToList();
            }
            else
            {
                flagsList.Add(setFlags);
            }

            var otherMessage = "";
            for (var i = 0; i < flagsList.Count; i++)
            {
                switch (flagsList[i])
                {
                    case "ServiceRequested":
                        otherMessage += "Potrzebny serwis";
                        break;

                    case "Offline":
                        otherMessage += "Offline";
                        break;

                    case "Jammed":
                        otherMessage += "Zablokowany";
                        break;

                    case "DoorOpen":
                        otherMessage += "Otwarte drzwiczki";
                        break;

                    case "NoToner":
                        otherMessage += "Brak tonera";
                        break;

                    case "LowToner":
                        otherMessage += "Mało tonera";
                        break;

                    case "NoPaper":
                        otherMessage += "Brak papieru";
                        break;

                    case "LowPaper":
                        otherMessage += "Mało papieru";
                        break;
                }

                if (flagsList.Count > 1 && i < flagsList.Count - 1)
                {
                    otherMessage += ", ";
                }
            }

            return otherMessage;
        }
コード例 #15
0
        private static string GetPrinterStatus(SimpleSnmp snmp)
        {
            //informacje o urządzeniu z systemu
            var deviceMessage = GetDeviceMessage(snmp);

            //informacje o drukarce
            var printerMessage = GetPrinterMessage(snmp);

            //reszta potrzebnych informacji
            var restMessage = GetRestOfMessages(snmp);

            return string.Format("{0}, {1}, Stany dodatkowe: {2}", deviceMessage, printerMessage, restMessage);
        }
コード例 #16
0
    /// <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;
    }
コード例 #17
0
    /// <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();
    }
コード例 #18
0
ファイル: module.cs プロジェクト: Proxx/Proxx.SNMP
 protected override void BeginProcessing()
 {
     base.BeginProcessing();
     _SimpleSnmp = new SimpleSnmp();
     _SimpleSnmp.Community = _Community;
     _SimpleSnmp.Retry = _Retry;
     _SimpleSnmp.Timeout = _TimeOut;
 }
コード例 #19
0
ファイル: module.cs プロジェクト: Proxx/Proxx.SNMP
 protected override void BeginProcessing()
 {
     base.BeginProcessing();
     _SimpleSnmp = new SimpleSnmp();
     _SimpleSnmp.Community = _Community;
     _SimpleSnmp.Retry = _Retry;
     _SimpleSnmp.Timeout = _TimeOut;
     if (_Force) { _RootOID = null; }
     else { _RootOID = new Oid(_Oid.ToString()); }
 }
コード例 #20
0
ファイル: Form1.cs プロジェクト: imbaaa/EhlProjects
        private void SNMPGetInfo()
        {
            if (this.krbSNMP.Checked)
            {
                try
                {
                    SimpleSnmp snmp = new SimpleSnmp(Properties.Settings.Default.ip, this.kcbCommunity.SelectedItem.ToString());
                    snmp.Retry = 5;
                    snmp.Timeout = 60000;
                    snmp.SuppressExceptions = false;
                    string oid = Properties.Settings.Default.oid;
                    Dictionary<Oid, AsnType> result = null;
                    if (this.kcbMethod.SelectedItem.ToString() == "Get NEXT")
                    {
                        Pdu pdu = new Pdu();
                        pdu.Type = PduType.GetNext;
                        pdu.VbList.Add(oid);
                        result = snmp.GetNext(SnmpVersion.Ver1, pdu);
                    }
                    else if (this.kcbMethod.SelectedItem.ToString() == "GET")
                    {
                        // Create a request Pdu
                        Pdu pdu = new Pdu();
                        pdu.Type = PduType.Get;
                        pdu.VbList.Add(oid);
                        result = snmp.GetNext(SnmpVersion.Ver1, pdu);
                    }
                    else if (this.kcbMethod.SelectedItem.ToString() == "Walk")
                    {
                        result = snmp.Walk(SnmpVersion.Ver2, oid);
                    }
                    else if (this.kcbMethod.SelectedItem.ToString() == "Get BULK")
                    {
                        //Using GetBulk
                        Pdu pdu = new Pdu();
                        pdu.Type = PduType.GetBulk;
                        pdu.VbList.Add(oid);
                        pdu.NonRepeaters = 0;
                        pdu.MaxRepetitions = Convert.ToInt32(this.krypTxtBxRepeaters.Text);
                        result = snmp.GetBulk(pdu);
                    }

                    ktbResult.SuspendLayout();
                    ktbResult.Clear();
                    if (result == null)
                    {
                        ktbResult.AppendText("Request failed.\r\n");
                    }
                    else
                    {
                        ktbResult.SuspendLayout();
                        foreach (KeyValuePair<Oid, AsnType> entry in result)
                        {
                            ktbResult.AppendText(String.Format("{0} = {1}: {2}\r\n", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
                              entry.Value.ToString()));
                        }
                        ktbResult.ResumeLayout();
                    }
                }
                catch (Exception snmpEx)
                {
                    ComponentFactory.Krypton.Toolkit.KryptonMessageBox.Show(snmpEx.Message,
                        "SNMP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                ktbResult.Focus();
                ktbResult.SelectionStart = 0;
                ktbResult.SelectionLength = 0;
                ktbResult.ScrollToCaret();
                ktbResult.ResumeLayout();
            }
        }
コード例 #21
0
    /// <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());
            }
        }
    }
コード例 #22
0
        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.");
        }
コード例 #23
0
    /// <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 );

        }



    }
コード例 #24
0
ファイル: SNMPUtils.cs プロジェクト: JonBons/Opserver
 public static Dictionary<Oid, AsnType> Walk(string ip, string oid, int port = 161, int timeout = 2000, int retries = 1)
 {
     var snmp = new SimpleSnmp(ip, port, "s3cur3", timeout, retries);
     return snmp.Walk(SnmpVersion.Ver2, oid);
 }