public string WMI([FromQuery] string identifier)
        {
            ISnmpData data  = null,
                      data2 = null;
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V1,
                                                                      new OctetString("public"),
                                                                      //new List<Variable> {new Variable(new ObjectIdentifier("1.3.6.1.2.1.25.1.6"))});
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(identifier))
            });
            ISnmpMessage response = message.GetResponse(60000, new IPEndPoint(IPAddress.Any, 161));

            string s = JsonConvert.SerializeObject(response.Pdu().Variables);

            foreach (var a in response.Pdu().Variables)
            {
                data2 = a.Data;
            }

            var result = Messenger.Get(VersionCode.V2,
                                       new IPEndPoint(IPAddress.Any, 161),
                                       new OctetString("public"),
                                       new List <Variable> {
                new Variable(new ObjectIdentifier(".1.3.6.1.2.1.1.3"))
            },
                                       60000);

            s += JsonConvert.SerializeObject(result);
            return(s);
        }
        internal override void GetNext(Variable variable)
        {
            if (string.IsNullOrEmpty(UserName))
            {
                Logger.Info("User name need to be specified for v3.");
                return;
            }

            Discovery             discovery = Messenger.NextDiscovery;
            ReportMessage         report    = discovery.GetResponse(Timeout, Agent);
            GetNextRequestMessage request   = new GetNextRequestMessage(VersionCode.V3, 100, 0, new OctetString(UserName), new List <Variable> {
                variable
            }, _privacy, Messenger.MaxMessageSize, report);
            ISnmpMessage response = request.GetResponse(Timeout, Agent, _registry);

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

            Logger.Info(response.Pdu().Variables[0].ToString(Objects));
        }
示例#3
0
        private Variable GetNext(List <Variable> vList)
        {
            strError = null;

            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V1,
                                                                      new OctetString("public"),
                                                                      vList);

            try
            {
                response = message.GetResponse(timeout, receiver);
            }
            catch (Exception e)
            {
                strError = "Error Retrieving Property";
                return(null);
            }
            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                strError = "Error Retrieving Property";
                return(null);
            }
            else
            {
                return(response.Pdu().Variables[0]);
            }


            return(null);
        }
示例#4
0
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                TcpClient    client      = new TcpClient();
                IAsyncResult asyncResult = client.BeginConnect(textBox1.Text, 161, null, null);
                // readTimeOut süresi kadar saniye içerisinde bağlantının kurulması bekleniyor.
                asyncResult.AsyncWaitHandle.WaitOne(3000, true);
                // readTimeOut süresi sonunda TCP baglantısı kurulamazsa
                if (asyncResult.IsCompleted)
                {
                    var result = await Messenger.GetAsync(VersionCode.V1,
                                                          new IPEndPoint(IPAddress.Parse(textBox1.Text), 161),
                                                          new OctetString("public"),
                                                          new List <Variable> {
                        new Variable(new ObjectIdentifier(textBox2.Text))
                    });

                    //result = Messenger.Get(VersionCode.V1,
                    //    new IPEndPoint(IPAddress.Parse(textBox1.Text), 161),
                    //    new OctetString("public"),
                    //    new List<Variable> { new Variable(new ObjectIdentifier(textBox2.Text)) },
                    //    5000);


                    textBox3.Text = result[0].Data.ToString();

                    GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                              VersionCode.V1,
                                                                              new OctetString("public"),
                                                                              new List <Variable> {
                        new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.6.0"))
                    });
                    ISnmpMessage response = message.GetResponse(60000, new IPEndPoint(IPAddress.Parse(textBox1.Text), 161));
                    if (response.Pdu().ErrorStatus.ToInt32() != 0)
                    {
                        //throw ErrorException.Create("error in response",receiver.Address,response);
                    }

                    var result1 = response.Pdu().Variables;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        internal override void GetNext(Variable variable)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(
                Messenger.NextRequestId,
                VersionCode,
                GetCommunity,
                new List <Variable> {
                variable
            });
            ISnmpMessage response = message.GetResponse(Timeout, Agent);

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

            Logger.Info(response.Pdu().Variables[0].ToString(Objects));
        }
        public void SnmpGetNext(string community, string ipAddress, string oidKey)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V2,
                                                                      new OctetString(community),
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(oidKey))
            });
            ISnmpMessage response = message.GetResponse(6000, new IPEndPoint(IPAddress.Parse(ipAddress), 161));

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "Error in response!",
                          IPAddress.Parse(ipAddress),
                          response);
            }

            var result = response.Pdu().Variables;

            variableList = result.ToList();
        }
        //-----------------------------------------------------------------------------
        //SNMPGETNEXT
        public void SnmpGetNext(string oidKey)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V2,
                                                                      community,
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(oidKey))
            });
            ISnmpMessage response = message.GetResponse(6000, server);

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "Error in response!",
                          server.Address,
                          response);
            }

            var result = response.Pdu().Variables;

            variableList = result.ToList();
        }
示例#8
0
        public static IList <Variable> GetNext(string IpAddress, string readPermissionString, string Identifier, int readPort)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V1,
                                                                      new OctetString(readPermissionString),
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(Identifier))
            });
            ISnmpMessage response = message.GetResponse(60000, new IPEndPoint(IPAddress.Parse(IpAddress), readPort));

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          IPAddress.Parse("192.168.1.2"),
                          response);
            }

            var result = response.Pdu().Variables;

            return(result);
        }
示例#9
0
        private void SNMP_GET_NEXT()
        {
            string adres = addressBox.Text;
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V1,
                                                                      new OctetString("public"),
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(adres))
            });
            ISnmpMessage response = message.GetResponse(60000, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 161));

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw new Exception();
            }

            var result = response.Pdu().Variables;

            foreach (var v in result)
            {
                consoleBox.Items.Add(v.ToString());
            }
        }
示例#10
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:", "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 < 2)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyVersionAttribute>().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                var addresses = Dns.GetHostAddressesAsync(extra[0]);
                addresses.Wait();
                foreach (IPAddress address in
                         addresses.Result.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)
                {
                    GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                              version,
                                                                              new OctetString(community),
                                                                              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)
                {
                    if (DESPrivacyProvider.IsSupported)
                    {
                        priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                    }
                    else
                    {
                        Console.WriteLine("DES (ECB) is not supported by .NET Core.");
                        return;
                    }
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

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

                GetNextRequestMessage request = new GetNextRequestMessage(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 GetNextRequestMessage(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);
            }
        }
示例#11
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;

            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("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:", "-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)
                {
                    GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                              version,
                                                                              new OctetString(community),
                                                                              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.NextDiscovery;
                ReportMessage report    = discovery.GetResponse(timeout, receiver);

                GetNextRequestMessage request = new GetNextRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), 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);
            }
        }