Beispiel #1
0
    public static void GetRequest(string[] argv)
    {
        int    commlength, miblength, datatype, datalength, datastart;
        int    uptime = 0;
        string output;
        SNMP   conn = new SNMP();

        byte[] response = new byte[1024];
        System.Web.HttpContext.Current.Response.Write("Device SNMP information:");

        // Send sysName SNMP request
        response = conn.get("get", argv[0], argv[1], ".1.3.6.1.2.1.1.4.0");
        if (response[0] == 0xff)
        {
            System.Web.HttpContext.Current.Response.Write("No response from " + argv[0]);
            return;
        }

        // If response, get the community name and MIB lengths
        commlength = Convert.ToInt16(response[6]);
        miblength  = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMP response
        datatype   = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart  = 26 + commlength + miblength;
        output     = Encoding.ASCII.GetString(response, datastart, datalength);
        System.Web.HttpContext.Current.Response.Write(" - sysName : " + output);

        // Send a SysUptime SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.3.0");
        if (response[0] == 0xff)
        {
            System.Web.HttpContext.Current.Response.Write("No response from " + argv[0]);
            return;
        }

        // Get the community and MIB lengths of the response
        commlength = Convert.ToInt16(response[6]);
        miblength  = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMp response
        datatype   = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart  = 26 + commlength + miblength;

        // The sysUptime value may by a multi-byte integer
        // Each byte read must be shifted to the higher byte order
        while (datalength > 0)
        {
            uptime = (uptime << 8) + response[datastart++];
            datalength--;
        }
        System.Web.HttpContext.Current.Response.Write(" - sysUptime : " + uptime);
    }
Beispiel #2
0
        /// <summary>
        /// Uses DAT SNMP set
        /// </summary>
        /// <param name="sov">The sov.</param>
        /// <param name="exeTime">The executable time.</param>
        /// <returns></returns>
        private string SnmpSet(SnmpOidValue sov, out int exeTime)
        {
            string result = string.Empty;

            exeTime = 0;
            int startCnt = 0;

            try
            {
                startCnt = Environment.TickCount;
                result   = SNMP.Set(sov).ToString();
                exeTime  = Environment.TickCount - startCnt;
            }
            catch (Exception ex)
            {
                GetLastError = ex.JoinAllErrorMessages();
            }
            return(result);
        }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="exeTime"></param>
        /// <param name="pOID"></param>
        /// <returns></returns>
        public string GetNextSnmp(out int exeTime, string pOID, ref string nextString)
        {
            string result = string.Empty;

            exeTime      = 0;
            GetLastError = string.Empty;

            int startCnt = Environment.TickCount;

            try
            {
                SnmpOidValue oidData = SNMP.GetNext(pOID);
                exeTime    = Environment.TickCount - startCnt;
                nextString = oidData.Oid;
                result     = oidData.Value.ToString();
                if (nextString[0] == '.')
                {
                    nextString = nextString.Substring(1);
                }
            }
            catch (SnmpException se)
            {
                SetLextmError(se);
            }
            catch (Exception ex)
            {
                GetLastError = "ERROR: " + ex.JoinAllErrorMessages();
            }
            finally
            {
                if (exeTime == 0 && startCnt != 0)
                {
                    exeTime = Environment.TickCount - startCnt;
                }
                if (result.Contains("NoSuch"))
                {
                    GetLastError = "ERROR: " + result;
                }
            }

            return(result);
        }
        private async void Work()
        {
            DisplayStatusMessage = false;
            IsWorking            = true;

            // Measure time
            StartTime = DateTime.Now;
            stopwatch.Start();
            dispatcherTimer.Tick    += DispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Start();
            EndTime = null;

            QueryResult.Clear();
            Responses = 0;

            // Change the tab title (not nice, but it works)
            Window window = Application.Current.Windows.OfType <Window>().FirstOrDefault(x => x.IsActive);

            if (window != null)
            {
                foreach (TabablzControl tabablzControl in VisualTreeHelper.FindVisualChildren <TabablzControl>(window))
                {
                    tabablzControl.Items.OfType <DragablzTabItem>().First(x => x.ID == _tabId).Header = Host;
                }
            }

            // Try to parse the string into an IP-Address
            IPAddress.TryParse(Host, out IPAddress ipAddress);

            try
            {
                // Try to resolve the hostname
                if (ipAddress == null)
                {
                    IPHostEntry ipHostEntrys = await Dns.GetHostEntryAsync(Host);

                    foreach (IPAddress ipAddr in ipHostEntrys.AddressList)
                    {
                        if (ipAddr.AddressFamily == AddressFamily.InterNetwork && SettingsManager.Current.SNMP_ResolveHostnamePreferIPv4)
                        {
                            ipAddress = ipAddr;
                            continue;
                        }
                        else if (ipAddr.AddressFamily == AddressFamily.InterNetworkV6 && !SettingsManager.Current.SNMP_ResolveHostnamePreferIPv4)
                        {
                            ipAddress = ipAddr;
                            continue;
                        }
                    }

                    // Fallback --> If we could not resolve our prefered ip protocol for the hostname
                    if (ipAddress == null)
                    {
                        foreach (IPAddress ipAddr in ipHostEntrys.AddressList)
                        {
                            ipAddress = ipAddr;
                            continue;
                        }
                    }
                }
            }
            catch (SocketException) // This will catch DNS resolve errors
            {
                Finished();

                StatusMessage        = string.Format(LocalizationManager.GetStringByKey("String_CouldNotResolveHostnameFor"), Host);
                DisplayStatusMessage = true;

                return;
            }

            // SNMP...
            SNMPOptions snmpOptions = new SNMPOptions()
            {
                Port    = SettingsManager.Current.SNMP_Port,
                Timeout = SettingsManager.Current.SNMP_Timeout
            };

            SNMP snmp = new SNMP();

            snmp.Received        += Snmp_Received;
            snmp.Timeout         += Snmp_Timeout;
            snmp.Error           += Snmp_Error;
            snmp.UserHasCanceled += Snmp_UserHasCanceled;
            snmp.Complete        += Snmp_Complete;

            switch (Mode)
            {
            case SNMPMode.Get:
                if (Version != SNMPVersion.v3)
                {
                    snmp.Getv1v2cAsync(Version, ipAddress, Community, OID, snmpOptions);
                }
                else
                {
                    snmp.Getv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, snmpOptions);
                }

                break;

            case SNMPMode.Walk:
                if (Version != SNMPVersion.v3)
                {
                    snmp.Walkv1v2cAsync(Version, ipAddress, Community, OID, SettingsManager.Current.SNMP_WalkMode, snmpOptions);
                }
                else
                {
                    snmp.Walkv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, SettingsManager.Current.SNMP_WalkMode, snmpOptions);
                }

                break;

            case SNMPMode.Set:
                if (Version != SNMPVersion.v3)
                {
                    snmp.Setv1v2cAsync(Version, ipAddress, Community, OID, Data, snmpOptions);
                }
                else
                {
                    snmp.Setv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, Data, snmpOptions);
                }
                break;
            }

            // Add to history...
            AddHostToHistory(Host);
            AddOIDToHistory(OID);
        }
