コード例 #1
0
ファイル: TableView.xaml.cs プロジェクト: Ziolass/SNMP-NMS
        private void populateTable(Variable[,] table,int selector)
        {
            
            int columns = table.GetLength(1);
            int rows = table.GetLength(0);
            string[,] tempTable = new string[rows, columns];

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    string[] tmp = table[i, j].ToString().Split(';');
                    string[] tmp2 = tmp[1].Split(':');

                    tempTable[i, j] = tmp2[1];
                }
            }


            DataTable dt = new DataTable();
            int nbColumns = columns;
            int nbRows = rows;
            string[] temp;
            if (selector == 0)
            {
                temp = ipAddrTable;
            }
            else if (selector == 1)
            {
                temp = ipRouteTable;
            }
            else
            {
                temp = ipNetTable;
            }
            for (int i = 0; i < nbColumns; i++)
            {
                dt.Columns.Add(temp[i], typeof(string));
            }

            for (int row = 0; row < nbRows; row++)
            {
                DataRow dr = dt.NewRow();
                for (int col = 0; col < nbColumns; col++)
                {
                    dr[col] = tempTable[row, col];
                }
                dt.Rows.Add(dr);
            }

            dataTable.ItemsSource = dt.DefaultView;




        }
コード例 #2
0
		/// <summary>
		/// Check the SNMP devices in the Devices.ini are available or not.
		/// If some devices are unavailable, the Devices.ini should be changed to give
		/// tester all available devices.
		/// </summary>
		/// <returns>list</returns>
		public static List<String> CheckSNMPDeviceAvailable(){			
			
		    List<string> notAvailable = new List<string>();
			int timeout = 3;
			VersionCode version = VersionCode.V1;
			IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"),161);
			OctetString community = new OctetString("public");
            
            ObjectIdentifier objectId = new ObjectIdentifier("1.3.6.1.2.1.11.1.0");
            Variable var = new Variable(objectId);   
            IList<Variable> varlist = new System.Collections.Generic.List<Variable>();
            varlist.Add(var);
            Variable data;
            IList<Variable> resultdata;
            IDictionary<string, string> AllDeviceInfo = new Dictionary<string, string> ();
            IDictionary<string, string> SNMPDeviceInfo = new Dictionary<string, string> ();
            
            AllDeviceInfo = AppConfigOper.mainOp.DevConfigs;

			foreach(string key in AllDeviceInfo.Keys)
			{
				if(key.ToUpper().StartsWith("SNMP"))
				{
					SNMPDeviceInfo.Add(key, AllDeviceInfo[key]);
				}
			}
			
			foreach (KeyValuePair<string, string>device in SNMPDeviceInfo)
			{ 
				Console.WriteLine("SNMPDeviceInfo: key={0},value={1}", device.Key, device.Value);
			}
			
            foreach(string deviceIp in SNMPDeviceInfo.Values)
            {
            	try
            	{
            		endpoint.Address = IPAddress.Parse(deviceIp);
	            	resultdata = Messenger.Get(version,endpoint,community,varlist,timeout);
	            	data = resultdata[0];
	            	Console.WriteLine("The device:" + deviceIp + "is availabe");
            	}
            	catch(Exception ex)
	            {
	            	notAvailable.Add(deviceIp);
	            	Console.WriteLine("There is no device in this ip address."+ deviceIp);
	            	string log = ex.ToString();
	            	continue;
	            }	
            }
            return notAvailable;
	   }
コード例 #3
0
        private void AddDevice(String snmpVersion, IPEndPoint agent, Lextm.SharpSnmpLib.Variable var)
        {
            int    devicePageCounter = 0;
            String deviceInfo        = "";

            if ((var != null) && (var.Data != null))
            {
                deviceInfo = var.Data.ToString();
            }

            List <PrintingDevice> deviceMatches = deviceList.FindAll(delegate(PrintingDevice device) { return(device.ipAddress.ToString() == agent.Address.ToString()); });

            if (deviceMatches.Count == 0)
            {
                String deviceDescription = GetDeviceDescription(agent.Address);
                String serialNumber      = GetSerialNumber(agent.Address, deviceInfo);
                String pageCounter       = GetPageCounter(agent.Address);

                Boolean deviceOK = true;
                if (String.IsNullOrEmpty(deviceDescription))
                {
                    deviceOK = false;
                }
                if (String.IsNullOrEmpty(serialNumber))
                {
                    deviceOK = false;
                }
                if (String.IsNullOrEmpty(pageCounter))
                {
                    deviceOK = false;
                }
                if (!int.TryParse(pageCounter, out devicePageCounter))
                {
                    deviceOK = false;
                }
                if (deviceOK)
                {
                    deviceList.Add(new PrintingDevice(this.tenantId, agent.Address.ToString(), deviceDescription, serialNumber, devicePageCounter));
                }
            }
        }
