public void TestConstructor2() { TimeTicks time2 = new TimeTicks(new byte[] { 0x3F, 0xE0 }); Assert.AreEqual(16352, time2.ToUInt32()); Assert.AreEqual(16352.GetHashCode(), time2.GetHashCode()); }
public void TestConstructor3() { TimeTicks time = new TimeTicks(800); uint count = time.ToUInt32(); Assert.AreEqual(time, new TimeTicks(count)); }
public void TestConstructor() { TimeTicks time = new TimeTicks(15); Assert.AreEqual(15, time.ToUInt32()); Assert.AreEqual("15 (00:00:00.1500000)", time.ToString()); }
public void TestEqual() { var left = new TimeTicks(800); var right = new TimeTicks(800); Assert.AreEqual(left, right); }
public void TestConstructor4() { var result = new TimeTicks(171447); var ticks = new TimeTicks(new TimeSpan(0, 0, 28, 34, 470)); Assert.Equal(result, ticks); }
public void TestConstructor() { TimeTicks time = new TimeTicks(15); Assert.Equal(15U, time.ToUInt32()); Assert.Equal("00:00:00.1500000", time.ToString()); }
public void FromSeconds() { float seconds0 = 0.0015F; TimeTicks ticks = TimeTicks.FromSeconds(seconds0); float seconds1 = ticks.TotalSeconds; Assert.AreEqual(seconds0, seconds1); }
/// <summary> /// Creates a <see cref="InformRequestPdu"/> instance for discovery. /// </summary> /// <param name="requestId">The request id.</param> public InformRequestPdu(int requestId) { Enterprise = null; RequestId = new Integer32(requestId); _time = new TimeTicks(0); Variables = new List<Variable>(); _varbindSection = Variable.Transform(Variables); }
public void TestToBytes() { TimeTicks time = new TimeTicks(16352); ISnmpData data = DataFactory.CreateSnmpData(time.ToBytes()); Assert.AreEqual(data.TypeCode, SnmpType.TimeTicks); Assert.AreEqual(16352, ((TimeTicks)data).ToUInt32()); Assert.AreEqual(new byte[] {0x43, 0x05, 0x00, 0x93, 0xA3, 0x41, 0x4B}, new TimeTicks(2476949835).ToBytes()); }
public void TestToTimeSpan() { TimeTicks time = new TimeTicks(171447); TimeSpan result = time.ToTimeSpan(); Assert.AreEqual(0, result.Hours); Assert.AreEqual(28, result.Minutes); Assert.AreEqual(34, result.Seconds); Assert.AreEqual(470, result.Milliseconds); }
public void TestToBytes() { TimeTicks time = new TimeTicks(16352); ISnmpData data = DataFactory.CreateSnmpData(time.ToBytes()); Assert.AreEqual(data.TypeCode, SnmpType.TimeTicks); Assert.AreEqual(16352, ((TimeTicks)data).ToUInt32()); Assert.AreEqual(new byte[] { 0x43, 0x05, 0x00, 0x93, 0xA3, 0x41, 0x4B }, new TimeTicks(2476949835).ToBytes()); }
public void TestTimeticks() { byte[] expected = new byte[] { 0x43, 0x02, 0x3F, 0xE0 }; ISnmpData data = DataFactory.CreateSnmpData(expected); Assert.Equal(SnmpType.TimeTicks, data.TypeCode); TimeTicks t = (TimeTicks)data; Assert.Equal(16352U, t.ToUInt32()); }
public TrapV2Pdu(int requestId, ObjectIdentifier enterprise, uint time, IList<Variable> variables) { Enterprise = enterprise; RequestId = new Integer32(requestId); _time = new TimeTicks(time); Variables = variables; IList<Variable> full = new List<Variable>(variables); full.Insert(0, new Variable(new uint[] { 1, 3, 6, 1, 2, 1, 1, 3, 0 }, _time)); full.Insert(1, new Variable(new uint[] { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 }, Enterprise)); _varbindSection = Variable.Transform(full); }
public void TestEqual() { var left = new TimeTicks(800); var right = new TimeTicks(800); Assert.AreEqual(left, right); // ReSharper disable EqualExpressionComparison Assert.IsTrue(left == left); // ReSharper restore EqualExpressionComparison Assert.IsTrue(left != null); Assert.IsTrue(left.Equals(right)); }
public InformRequestPdu(int requestId, ObjectIdentifier enterprise, uint time, IList<Variable> variables) { Enterprise = enterprise; RequestId = new Integer32(requestId); _time = new TimeTicks(time); Variables = variables; IList<Variable> full = new List<Variable>(variables); full.Insert(0, new Variable(new uint[] { 1, 3, 6, 1, 2, 1, 1, 3, 0 }, _time)); full.Insert(1, new Variable(new uint[] { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 }, Enterprise)); _varbindSection = Variable.Transform(full); ////_raw = ByteTool.ParseItems(_seq, new Integer32(0), new Integer32(0), _varbindSection); }
/// <summary> /// Initializes a new instance of the <see cref="InformRequestPdu"/> class. /// </summary> /// <param name="stream">The stream.</param> public InformRequestPdu(Stream stream) { RequestId = (Integer32)DataFactory.CreateSnmpData(stream); ErrorStatus = (Integer32)DataFactory.CreateSnmpData(stream); ErrorIndex = (Integer32)DataFactory.CreateSnmpData(stream); _varbindSection = (Sequence)DataFactory.CreateSnmpData(stream); Variables = Variable.Transform(_varbindSection); _time = (TimeTicks)Variables[0].Data; Variables.RemoveAt(0); Enterprise = (ObjectIdentifier)Variables[0].Data; Variables.RemoveAt(0); ////_raw = ByteTool.ParseItems(_seq, _errorStatus, _errorIndex, _varbindSection); ////Debug.Assert(length >= _raw.Length, "length not match"); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty propertyValue = property.FindPropertyRelative("m_value"); long value = propertyValue.longValue; var ticks = new TimeTicks(value); TimeSpan span = ticks; string text = span.ToString("G"); text = EditorGUI.DelayedTextField(position, label, text); if (TimeSpan.TryParse(text, out span)) { ticks = span; propertyValue.longValue = ticks.Value; } }
private ISnmpData ConvertStringValue2SnmpData(SnmpType type, string value) { ISnmpData data; try { switch (type) { case SnmpType.Integer32: data = new Integer32(int.Parse(value)); break; case SnmpType.Counter32: data = new Counter32(uint.Parse(value)); break; case SnmpType.Gauge32: data = new Gauge32(uint.Parse(value)); break; case SnmpType.TimeTicks: data = new TimeTicks(uint.Parse(value)); break; case SnmpType.OctetString: data = new OctetString(value); break; case SnmpType.IPAddress: data = new IP((IPAddress.Parse(value)).GetAddressBytes()); break; default: throw new InvalidDataType(); } } catch (InvalidCastException) { throw new InvalidDataType(); } return(data); }
public TrapV2Pdu(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } RequestId = (Integer32)DataFactory.CreateSnmpData(stream); // request #pragma warning disable 168 Integer32 temp1 = (Integer32)DataFactory.CreateSnmpData(stream); // 0 Integer32 temp2 = (Integer32)DataFactory.CreateSnmpData(stream); // 0 #pragma warning restore 168 _varbindSection = (Sequence)DataFactory.CreateSnmpData(stream); Variables = Variable.Transform(_varbindSection); // v[0] is timestamp. v[1] oid, v[2] value. _time = (TimeTicks)Variables[0].Data; Variables.RemoveAt(0); Enterprise = (ObjectIdentifier)Variables[0].Data; Variables.RemoveAt(0); }
public InformRequestPdu(int requestId, ObjectIdentifier enterprise, uint time, IList<Variable> variables) { if (enterprise == null) { throw new ArgumentNullException("enterprise"); } if (variables == null) { throw new ArgumentNullException("variables"); } Enterprise = enterprise; RequestId = new Integer32(requestId); _time = new TimeTicks(time); Variables = variables; IList<Variable> full = new List<Variable>(variables); full.Insert(0, new Variable(_timeId, _time)); full.Insert(1, new Variable(_enterpriseId, Enterprise)); _varbindSection = Variable.Transform(full); }
/// <summary> /// Creates a <see cref="TrapV1Pdu"/> instance with PDU elements. /// </summary> /// <param name="enterprise">Enterprise</param> /// <param name="agent">Agent address</param> /// <param name="generic">Generic trap type</param> /// <param name="specific">Specific trap type</param> /// <param name="timestamp">Time stamp</param> /// <param name="variables">Variable binds</param> public TrapV1Pdu(ObjectIdentifier enterprise, IP agent, Integer32 generic, Integer32 specific, TimeTicks timestamp, IList<Variable> variables) { if (enterprise == null) { throw new ArgumentNullException("enterprise"); } if (agent == null) { throw new ArgumentNullException("agent"); } if (generic == null) { throw new ArgumentNullException("generic"); } if (specific == null) { throw new ArgumentNullException("specific"); } if (timestamp == null) { throw new ArgumentNullException("timestamp"); } if (variables == null) { throw new ArgumentNullException("variables"); } Enterprise = enterprise; AgentAddress = agent; _generic = generic; _specific = specific; TimeStamp = timestamp; _varbindSection = Variable.Transform(variables); Variables = variables; }
public void FromSecondsOneTick() { TimeTicks ticks = TimeTicks.FromSeconds(0.0000001F); Assert.AreEqual(1L, ticks.Value); }
public SysORUpTime(int index, TimeTicks time) : base("1.3.6.1.2.1.1.9.1.4.{0}", index) { _data = time; }
public void OneTickSeconds() { TimeTicks ticks = TimeTicks.FromTicks(1L); Assert.AreEqual(0.0000001F, ticks.TotalSeconds); }
//システム情報の取得 public void getSystemInfo(Class_InputData input, Class_TextLog log, int tabnum = 1) { try { // コミュニティ名 OctetString comm = new OctetString(input.community); // パラメータクラス AgentParameters param = new AgentParameters(comm); // バージョン取得 param.Version = input.versionofSNMPsharp; IpAddress agent = new IpAddress(input.hostname); //System情報の検索 foreach (KeyValuePair <string, string> systemhs in SYSTEMLIST) { //一括のときはやらない if (tabnum == 3 && (systemhs.Key != "sysDescr" && systemhs.Key != "sysName")) { continue; } // Construct target UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add(systemhs.Value); if (input.version == "v1" | input.version == "1") { SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request log.Write("Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex); } else { string value = result.Pdu.VbList[0].Value.ToString(); //TimeTick型の時はミリ秒も出力する if (result.Pdu.VbList[0].Value.Type == SnmpConstants.SMI_TIMETICKS) { TimeTicks timeti = (TimeTicks)result.Pdu.VbList[0].Value; value = "(" + timeti.Milliseconds.ToString() + "ms)" + result.Pdu.VbList[0].Value.ToString(); } systemhash[systemhs.Key] = value; log.Write("GET項目:" + input.hostname + " : " + systemhs.Key + " " + systemhs.Value + " 値:" + value); } } else { //Console.WriteLine("SNMP agentからのレスポンスがありません."); log.Write("SNMP agentからのレスポンスがありません."); } } // v2以降の時 else { SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param); // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request log.Write("Error in SNMP reply. Error " + result.Pdu.ErrorStatus.ToString() + " index " + result.Pdu.ErrorIndex.ToString()); //Console.WriteLine("Error in SNMP reply. Error {0} index {1}", //result.Pdu.ErrorStatus, //result.Pdu.ErrorIndex); } else { string value = result.Pdu.VbList[0].Value.ToString(); //TimeTick型の時はミリ秒も出力する if (result.Pdu.VbList[0].Value.Type == SnmpConstants.SMI_TIMETICKS) { TimeTicks timeti = (TimeTicks)result.Pdu.VbList[0].Value; value = "(" + timeti.Milliseconds.ToString() + "ms)" + result.Pdu.VbList[0].Value.ToString(); } //取得した値を格納 _systemhash[systemhs.Key] = value; log.Write("GET項目:" + input.hostname + " : " + systemhs.Key + " " + systemhs.Value + " 値:" + value); } } else { log.Write("SNMP agentからのレスポンスがありません."); //Console.WriteLine("SNMP agentからのレスポンスがありません."); } } target.Close(); } } catch (Exception) { throw; } }
public void TestConstructor() { TimeTicks time = new TimeTicks(15); Assert.AreEqual(15, time.ToUInt32()); }
public TrapV1Pdu(uint[] enterprise, IP agent, Integer32 generic, Integer32 specific, TimeTicks timestamp, IList<Variable> variables) : this(new ObjectIdentifier(enterprise), agent, generic, specific, timestamp, variables) { }
public void TestConstructor() { TimeTicks time = new TimeTicks(15); Assert.AreEqual(15, time.ToUInt32()); Assert.AreEqual("00:00:00.1500000", time.ToString()); }
public void TestConstructor4() { var result = new TimeTicks(171447); var ticks = new TimeTicks(new TimeSpan(0, 0, 28, 34, 470)); Assert.AreEqual(result, ticks); }
//GETを取得する public void getRequest(Class_InputData input) { try{ // コミュニティ名 OctetString comm = new OctetString(input.community); // パラメータクラス AgentParameters param = new AgentParameters(comm); // バージョン取得 param.Version = input.versionofSNMPsharp; IpAddress agent = new IpAddress(input.hostname); // Construct target UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.Get); pdu.VbList.Add(input.oid); //バージョン1の時 if (input.version == "v1" | input.version == "1") { SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param); // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request Console.WriteLine("Error in SNMP reply. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } else { resultList = new Dictionary <string, string>(); resultList["oid"] = result.Pdu.VbList[0].Oid.ToString(); resultList["type"] = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type); //日本語の可能性あり //ifdescの時日本語の可能性あり //1.3.6.1.2.1.2.2.1.2 ifdesc //1.3.6.1.2.1.25.3.2.1.3. hrDeviceDescr if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.2") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.25.3.2.1.3")) { resultList["value"] = convertJP(result.Pdu.VbList[0].Value.ToString()); } else if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.7.") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.8.")) { resultList["value"] = Util.convIfStatus(result.Pdu.VbList[0].Oid.ToString()); } else { string value = result.Pdu.VbList[0].Value.ToString(); //TimeTick型の時はミリ秒も出力する if (resultList["type"] == SnmpConstants.SMI_TIMETICKS_STR) { TimeTicks timeti = (TimeTicks)result.Pdu.VbList[0].Value; value = "(" + timeti.Milliseconds.ToString() + "ms)" + result.Pdu.VbList[0].Value.ToString(); } resultList["value"] = value; } } } else { Console.WriteLine("SNMP agentからのレスポンスがありません."); } } // v2以降の時 else { SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param); // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request Console.WriteLine("Error in SNMP reply. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); } else { resultList = new Dictionary <string, string>(); resultList["oid"] = result.Pdu.VbList[0].Oid.ToString(); resultList["type"] = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type); //日本語の可能性あり //ifdescの時日本語の可能性あり if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.2") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.25.3.2.1.3")) { resultList["value"] = convertJP(result.Pdu.VbList[0].Value.ToString()); } else if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.7.") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.8.")) { resultList["value"] = Util.convIfStatus(result.Pdu.VbList[0].Oid.ToString()); } else { string value = result.Pdu.VbList[0].Value.ToString(); //TimeTick型の時はミリ秒も出力する if (resultList["type"] == SnmpConstants.SMI_TIMETICKS_STR) { TimeTicks timeti = (TimeTicks)result.Pdu.VbList[0].Value; value = "(" + timeti.Milliseconds.ToString() + "ms)" + result.Pdu.VbList[0].Value.ToString(); } resultList["value"] = value; } } } else { Console.WriteLine("SNMP agentからのレスポンスがありません."); } } target.Close(); } catch (Exception) { throw; } }
public InformRequestPdu(Tuple<int, byte[]> length, Stream stream) { if (length == null) { throw new ArgumentNullException("length"); } if (stream == null) { throw new ArgumentNullException("stream"); } RequestId = (Integer32)DataFactory.CreateSnmpData(stream); #pragma warning disable 168 var temp1 = (Integer32)DataFactory.CreateSnmpData(stream); // 0 var temp2 = (Integer32)DataFactory.CreateSnmpData(stream); // 0 #pragma warning restore 168 _varbindSection = (Sequence)DataFactory.CreateSnmpData(stream); Variables = Variable.Transform(_varbindSection); if (Variables.Count >= 2) { _time = (TimeTicks)Variables[0].Data; Variables.RemoveAt(0); Enterprise = (ObjectIdentifier)Variables[0].Data; Variables.RemoveAt(0); } else if (Variables.Count == 0) { _time = new TimeTicks(0); Enterprise = null; } else { throw new InvalidDataException("malformed inform message"); } _length = length.Item2; }
/// <summary> /// Nạp file json preclaim /// </summary> /// <param name="path"></param> /// <param name="year"></param> /// <param name="month"></param> /// <returns></returns> public static List <PreclaimViewModel> JsonToPreclaim(string path) { string line; List <string> subJsonList = new List <string>(); StreamReader r = new StreamReader(path); bool isFirst = false; string subJson = ""; while ((line = r.ReadLine()) != null) { subJson += line; if (line.Trim() == "{") { isFirst = true; } else if (line.Trim() == "}") { if (isFirst) { subJsonList.Add(subJson); } isFirst = false; subJson = ""; } } List <PreclaimViewModel> objects = new List <PreclaimViewModel>(); BsonDocument doctem = null; PreclaimJson preJson = null; PreclaimViewModel preVM = null; int serial = 1; for (int i = 0; i < subJsonList.Count; i++) { doctem = BsonSerializer.Deserialize <BsonDocument>(subJsonList[i]); preJson = BsonSerializer.Deserialize <PreclaimJson>(doctem); preVM = new PreclaimViewModel { SerialNo = serial, Asset_ID = preJson.Asset_ID, ISRC = preJson.ISRC == null ? string.Empty: VnHelper.ConvertToUnSign(ConvertAllToUnicode.ConvertFromComposite(preJson.ISRC.ToUpper())), Comp_Asset_ID = preJson.Comp_Asset_ID, C_Title = preJson.C_Title == null ? string.Empty : VnHelper.ConvertToUnSign(ConvertAllToUnicode.ConvertFromComposite(preJson.C_Title.ToUpper())), C_ISWC = preJson.C_ISWC == null ? string.Empty : VnHelper.ConvertToUnSign(ConvertAllToUnicode.ConvertFromComposite(preJson.C_ISWC.ToUpper())), C_Workcode = preJson.C_Workcode == null ? string.Empty : VnHelper.ConvertToUnSign(ConvertAllToUnicode.ConvertFromComposite(preJson.C_Workcode.ToUpper())), C_Writers = preJson.C_Writers == null ? string.Empty : VnHelper.ConvertToUnSign(ConvertAllToUnicode.ConvertFromComposite(preJson.C_Writers.ToUpper())), Combined_Claim = preJson.Combined_Claim == null ? "0": VnHelper.ConvertToUnSign(preJson.Combined_Claim), Mechanical = preJson.Mechanical == null ? "0" : VnHelper.ConvertToUnSign(preJson.Mechanical), Performance = preJson.Performance == null ? "0" : VnHelper.ConvertToUnSign(preJson.Performance), //MONTH = month,// preJson.MONTH, //Year = year }; //if (preJson.CREATED_AT != null) //{ preVM.DtCREATED_AT = TimeTicks.ConvertTicksMongoToC(preJson.CREATED_AT); //} if (preJson.UPDATED_AT != null) { preVM.DtUPDATED_AT = TimeTicks.ConvertTicksMongoToC((long)preJson.UPDATED_AT); } objects.Add(preVM); serial++; } return(objects); }
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]).Where(address => address.AddressFamily == AddressFamily.InterNetwork)) { ip = address; break; } if (ip == null) { Console.WriteLine("invalid host or wrong IP address found: " + extra[0]); return; } } if ((extra.Count - 1) % 3 != 0) { Console.WriteLine("invalid variable number: " + (extra.Count - 1)); 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])); 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.NextDiscovery; 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 response = request.GetResponse(timeout, receiver); 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); } }
private List <Variable> BuildVariableList(Command command, List <string> values) { List <Variable> variables = new List <Variable>(); if (command == Command.Get) { for (int i = 1; i < values.Count; i++) { Variable test = new Variable(new ObjectIdentifier(values[i])); variables.Add(test); } } else { for (int i = 1; i < values.Count; i = i + 3) { string type = values[i + 1]; if (type.Length != 1) { throw new InvalidOperationException("SNMP Error: Invalid type string: " + type); } ISnmpData data; switch (type[0]) { case 'i': data = new Integer32(int.Parse(values[i + 2])); break; case 'u': data = new Gauge32(uint.Parse(values[i + 2])); break; case 't': data = new TimeTicks(uint.Parse(values[i + 2])); break; case 'a': data = new IP(IPAddress.Parse(values[i + 2])); break; case 'o': data = new ObjectIdentifier(values[i + 2]); break; case 'x': data = new OctetString(ByteTool.Convert(values[i + 2])); break; case 's': data = new OctetString(values[i + 2]); break; case 'd': data = new OctetString(ByteTool.ConvertDecimal(values[i + 2])); break; case 'n': data = new Null(); break; default: throw new InvalidOperationException("SNMP Error: Unknown type string: " + type[0]); } Variable test = new Variable(new ObjectIdentifier(values[i]), data); variables.Add(test); } } return(variables); }
//v2の時 private int getBulk(AgentParameters param, Form_snmpDataGet form) { try { int ret = 0; //結果格納 resultHashL = new List <Dictionary <string, string> >(); _headerList = new List <string>(); tablearray = new Dictionary <string, List <string> >(); int flg = 0; IpAddress agent = new IpAddress(INPUT.hostname); UdpTarget target = new UdpTarget((IPAddress)agent, 161, 5000, 1); // アドレス ポート 待ち時間 リトライ Oid rootOid = new Oid(INPUT.oid); Oid lastOid = (Oid)rootOid.Clone(); // Pdu class used for all requests Pdu pdu = new Pdu(PduType.GetBulk); pdu.NonRepeaters = 0; pdu.MaxRepetitions = 50; // Loop through results while (lastOid != null) { System.Windows.Forms.Application.DoEvents(); if (form.cancelflg) { //中断された時 form.cancelflg = false; break; } if (pdu.RequestId != 0) { pdu.RequestId += 1; } // Clear Oids from the Pdu class. pdu.VbList.Clear(); // Initialize request PDU with the last retrieved Oid pdu.VbList.Add(lastOid); // Make SNMP request System.Threading.Thread.Sleep(15); SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param); //Console.WriteLine("{0} {1} ", result.Pdu.ErrorStatus,result.Pdu.ErrorIndex); // You should catch exceptions in the Request if using in real application. // If result is null then agent didn't reply or we couldn't parse the reply. if (result != null) { // ErrorStatus other then 0 is an error returned by // the Agent - see SnmpConstants for error definitions if (result.Pdu.ErrorStatus != 0) { // agent reported an error with the request Errormsg = string.Format("Error in SNMP reply. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex); lastOid = null; ret = -1; break; } else { int i = 0; // Walk through returned variable bindings foreach (Vb v in result.Pdu.VbList) { // Check that retrieved Oid is "child" of the root OID if (rootOid.IsRootOf(v.Oid)) { //tableget //値の取得 Dictionary <string, string> hashtbl = new Dictionary <string, string>(); if (INPUT.method == 3) { //テーブル用データの取得 getForTable(v, ref flg); } else { hashtbl["oid"] = v.Oid.ToString(); hashtbl["type"] = SnmpConstants.GetTypeName(v.Value.Type); //ifdescの時日本語の可能性あり //1.3.6.1.2.1.2.2.1.2 ifdesc //1.3.6.1.2.1.25.3.2.1.3. hrDeviceDescr if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.2.") | 0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.25.3.2.1.3.")) { hashtbl["value"] = convertJP(v.Value.ToString()); } else { if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.3.")) { hashtbl["value"] = Util.ifTypeConv(v.Value.ToString()); } else if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.7.") | 0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.8.")) { hashtbl["value"] = Util.convIfStatus(v.Value.ToString()); } else { string value = v.Value.ToString(); //TimeTick型の時はミリ秒も出力する if (hashtbl["type"] == SnmpConstants.SMI_TIMETICKS_STR) { TimeTicks timeti = (TimeTicks)v.Value; value = "(" + timeti.Milliseconds.ToString() + "ms)" + v.Value.ToString(); } hashtbl["value"] = value; } } //リストに格納 resultHashL.Add(hashtbl); } if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW) { lastOid = null; } else { lastOid = v.Oid; } } else { // we have reached the end of the requested // MIB tree. Set lastOid to null and exit loop lastOid = null; } i++; } } } else { Console.WriteLine("No response received from SNMP agent."); } } target.Close(); return(ret); } catch { throw; } }
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(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 = 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) { #if NET452 priv = new DESPrivacyProvider(new OctetString(privPhrase), auth); #else Console.WriteLine("DES (ECB) is not supported by .NET Core."); return; #endif } 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); } }
public InformRequestPdu(Tuple<int, byte[]> length, Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } RequestId = (Integer32)DataFactory.CreateSnmpData(stream); #pragma warning disable 168 var temp1 = (Integer32)DataFactory.CreateSnmpData(stream); // 0 var temp2 = (Integer32)DataFactory.CreateSnmpData(stream); // 0 #pragma warning restore 168 _varbindSection = (Sequence)DataFactory.CreateSnmpData(stream); Variables = Variable.Transform(_varbindSection); _time = (TimeTicks)Variables[0].Data; Variables.RemoveAt(0); Enterprise = (ObjectIdentifier)Variables[0].Data; Variables.RemoveAt(0); _length = length.Item2; }
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); } }