Beispiel #5
0
 public CommandField(byte ID, Variable Data)
 {
     FieldID   = ID;
     FieldData = SNMP.EncodeVarBind(Data);
 }
Beispiel #6
0
 public Variable AsVarBind()
 {
     return(SNMP.DecodeVarBind(FieldData));
 }
Beispiel #7
0
    public static void Main(string[] argv)
    {
        int    commlength, miblength, datatype, datalength, datastart;
        int    uptime = 0;
        string output;
        SNMP   conn = new SNMP();

        byte[] response = new byte[1024];

        Console.WriteLine("Device SNMP information:");

        // Send sysName SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.5.0");
        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // If response, get the community name and MIB lengths
        commlength = Convert.ToInt16(response[6]);
        miblength  = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMP response
        datatype   = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart  = 26 + commlength + miblength;
        output     = Encoding.ASCII.GetString(response, datastart, datalength);
        Console.WriteLine("  sysName - Datatype: {0}, Value: {1}",
                          datatype, output);

        // Send a sysLocation SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.6.0");
        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // If response, get the community name and MIB lengths
        commlength = Convert.ToInt16(response[6]);
        miblength  = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMP response
        datatype   = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart  = 26 + commlength + miblength;
        output     = Encoding.ASCII.GetString(response, datastart, datalength);
        Console.WriteLine("  sysLocation - Datatype: {0}, Value: {1}", datatype, output);

        // Send a sysContact SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.4.0");
        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // Get the community and MIB lengths
        commlength = Convert.ToInt16(response[6]);
        miblength  = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMP response
        datatype   = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart  = 26 + commlength + miblength;
        output     = Encoding.ASCII.GetString(response, datastart, datalength);
        Console.WriteLine("  sysContact - Datatype: {0}, Value: {1}",
                          datatype, output);

        // Send a SysUptime SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.3.0");
        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // Get the community and MIB lengths of the response
        commlength = Convert.ToInt16(response[6]);
        miblength  = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMp response
        datatype   = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart  = 26 + commlength + miblength;

        // The sysUptime value may by a multi-byte integer
        // Each byte read must be shifted to the higher byte order
        while (datalength > 0)
        {
            uptime = (uptime << 8) + response[datastart++];
            datalength--;
        }
        Console.WriteLine("  sysUptime - Datatype: {0}, Value: {1}",
                          datatype, uptime);
    }