コード例 #4
0
        public static void Main(string[] args)
        {
            string community = "public";
            bool showHelp   = false;
            bool showVersion = false;
            VersionCode version = VersionCode.V1;
            int timeout = 1000;
            int retry = 0;
            Levels level = Levels.Reportable;
            string user = string.Empty;
            string authentication = string.Empty;
            string authPhrase = string.Empty;
            string privacy = string.Empty;
            string privPhrase = string.Empty;
            bool dump = false;

            OptionSet p = new OptionSet()
                .Add("c:", "-c for community name, (default is public)", delegate (string v) { if (v != null) community = v; })
                .Add("l:", "-l for security level, (default is noAuthNoPriv)", delegate (string v)
                                                                                   {
                                                                                       if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                                                                                       }
                                                                                       else
                                                                                       {
                                                                                           throw new ArgumentException("no such security mode: " + v);
                                                                                       }
                                                                                   })
                .Add("a:", "-a for authentication method (MD5 or SHA)", delegate (string v) { authentication = v; })
                .Add("A:", "-A for authentication passphrase", delegate(string v) { authPhrase = v; })
                .Add("x:", "-x for privacy method", delegate (string v) { privacy = v; })
                .Add("X:", "-X for privacy passphrase", delegate (string v) { privPhrase = v; })
                .Add("u:", "-u for security name", delegate(string v) { user = v; })
                .Add("h|?|help", "-h, -?, -help for help.", delegate (string v) { showHelp = v != null; })
                .Add("V", "-V to display version number of this application.", delegate (string v) { showVersion = v != null; })
                .Add("d", "-d to display message dump", delegate(string v) { dump = true; })
                .Add("t:", "-t for timeout value (unit is second).", delegate (string v) { timeout = int.Parse(v) * 1000; })
                .Add("r:", "-r for retry count (default is 0)", delegate (string v) { retry = int.Parse(v); })
                .Add("v|version:", "-v for SNMP version (1, 2, and 3 are currently supported)", delegate (string v)
                                                                                               {
                                                                                                   switch (int.Parse(v))
                                                                                                   {
                                                                                                       case 1:
                                                                                                           version = VersionCode.V1;
                                                                                                           break;
                                                                                                       case 2:
                                                                                                           version = VersionCode.V2;
                                                                                                           break;
                                                                                                       case 3:
                                                                                                           version = VersionCode.V3;
                                                                                                           break;
                                                                                                       default:
                                                                                                           throw new ArgumentException("no such version: " + v);
                                                                                                   }
                                                                                               });
            
            List<string> extra = p.Parse (args);
            
            if (showHelp)
            {
                ShowHelp();   
                return;
            }
            
            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            if (extra.Count < 2)
            {
                ShowHelp();
                return;
            }
            
            IPAddress ip;
            bool parsed = IPAddress.TryParse(extra[0], out ip);
            if (!parsed)
            {
                foreach (IPAddress address in Dns.GetHostAddresses(extra[0]))
                {
                    if (address.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    ip = address;
                    break;
                }
                
                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List<Variable> vList = new List<Variable>();
                for (int i = 1; i < extra.Count; i++)
                {
                    Variable test = new Variable(new ObjectIdentifier(extra[i]));
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (
                        Variable variable in
                            Messenger.Get(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }
                
                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery discovery = Messenger.NextDiscovery;
                ReportMessage report = discovery.GetResponse(timeout, receiver);

                GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);

                ISnmpMessage response = request.GetResponse(timeout, receiver);
                if (dump)
                {
                    Console.WriteLine(ByteTool.Convert(request.ToBytes()));
                }

                if (response.Pdu.ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                        "error in response",
                        receiver.Address,
                        response);
                }

                foreach (Variable v in response.Pdu.Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: bleissem/sharpsnmplib
        static void Main(string[] args)
        {
            string community = "public";
            bool showHelp = false;
            bool showVersion = false;
            VersionCode version = VersionCode.V1;
            int timeout = 1000;
            int retry = 0;
            Levels level = Levels.Reportable;
            string user = string.Empty;
            string authentication = string.Empty;
            string authPhrase = string.Empty;
            string privacy = string.Empty;
            string privPhrase = string.Empty;
            bool dump = false;

            OptionSet p = new OptionSet()
                .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null) community = v; })
                .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
                                                                                   {
                                                                                       if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                                                                                       }
                                                                                       else
                                                                                       {
                                                                                           throw new ArgumentException("no such security mode: " + v);
                                                                                       }
                                                                                   })
                .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                .Add("u:", "Security name", delegate(string v) { user = v; })
                .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                .Add("d", "Display message dump", delegate(string v) { dump = true; })
                .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                .Add("v:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
                                                                                       {
                                                                                           switch (int.Parse(v))
                                                                                           {
                                                                                               case 1:
                                                                                                   version = VersionCode.V1;
                                                                                                   break;
                                                                                               case 2:
                                                                                                   version = VersionCode.V2;
                                                                                                   break;
                                                                                               case 3:
                                                                                                   version = VersionCode.V3;
                                                                                                   break;
                                                                                               default:
                                                                                                   throw new ArgumentException("no such version: " + v);
                                                                                           }
                                                                                       });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List<string> extra;
            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if ((extra.Count - 1) % 3 != 0)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            IPAddress ip;
            bool parsed = IPAddress.TryParse(extra[0], out ip);
            if (!parsed)
            {
                foreach (IPAddress address in
                    Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List<Variable> vList = new List<Variable>();
                for (int i = 1; i < extra.Count; i = i + 3)
                {
                    string type = extra[i + 1];
                    if (type.Length != 1)
                    {
                        Console.WriteLine("invalid type string: " + type);
                        return;
                    }

                    ISnmpData data;

                    switch (type[0])
                    {
                        case 'i':
                            data = new Integer32(int.Parse(extra[i + 2]));
                            break;
                        case 'u':
                            data = new Gauge32(uint.Parse(extra[i + 2]));
                            break;
                        case 't':
                            data = new TimeTicks(uint.Parse(extra[i + 2]));
                            break;
                        case 'a':
                            data = new IP(IPAddress.Parse(extra[i + 2]).GetAddressBytes());
                            break;
                        case 'o':
                            data = new ObjectIdentifier(extra[i + 2]);
                            break;
                        case 'x':
                            data = new OctetString(ByteTool.Convert(extra[i + 2]));
                            break;
                        case 's':
                            data = new OctetString(extra[i + 2]);
                            break;
                        case 'd':
                            data = new OctetString(ByteTool.ConvertDecimal(extra[i + 2]));
                            break;
                        case 'n':
                            data = new Null();
                            break;
                        default:
                            Console.WriteLine("unknown type string: " + type[0]);
                            return;
                    }

                    Variable test = new Variable(new ObjectIdentifier(extra[i]), data);
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (Variable variable in
                        Messenger.Set(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery discovery = Messenger.GetNextDiscovery(SnmpType.SetRequestPdu);
                ReportMessage report = discovery.GetResponse(timeout, receiver);

                SetRequestMessage request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);
                ISnmpMessage reply = request.GetResponse(timeout, receiver);
                if (dump)
                {
                    Console.WriteLine("Request message bytes:");
                    Console.WriteLine(ByteTool.Convert(request.ToBytes()));
                    Console.WriteLine("Response message bytes:");
                    Console.WriteLine(ByteTool.Convert(reply.ToBytes()));
                }

                if (reply is ReportMessage)
                {
                    if (reply.Pdu().Variables.Count == 0)
                    {
                        Console.WriteLine("wrong report message received");
                        return;
                    }

                    var id = reply.Pdu().Variables[0].Id;
                    if (id != Messenger.NotInTimeWindow)
                    {
                        var error = id.GetErrorMessage();
                        Console.WriteLine(error);
                        return;
                    }

                    // according to RFC 3414, send a second request to sync time.
                    request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, reply);
                    reply = request.GetResponse(timeout, receiver);
                }
                else if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                        "error in response",
                        receiver.Address,
                        reply);
                }

                foreach (Variable v in reply.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
コード例 #6
0
ファイル: KpSnmpLogic.cs プロジェクト: LoganDing/scada
 /// <summary>
 /// Конструктор
 /// </summary>
 public VarGroup(string name, int varCnt, int startSignal)
 {
     Name = name;
     VarNames = new string[varCnt];
     Variables = new Variable[varCnt];
     StartSignal = startSignal;
     ReqDescr = string.Format(Localization.UseRussian ?
         "Получение значений переменных группы \"{0}\"" :
         "Get variables of the group \"{0}\"", Name);
 }
コード例 #7
0
ファイル: KpSnmpLogic.cs プロジェクト: LoganDing/scada
        /// <summary>
        /// Отправить команду установки переменной
        /// </summary>
        private void Command(string varName, Variable variable)
        {
            lastCommSucc = false;
            int tryNum = 0;

            while (RequestNeeded(ref tryNum))
            {
                WriteToLog(string.Format(Localization.UseRussian ?
                    "Установка значения переменной \"{0}\"" :
                    "Set variable \"{0}\"", varName));

                try
                {
                    IList<Variable> sentVars = Messenger.Set(snmpVersion, endPoint, writeCommunity,
                        new List<Variable>() { variable }, ReqParams.Timeout);

                    if (sentVars == null || sentVars.Count != 1 || sentVars[0].Id != variable.Id)
                        throw new Exception(KpPhrases.VariablesMismatch);

                    WriteToLog(varName + " = " + ConvertVarDataToString(sentVars[0].Data));
                    lastCommSucc = true;
                }
                catch (Exception ex)
                {
                    WriteToLog((Localization.UseRussian ?
                        "Ошибка при установке переменной: " :
                        "Error setting variable: ") + ex.Message);
                }

                // завершение запроса
                FinishRequest();
                tryNum++;
            }
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: stubarr/sharpsnmplib-1
        public static void Main(string[] args)
        {
            string community = "public";
            bool showHelp   = false;
            bool showVersion = false;
            VersionCode version = VersionCode.V2; // GET BULK is available in SNMP v2 and above.
            int timeout = 1000;
            int retry = 0;
            Levels level = Levels.Reportable;
            string user = string.Empty;
            string authentication = string.Empty;
            string authPhrase = string.Empty;
            string privacy = string.Empty;
            string privPhrase = string.Empty;
            int maxRepetitions = 10;
            int nonRepeaters = 0;

            OptionSet p = new OptionSet()
                .Add("c:", "Community name, (default is public)", delegate (string v) { if (v != null) community = v; })
                .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
                                                                                   {
                                                                                       if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Reportable;
                                                                                       }
                                                                                       else if (v.ToUpperInvariant() == "AUTHPRIV")
                                                                                       {
                                                                                           level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                                                                                       }
                                                                                       else
                                                                                       {
                                                                                           throw new ArgumentException("no such security mode: " + v);
                                                                                       }
                                                                                   })
                .Add("Cn:", "Non-repeaters (default is 0)", delegate(string v) { nonRepeaters = int.Parse(v); })
                .Add("Cr:", "Max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); })
                .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                .Add("u:", "Security name", delegate(string v) { user = v; })
                .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                .Add("V", "Display version number of this application.", delegate (string v) { showVersion = v != null; })
                .Add("t:", "Timeout value (unit is second).", delegate (string v) { timeout = int.Parse(v) * 1000; })
                .Add("r:", "Retry count (default is 0)", delegate (string v) { retry = int.Parse(v); })
                .Add("v:", "SNMP version (2 and 3 are currently supported)", delegate (string v)
                                                                                       {
                                                                                           switch (int.Parse(v))
                                                                                           {
                                                                                               case 2:
                                                                                                   version = VersionCode.V2;
                                                                                                   break;
                                                                                               case 3:
                                                                                                   version = VersionCode.V3;
                                                                                                   break;
                                                                                               default:
                                                                                                   throw new ArgumentException("no such version: " + v);
                                                                                           }
                                                                                       });
            
            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List<string> extra;
            try
            {
                extra = p.Parse(args);
            }
            catch(OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if (extra.Count < 2)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            } 
            
            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }
            
            IPAddress ip;
            bool parsed = IPAddress.TryParse(extra[0], out ip);
            if (!parsed)
            {
                foreach (IPAddress address in
                    Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List<Variable> vList = new List<Variable>();
                for (int i = 1; i < extra.Count; i++)
                {
                    Variable test = new Variable(new ObjectIdentifier(extra[i]));
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    GetBulkRequestMessage message = new GetBulkRequestMessage(0,
                                                                              version,
                                                                              new OctetString(community),
                                                                              nonRepeaters,
                                                                              maxRepetitions,
                                                                              vList);
                    ISnmpMessage response = message.GetResponse(timeout, receiver);
                    if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                    {
                        throw ErrorException.Create(
                            "error in response",
                            receiver.Address,
                            response);
                    }

                    foreach (Variable variable in response.Pdu().Variables)
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
                ReportMessage report = discovery.GetResponse(timeout, receiver);

                GetBulkRequestMessage request = new GetBulkRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), nonRepeaters, maxRepetitions, vList, priv, Messenger.MaxMessageSize, report);

                ISnmpMessage reply = request.GetResponse(timeout, receiver);
                if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                        "error in response",
                        receiver.Address,
                        reply);
                }

                foreach (Variable v in reply.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
コード例 #9
0
ファイル: frmMain.cs プロジェクト: nhickman/visual_snmp
        private void btnGet_Click(object sender, EventArgs e)
        {
            IPAddress ip;
            VersionCode version = VersionCode.V1;
            string community = "public";
            string user = string.Empty;
            string authentication = string.Empty;
            string authPhrase = string.Empty;
            string privacy = string.Empty;
            string privPhrase = string.Empty;
            int timeout = 1000;

            switch(cmbVersion.SelectedIndex+1)
            {
                case 1:
                    version = VersionCode.V1;
                    break;
                case 2:
                    version = VersionCode.V2;
                    break;
                case 3:
                    version = VersionCode.V3;
                    break;
                default:
                    MessageBox.Show("Invalid SNMP version selected.");
                    return;
            }

            community = txtCommunity.Text;

            bool parsed = IPAddress.TryParse(txtIP.Text , out ip);
            if (!parsed)
            {
                foreach (IPAddress address in Dns.GetHostAddresses(txtIP.Text))
                {
                    if (address.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    MessageBox.Show("Invalid IP: " + txtIP.Text);
                    return;
                }
            }

            try
            {
                List<Variable> vList = new List<Variable>();
                Variable test = new Variable(new ObjectIdentifier(cmbOID.Text));
                vList.Add(test);

                IPEndPoint receiver = new IPEndPoint(ip, 161);

                foreach (Variable variable in
                         Messenger.Get(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                        rtxOutput.Text = Convert.ToString(variable.Data);
                    }
                return;
            }

            catch (SnmpException ex)
            {
                MessageBox.Show("SNMP Exception: " + ex);
            }
            catch (SocketException ex)
            {
                MessageBox.Show("Socket Exception: " + ex);
            }
        }
コード例 #10
-1
ファイル: LxDeviceAvailable.cs プロジェクト: YouwenYao/Alex
        //**********************************************************************
        /// <summary>
        /// Check the SNMP devices in the Devices.ini are available or not.
        /// If some devices are unavailable, the Devices.ini should be changed to give
        /// tester all available devices.
        /// Author: Sashimi.
        /// </summary>
        public static List<String> CheckSNMPDeviceAvailable(List<string> keyName)
        {
            List<string> notAvailable = new List<string>();
            // There are all devices in Device.ini.
            string groupName="SNMPDevices";
            //GXT_Ip_Port=10.146.88.10:163
            string keyName_IpPort = "SNMP_GXT_Ip_Port";
            string ipPort = myparseToValue(groupName,keyName_IpPort);
            string IP_Port = "";
            if(ipPort.IndexOf(":") != -1)
            {
                string[] spilt = ipPort.Split(':');
                IP_Port = spilt[0];
            }

            int timeout = 3;
            VersionCode version = VersionCode.V1;
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"),161);
            OctetString community = new OctetString("public");

            ObjectIdentifier objectId = new ObjectIdentifier("1.3.6.1.2.1.11.1.0");
            Variable var = new Variable(objectId);
            IList<Variable> varlist = new System.Collections.Generic.List<Variable>();
            varlist.Add(var);
            Variable data;
            IList<Variable> resultdata;

            foreach(string deviceIP in keyName){
                string strIP = myparseToValue(groupName,deviceIP);
                try
                {
                    if(!deviceIP.Equals("SNMP_GXT_Ip_Port"))
                        endpoint.Address = IPAddress.Parse(strIP);
                    else
                        endpoint.Address = IPAddress.Parse(IP_Port);
                     resultdata = Messenger.Get(version,endpoint,community,varlist,timeout);
                     data = resultdata[0];
                     Console.WriteLine("The device:" + deviceIP + "("+ strIP +")"+ " is availabe");
                }
                catch(Exception ex)
                {
                    notAvailable.Add(deviceIP);
                    Console.WriteLine("There is no device in this ip address."+ deviceIP + "("+ strIP +")!" );
                    string log = ex.ToString();
                    continue;
                }
            }

            return notAvailable;
        }
コード例 #11
-1
ファイル: TableView.xaml.cs プロジェクト: Ziolass/SNMP-NMS
 public TableView(Variable[,] table,int selector)
 {
     InitializeComponent();
     
     populateTable(table,selector);
 }
コード例 #12
-1
ファイル: TableView.xaml.cs プロジェクト: lesiu005/ZST-SNMP
 public TableView(Variable[,] table)
 {
     InitializeComponent();
     populateTable(table);
 }