Beispiel #8
0
    public static void Main(string[] argv)
    {
        int commlength, miblength, datatype, datalength, datastart;
        int uptime = 0;
        string output;
        SNMP conn = new SNMP();
        byte[] response = new byte[1024];

        Console.WriteLine("Device SNMP information:");

        // Send sysName SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.5.0");
        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // If response, get the community name and MIB lengths
        commlength = Convert.ToInt16(response[6]);
        miblength = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMP response
        datatype = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart = 26 + commlength + miblength;
        output = Encoding.ASCII.GetString(response, datastart, datalength);
        Console.WriteLine("  sysName - Datatype: {0}, Value: {1}",
                datatype, output);

        // Send a sysLocation SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.6.0");
        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // If response, get the community name and MIB lengths
        commlength = Convert.ToInt16(response[6]);
        miblength = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMP response
        datatype = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart = 26 + commlength + miblength;
        output = Encoding.ASCII.GetString(response, datastart, datalength);
        Console.WriteLine("  sysLocation - Datatype: {0}, Value: {1}", datatype, output);

        // Send a sysContact SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.4.0");
        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // Get the community and MIB lengths
        commlength = Convert.ToInt16(response[6]);
        miblength = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMP response
        datatype = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart = 26 + commlength + miblength;
        output = Encoding.ASCII.GetString(response, datastart, datalength);
        Console.WriteLine("  sysContact - Datatype: {0}, Value: {1}",
                datatype, output);

        // Send a SysUptime SNMP request
        response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.3.0");

        if (response[0] == 0xff)
        {
            Console.WriteLine("No response from {0}", argv[0]);
            return;
        }

        // Get the community and MIB lengths of the response
        commlength = Convert.ToInt16(response[6]);
        miblength = Convert.ToInt16(response[23 + commlength]);

        // Extract the MIB data from the SNMp response
        datatype = Convert.ToInt16(response[24 + commlength + miblength]);
        datalength = Convert.ToInt16(response[25 + commlength + miblength]);
        datastart = 26 + commlength + miblength;

        // The sysUptime value may by a multi-byte integer
        // Each byte read must be shifted to the higher byte order
        while (datalength > 0)
        {
            uptime = (uptime << 8) + response[datastart++];
            datalength--;
        }
        Console.WriteLine("  sysUptime - Datatype: {0}, Value: {1}",
               datatype, uptime);
    }
Beispiel #9
0
        private async void Work()
        {
            DisplayStatusMessage = false;
            IsWorking            = true;

            // Measure time
            StartTime = DateTime.Now;
            stopwatch.Start();
            dispatcherTimer.Tick    += DispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Start();
            EndTime = null;

            QueryResult.Clear();
            Responses = 0;

            // Try to parse the string into an IP-Address
            IPAddress.TryParse(Host, out IPAddress ipAddress);

            try
            {
                // Try to resolve the hostname
                if (ipAddress == null)
                {
                    IPHostEntry ipHostEntrys = await Dns.GetHostEntryAsync(Host);

                    foreach (IPAddress ipAddr in ipHostEntrys.AddressList)
                    {
                        if (ipAddr.AddressFamily == AddressFamily.InterNetwork && SettingsManager.Current.SNMP_ResolveHostnamePreferIPv4)
                        {
                            ipAddress = ipAddr;
                            continue;
                        }
                        else if (ipAddr.AddressFamily == AddressFamily.InterNetworkV6 && !SettingsManager.Current.SNMP_ResolveHostnamePreferIPv4)
                        {
                            ipAddress = ipAddr;
                            continue;
                        }
                    }

                    // Fallback --> If we could not resolve our prefered ip protocol for the hostname
                    if (ipAddress == null)
                    {
                        foreach (IPAddress ipAddr in ipHostEntrys.AddressList)
                        {
                            ipAddress = ipAddr;
                            continue;
                        }
                    }
                }
            }
            catch (SocketException) // This will catch DNS resolve errors
            {
                Finished();

                StatusMessage        = string.Format(Application.Current.Resources["String_CouldNotResolveHostnameFor"] as string, Host);
                DisplayStatusMessage = true;

                return;
            }

            // SNMP...
            SNMPOptions snmpOptions = new SNMPOptions()
            {
                Port    = SettingsManager.Current.SNMP_Port,
                Timeout = SettingsManager.Current.SNMP_Timeout
            };

            SNMP snmp = new SNMP();

            snmp.Received        += Snmp_Received;
            snmp.Timeout         += Snmp_Timeout;
            snmp.Error           += Snmp_Error;
            snmp.UserHasCanceled += Snmp_UserHasCanceled;
            snmp.Complete        += Snmp_Complete;

            switch (Mode)
            {
            case SNMPMode.Get:
                if (Version != SNMPVersion.v3)
                {
                    snmp.Getv1v2cAsync(Version, ipAddress, Community, OID, snmpOptions);
                }
                else
                {
                    snmp.Getv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, snmpOptions);
                }

                break;

            case SNMPMode.Walk:
                if (Version != SNMPVersion.v3)
                {
                    snmp.Walkv1v2cAsync(Version, ipAddress, Community, OID, SettingsManager.Current.SNMP_WalkMode, snmpOptions);
                }
                else
                {
                    snmp.Walkv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, SettingsManager.Current.SNMP_WalkMode, snmpOptions);
                }

                break;

            case SNMPMode.Set:
                if (Version != SNMPVersion.v3)
                {
                    snmp.Setv1v2cAsync(Version, ipAddress, Community, OID, Data, snmpOptions);
                }
                else
                {
                    snmp.Setv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, Data, snmpOptions);
                }
                break;
            }

            // Add to history...
            AddHostToHistory(Host);
            AddOIDToHistory(OID);
        }
        // retourne le status du switch
        static public string getStatusSwitch(string ipAdress)
        {
            SNMP   snmp;
            int    DeviceId = 1;
            int    retries = 1;
            int    TimeoutInMS = 20000;
            string Result1Str; string status = "";

            try
            {
                string[] ErrorMessageText = new string[8];
                ErrorMessageText[0] = "service recquis";
                ErrorMessageText[1] = "Eteinte";
                ErrorMessageText[2] = "Bourrage papier";
                ErrorMessageText[3] = "porte ouverte";
                ErrorMessageText[4] = "pas de toner";
                ErrorMessageText[5] = "niveau toner bas";
                ErrorMessageText[6] = "plus de papier";
                ErrorMessageText[7] = "niveau de papier bas";

                snmp = new SNMP();
                snmp.Open(ipAdress, "public", retries, TimeoutInMS);//.1.3.6.1.2.1.2.2.1.7.25
                uint nbPort = snmp.GetAsByte(String.Format(".1.3.6.1.2.1.2.1.0"));
                snmp.Close();
                System.Console.WriteLine("nombre de port : " + nbPort);

                for (int i = 1; i <= nbPort; i++)
                {
                    snmp = new SNMP();
                    snmp.Open(ipAdress, "public", retries, TimeoutInMS);//.1.3.6.1.2.1.2.2.1.7.25//.1.3.6.1.2.1.2.1.0//.1.3.6.1.2.1.2.2.1.6.
                    string adressResult = snmp.Get(".1.3.6.1.2.1.2.2.1.6." + i);
                    byte[] ba           = Encoding.Default.GetBytes(adressResult);
                    string hexString    = BitConverter.ToString(ba);
                    uint   statusResult = snmp.GetAsByte(".1.3.6.1.2.1.2.2.1.8." + i);

                    switch (statusResult)
                    {
                    case 1:
                        Result1Str = "up";
                        break;

                    case 2:
                        Result1Str = "down";
                        break;

                    case 3:
                        Result1Str = "testing";
                        break;

                    case 4:
                        Result1Str = "unknown";
                        break;

                    case 5:
                        Result1Str = "dormant";
                        break;

                    case 6:
                        Result1Str = "notPresent";
                        break;

                    case 7:
                        Result1Str = "lowerLayerDown";
                        break;

                    default:
                        Result1Str = "code inconnu" + statusResult;
                        break;
                    }
                    Console.WriteLine("  port " + i + " adresse : " + hexString + " " + statusResult + " " + Result1Str);
                    snmp.Close();
                }
            }
            catch (Exception)
            {
                status = "Informations non disponibles...";
            }
            return(status);
        }
        //retourne le pourcentage d'encre présente dans x toner
        static public string getTonerStatus(string ipAdress, string printerName, int tonerNumber)
        {
            int    retries         = 1;
            int    TimeoutInMS     = 20000;
            int    tonerNumberDell = 0;
            string status;
            uint   currentlevel;
            uint   maxlevel;

            try
            {
                SNMP snmp = new SNMP();
                snmp.Open(ipAdress, "public", retries, TimeoutInMS);
                switch (tonerNumber)
                {
                case 1:
                    tonerNumberDell = 4;
                    break;

                case 2:
                    tonerNumberDell = 3;
                    break;

                case 3:
                    tonerNumberDell = 1;
                    break;

                case 4:
                    tonerNumberDell = 2;
                    break;
                }
                switch (printerName)
                {
                case "Dell 3010 cn":
                    currentlevel =
                        Convert.ToUInt32(snmp.Get(".1.3.6.1.2.1.43.11.1.1.9.1." +
                                                  tonerNumberDell.ToString()));
                    maxlevel =
                        Convert.ToUInt32(snmp.Get(".1.3.6.1.2.1.43.11.1.1.8.1." +
                                                  tonerNumberDell.ToString()));
                    break;

                default:
                    currentlevel =
                        Convert.ToUInt32(snmp.Get(".1.3.6.1.2.1.43.11.1.1.9.1." +
                                                  tonerNumber.ToString()));
                    maxlevel =
                        Convert.ToUInt32(snmp.Get(".1.3.6.1.2.1.43.11.1.1.8.1." +
                                                  tonerNumber.ToString()));
                    break;
                }
                uint remaininglevel = (currentlevel * 100 / maxlevel);
                status = remaininglevel.ToString();
                snmp.Close();
            }
            catch (Exception)
            {
                status = "Informations non disponibles...";
            }
            return(status);
        }
        // retourne le status de l'imprimante
        static public string getStatus(string ipAdress)
        {
            SNMP   snmp;
            int    DeviceId = 1;
            int    retries = 1;
            int    TimeoutInMS = 20000;
            string Result1Str; string status;

            try
            {
                string[] ErrorMessageText = new string[8];
                ErrorMessageText[0] = "service recquis";
                ErrorMessageText[1] = "Eteinte";
                ErrorMessageText[2] = "Bourrage papier";
                ErrorMessageText[3] = "porte ouverte";
                ErrorMessageText[4] = "pas de toner";
                ErrorMessageText[5] = "niveau toner bas";
                ErrorMessageText[6] = "plus de papier";
                ErrorMessageText[7] = "niveau de papier bas";

                snmp = new SNMP();
                snmp.Open(ipAdress, "public", retries, TimeoutInMS);
                uint WarningErrorBits = snmp.GetAsByte(String.Format("25.3.5.1.2.{0}",
                                                                     DeviceId));
                uint statusResult = snmp.GetAsByte(String.Format("25.3.2.1.5.{0}",
                                                                 DeviceId));

                switch (statusResult)
                {
                case 2:
                    Result1Str = "OK";
                    break;

                case 3:
                    Result1Str = "Avertissement: ";
                    break;

                case 4:
                    Result1Str = "Test: ";
                    break;

                case 5:
                    Result1Str = "Hors de fonctionnement: ";
                    break;

                default:
                    Result1Str = "Code Inconnu: " + statusResult;
                    break;
                }
                string Str = "";

                if ((statusResult == 3 || statusResult == 5))
                {
                    int Mask   = 1;
                    int NumMsg = 0;
                    for (int i = 0; i < 8; i++)
                    {
                        if ((WarningErrorBits & Mask) == Mask)
                        {
                            if (Str.Length > 0)
                            {
                                Str += ", ";
                            }
                            Str   += ErrorMessageText[i];
                            NumMsg = NumMsg + 1;
                        }
                        Mask = Mask * 2;
                    }
                }
                status = Result1Str + Str;
                snmp.Close();
            }
            catch (Exception)
            {
                status = "Informations non disponibles...";
            }
            return(status);
        }
Beispiel #13
0
        /// <summary>
        /// Get Virtual Servers, Pools, PoolMembers, Profiles and Certificates from Group
        /// </summary>
        /// <param name="devGroup">Group to Collect Info From</param>
        private static void GetObjectsFromDeviceGroup(SyncFailoverGroup sfog)
        {
            // Create Common Partition Holder
            Partition CommonPartition = new Partition("Blank", "Blank");

            // Attach to First Device in Device Group
            m_interfaces.initialize(sfog.DeviceList[0].Address, sfog.DeviceList[0].F5usr, sfog.DeviceList[0].F5pwd);

            if (m_interfaces.initialized)
            {
                // Get SNMP Info (Not Partition Dependant)
                // Virtual Server
                List <Variable> VirtualServerSnmpResults = SNMP.WalkSNMP(SNMP.ltmVsStatusName, sfog.DeviceList[0].Address, sfog.DeviceList[0].Port, sfog.DeviceList[0].Community);
                // Pools
                List <Variable> PoolSnmpResults = SNMP.WalkSNMP(SNMP.ltmPoolStatusName, sfog.DeviceList[0].Address, sfog.DeviceList[0].Port, sfog.DeviceList[0].Community);
                // Pool Members
                List <Variable> PoolMemberSnmpResults = SNMP.WalkSNMP(SNMP.ltmPoolMbrStatusNodeName, sfog.DeviceList[0].Address, sfog.DeviceList[0].Port, sfog.DeviceList[0].Community);
                // Client SSL Profiles
                List <Variable> ClientSslProfileSnmpResults = SNMP.WalkSNMP(SNMP.ltmClientSslName, sfog.DeviceList[0].Address, sfog.DeviceList[0].Port, sfog.DeviceList[0].Community);
                // Server SSL Profiles
                List <Variable> ServerSslProfileSnmpResults = SNMP.WalkSNMP(SNMP.ltmServerSslName, sfog.DeviceList[0].Address, sfog.DeviceList[0].Port, sfog.DeviceList[0].Community);

                // Get List of Partitions
                ManagementPartitionAuthZPartition[] partitionList = m_interfaces.ManagementPartition.get_partition_list();

                // Loop through Partitions
                foreach (ManagementPartitionAuthZPartition partition in partitionList)
                {
                    // Set Active Partition
                    m_interfaces.ManagementPartition.set_active_partition(partition.partition_name);

                    // Create Partition
                    Partition newPartition = new Partition(sfog.Key, partition.partition_name);
                    sfog.PartitionList.Add(newPartition);

                    // Get Certificates
                    ManagementKeyCertificateCertificateInformation_v2[] certs = m_interfaces.ManagementKeyCertificate.get_certificate_list_v2(ManagementKeyCertificateManagementModeType.MANAGEMENT_MODE_DEFAULT);
                    foreach (ManagementKeyCertificateCertificateInformation_v2 cert in certs)
                    {
                        Certificate newCert = new Certificate(cert, sfog, partition.partition_name);
                        newPartition.CertificateList.Add(newCert);
                    }

                    // Get Client SSL Profiles
                    // Get iControl Info
                    string[] ProfileClientSSLList                    = m_interfaces.LocalLBProfileClientSSL.get_list();
                    string[] ProfileClientSSLDescriptionList         = m_interfaces.LocalLBProfileClientSSL.get_description(ProfileClientSSLList);
                    LocalLBProfileString[] ProfileClientSSL_ca_files = m_interfaces.LocalLBProfileClientSSL.get_certificate_file_v2(ProfileClientSSLList);

                    // Loop Through All Client SSL profiles
                    for (int i = 0; i < ProfileClientSSLList.Length; i++)
                    {
                        // Create Profile
                        ProfileClientSSL newProfile = new ProfileClientSSL(sfog, partition.partition_name, ProfileClientSSLList[i], ProfileClientSSLDescriptionList[i], ProfileClientSSL_ca_files[i].value);

                        // Look for Matching Certs in This Partition
                        foreach (Certificate cert in newPartition.CertificateList)
                        {
                            if (ProfileClientSSL_ca_files[i].value == cert.SCOM_Object.Values[3].ToString())
                            {
                                newProfile.CertificateList.Add(cert);
                            }
                        }

                        // Look For Matching Certificates in Common Partition
                        if (partition.partition_name != "Common")
                        {
                            foreach (Certificate cert in CommonPartition.CertificateList)
                            {
                                if (ProfileClientSSL_ca_files[i].value == cert.SCOM_Object.Values[3].ToString())
                                {
                                    newProfile.CertificateList.Add(cert);
                                }
                            }
                        }

                        // Save ClientSslProfile
                        newPartition.ClientSslProfileList.Add(newProfile);
                    }

                    // Get Server SSL Profiles
                    string[] ProfileServerSSLList                    = m_interfaces.LocalLBProfileServerSSL.get_list();
                    string[] ProfileServerSSLDescriptionList         = m_interfaces.LocalLBProfileServerSSL.get_description(ProfileServerSSLList);
                    LocalLBProfileString[] ProfileServerSSL_ca_files = m_interfaces.LocalLBProfileServerSSL.get_certificate_file_v2(ProfileServerSSLList);
                    // Loop Through All Server SSL profiles
                    for (int i = 0; i < ProfileServerSSLList.Length; i++)
                    {
                        // Create Profile
                        ProfileServerSSL newProfile = new ProfileServerSSL(sfog, partition.partition_name, ProfileServerSSLList[i], ProfileServerSSLDescriptionList[i], ProfileServerSSL_ca_files[i].value);
                        // Look for Matching Certs in This Partition
                        foreach (Certificate cert in newPartition.CertificateList)
                        {
                            if (ProfileServerSSL_ca_files[i].value == cert.SCOM_Object.Values[3].ToString())
                            {
                                newProfile.CertificateList.Add(cert);
                            }
                        }

                        // Look For Matching Certificates in Common Partition
                        if (partition.partition_name != "Common")
                        {
                            foreach (Certificate cert in CommonPartition.CertificateList)
                            {
                                if (ProfileServerSSL_ca_files[i].value == cert.SCOM_Object.Values[3].ToString())
                                {
                                    newProfile.CertificateList.Add(cert);
                                }
                            }
                        }
                        newPartition.ServerSslProfileList.Add(newProfile);
                    }

                    // Get Virtual Servers
                    // Get iControl Info
                    string[] vipNames        = m_interfaces.LocalLBVirtualServer.get_list();
                    string[] vipDefaultPools = m_interfaces.LocalLBVirtualServer.get_default_pool_name(vipNames);
                    LocalLBVirtualServerVirtualServerType[] vipTypes = m_interfaces.LocalLBVirtualServer.get_type(vipNames);
                    CommonAddressPort[] vipAddressPorts     = m_interfaces.LocalLBVirtualServer.get_destination_v2(vipNames);
                    string[]            vipDescriptions     = m_interfaces.LocalLBVirtualServer.get_description(vipNames);
                    CommonULong64[]     vipConnectionLimits = m_interfaces.LocalLBVirtualServer.get_connection_limit(vipNames);
                    LocalLBVirtualServerVirtualServerProfileAttribute[][] vipProfiles = m_interfaces.LocalLBVirtualServer.get_profile(vipNames);

                    // Loop Through All Virtual Servers
                    for (int i = 0; i < vipNames.Length; i++)
                    {
                        // Set Address
                        string vipAddress = vipAddressPorts[i].address;
                        vipAddress = vipAddress.Substring(vipAddress.LastIndexOf("/") + 1);
                        // Get Connection Limit
                        string vipConnectionLimit = ConvertUlong(vipConnectionLimits[i]).ToString();
                        // Get Oid Suffix
                        string vipOidSuffix = GetOidSuffix(vipNames[i], SNMP.ltmVsStatusName, VirtualServerSnmpResults);
                        // Get Client SSL Profiles
                        string vipClientSSLProfiles = "";
                        string vipServerSSLProfiles = "";
                        foreach (LocalLBVirtualServerVirtualServerProfileAttribute profileAttr in vipProfiles[i])
                        {
                            if (profileAttr.profile_type == LocalLBProfileType.PROFILE_TYPE_CLIENT_SSL)
                            {
                                vipClientSSLProfiles += profileAttr.profile_name + ",";
                            }
                            if (profileAttr.profile_type == LocalLBProfileType.PROFILE_TYPE_SERVER_SSL)
                            {
                                vipServerSSLProfiles += profileAttr.profile_name + ",";
                            }
                        }
                        vipClientSSLProfiles = vipClientSSLProfiles.TrimEnd(',');
                        vipServerSSLProfiles = vipServerSSLProfiles.TrimEnd(',');
                        // Get Device Group
                        string vipDeviceGroup = sfog.Name;

                        VirtualServer vs = new VirtualServer(sfog, partition.partition_name, vipNames[i], vipAddress, vipAddressPorts[i].port.ToString(), vipDescriptions[i],
                                                             vipTypes[i].ToString(), vipDefaultPools[i], vipConnectionLimit, vipClientSSLProfiles, vipServerSSLProfiles);

                        // Look For Matching ClientSslProfiles in this Partition
                        foreach (ProfileClientSSL profile in newPartition.ClientSslProfileList)
                        {
                            if (vipClientSSLProfiles.Contains(profile.SCOM_Object.Values[0].ToString()))
                            {
                                vs.ProfileClientSslList.Add(profile);
                            }
                        }
                        // Look For Matching ClientSslProfiles in Common Partition
                        if (partition.partition_name != "Common")
                        {
                            foreach (ProfileClientSSL profile in CommonPartition.ClientSslProfileList)
                            {
                                if (vipClientSSLProfiles.Contains(profile.SCOM_Object.Values[0].ToString()))
                                {
                                    vs.ProfileClientSslList.Add(profile);
                                }
                            }
                        }
                        // Look For Matching ServerSslProfiles in this Partition
                        foreach (ProfileServerSSL profile in newPartition.ServerSslProfileList)
                        {
                            if (vipServerSSLProfiles.Contains(profile.SCOM_Object.Values[0].ToString()))
                            {
                                vs.ProfileServerSslList.Add(profile);
                            }
                        }
                        // Look For Matching ClientSslProfiles in Common Partition
                        if (partition.partition_name != "Common")
                        {
                            foreach (ProfileServerSSL profile in CommonPartition.ServerSslProfileList)
                            {
                                if (vipServerSSLProfiles.Contains(profile.SCOM_Object.Values[0].ToString()))
                                {
                                    vs.ProfileServerSslList.Add(profile);
                                }
                            }
                        }
                        // Add it to the List
                        newPartition.VirtualServerList.Add(vs);
                    }

                    // Get Pools & Pool Members
                    // Get iControl Info
                    string[] poolNames                           = m_interfaces.LocalLBPool.get_list();
                    string[] poolDescriptions                    = m_interfaces.LocalLBPool.get_description(poolNames);
                    long[]   poolActiveMemberCount               = m_interfaces.LocalLBPool.get_active_member_count(poolNames);
                    CommonAddressPort[][] poolMembers            = m_interfaces.LocalLBPool.get_member_v2(poolNames);
                    string[][]            poolMemberDescriptions = m_interfaces.LocalLBPool.get_member_description(poolNames, poolMembers);
                    // Loop Through All Pools
                    for (int i = 0; i < poolNames.Length; i++)
                    {
                        // Get Full Name
                        string sPoolName = poolNames[i];

                        // Get Node Short Name
                        string sShortPoolName = sPoolName.Substring(sPoolName.LastIndexOf("/") + 1);

                        // Ignore _auto_ Nodes
                        if (sShortPoolName.ToLower().StartsWith("_auto_"))
                        {
                            continue;
                        }

                        // Get Oid Suffix
                        string OidSuffix = GetOidSuffix(sPoolName, SNMP.ltmPoolStatusName, PoolSnmpResults);

                        // Get Monitor Rule
                        string MonitorRule = SNMP.GetSNMP(SNMP.ltmPoolMonitorRule + OidSuffix, sfog.DeviceList[0].Address, sfog.DeviceList[0].Port, sfog.DeviceList[0].Community)[0].Data.ToString();

                        // Create new Pool
                        Pool newPool = new Pool(sfog, partition.partition_name, sPoolName, sShortPoolName, poolDescriptions[i], MonitorRule, poolMembers[i].Length, poolActiveMemberCount[i]);

                        // Add Pool Members
                        for (int j = 0; j < poolMembers[i].Length; j++)
                        {
                            // Get Oid Suffix
                            string pmOidSuffix = GetOidSuffix(poolMembers[i][j].address, SNMP.ltmPoolMbrStatusNodeName, PoolMemberSnmpResults);
                            // Get Monitor Rule (using SNMP as iControl seems to Error)
                            string pmMonitorRule = SNMP.GetSNMP(SNMP.ltmPoolMemberMonitorRule + pmOidSuffix, sfog.DeviceList[0].Address, sfog.DeviceList[0].Port, sfog.DeviceList[0].Community)[0].Data.ToString();

                            // Create New Pool Member
                            PoolMember newPoolMember = new PoolMember(sfog, partition.partition_name, sPoolName, poolMembers[i][j].address, poolMemberDescriptions[i][j], poolMembers[i][j].port.ToString(), pmMonitorRule);

                            // Add to Pool
                            newPool.PoolMembers.Add(newPoolMember);
                        }

                        // Add it to the List
                        newPartition.PoolList.Add(newPool);

                        // Match To Virtual Servers (DefaultPool)
                        foreach (VirtualServer vs in newPartition.VirtualServerList)
                        {
                            if (vs.DefaultPoolName == sPoolName)
                            {
                                vs.DefaultPool = newPool;
                            }
                        }
                    }


                    // Get Nodes
                    string[] nodeNameList        = m_interfaces.LocalLBNodeAddressV2.get_list();
                    string[] nodeAddressList     = m_interfaces.LocalLBNodeAddressV2.get_address(nodeNameList);
                    string[] nodeDescriptionList = m_interfaces.LocalLBNodeAddressV2.get_description(nodeNameList);
                    for (int i = 0; i < nodeNameList.Length; i++)
                    {
                        // Get Node Full Name
                        string sNodeName = nodeNameList[i];

                        // Get Node Short Name
                        string sShortNodeName = sNodeName.Substring(sNodeName.LastIndexOf("/") + 1);

                        // Ignore _auto_ Nodes
                        if (sShortNodeName.ToLower().StartsWith("_auto_"))
                        {
                            continue;
                        }

                        string MonitorRules = "";
                        try
                        {
                            LocalLBMonitorRule[] nodeMonitorRuleList = m_interfaces.LocalLBNodeAddressV2.get_monitor_rule(new string[] { sNodeName });
                            for (int j = 0; j < nodeMonitorRuleList[0].monitor_templates.Length; j++)
                            {
                                MonitorRules += nodeMonitorRuleList[0].monitor_templates[j].ToString() + ",";
                            }
                            MonitorRules = MonitorRules.TrimEnd(',');
                        }
                        catch (Exception)
                        {
                        }

                        // Create a New Node
                        Node newNode = new Node(sfog.Key, partition.partition_name, sNodeName, sShortNodeName, nodeAddressList[i], nodeDescriptionList[i], MonitorRules);
                        newPartition.NodeList.Add(newNode);
                    }

                    // Take a Copy of Common Parition
                    if (partition.partition_name == "Common")
                    {
                        CommonPartition = newPartition;
                    }
                }
            }
        }