Example #1
0
        /// <summary>
        /// Constructor
        /// </summary>
        static void Main(string[] args)
        {
            Debug.AutoFlush   = true;
            Debug.IndentLevel = 0;

            // Write to CLI also
            TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out);

            Debug.Listeners.Add(writer);

            run = new WinLLDP(OsInfo.GetStaticInfo());

            // Send first packet immediately
            SendPacket();

            // Run the LLDP packet sender every X seconds
            Debug.WriteLine("Starting timer", EventLogEntryType.Information);
            timer.Interval  = TimeSpan.FromSeconds(10).TotalMilliseconds;
            timer.AutoReset = true;
            timer.Elapsed  += TriggerEvent;
            timer.Start();

            // Wait for keypress
            Debug.WriteLine("Press key to stop", EventLogEntryType.Information);
            Console.ReadKey();

            timer.Stop();
        }
Example #2
0
 /// <summary>
 /// 连接一句话
 /// </summary>
 private void ConnectOneShell()
 {
     try
     {
         //初始化ShellCmder
         _shellCmder = new ShellCmder(_hostService, _shellData);
         //初始化内部命令
         _internalCommand = new InternalCommand(shellTextBox_Cmder, _shellCmder);
         //获取系统信息
         OsInfo info = _shellCmder.GetSysInfo();
         string str  = string.Format("操作系统平台:{0}    当前用户:{1}", info.Platform, info.CurrentUser);
         //设置系统平台
         if (info.DirSeparators == @"\")
         {
             _isWin = true;
         }
         else
         {
             _isWin = false;
         }
         //设置当前目录
         _currentDir = info.ShellDir;
         //cmder的系统平台
         shellTextBox_Cmder.IsWin = _isWin;
         //设置提示信息
         shellTextBox_Cmder.Prompt = _currentDir;
         shellTextBox_Cmder.PrintCommandResult(str);
     }
     catch (Exception ex)
     {
         shellTextBox_Cmder.PrintCommandResult(ex.Message);
     }
 }
Example #3
0
        private static OsInfo GetLinuxOsInfo()
        {
            var osInfo = new OsInfo
            {
                Type         = OSType.Linux,
                FullName     = RuntimeInformation.OSDescription,
                BuildVersion = ReadBuildVersion()
            };

            try
            {
                var path = osInfo.FullName.Contains("SUSE", StringComparison.OrdinalIgnoreCase)
                    ? "/usr/lib/os-release"
                    : "/etc/os-release";

                var osReleaseProperties =
                    (from line in File.ReadAllLines(path)
                     let splitted = line.Split("=")
                                    where splitted.Length == 2
                                    select(Key: splitted[0], Value: splitted[1]?.Replace("\"", string.Empty)))
                    .ToDictionary(x => x.Key, x => x.Value);

                osReleaseProperties.TryGetValue("NAME", out var name);

                var version = GetVersionByDistro(name);
                if (string.IsNullOrWhiteSpace(version) &&
                    osReleaseProperties.TryGetValue("VERSION_ID", out var versionId))
                {
                    version = versionId;
                }

                if (osReleaseProperties.TryGetValue("PRETTY_NAME", out var prettyName))
                {
                    osInfo.FullName = prettyName;
                }
                else if (string.IsNullOrWhiteSpace(version) == false && name != null)
                {
                    osInfo.FullName = $"{name} {version}";
                }

                osInfo.Version = version;
            }
            catch (Exception e)
            {
                if (Logger.IsOperationsEnabled)
                {
                    Logger.Operations("Failed to get Linux OS info", e);
                }
            }

            return(osInfo);
        }
Example #4
0
        public Task <OsInfo> ReadOsInfo()
        {
            var computerInfo = new ComputerInfo();

            var info = new OsInfo
            {
                MachineName          = Environment.MachineName,
                Bitness              = Environment.Is64BitOperatingSystem ? (byte)64 : (byte)32,
                Edition              = computerInfo.OSFullName,
                Version              = computerInfo.OSVersion,
                InstalledUICulture   = CultureInfo.InstalledUICulture.IetfLanguageTag,
                EnvironmentVariables = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)
            };

            return(Task.FromResult(info));
        }
Example #5
0
        private static OsInfo GetOSInformation()
        {
            OsInfo                   inf      = new OsInfo();
            WqlObjectQuery           objQuery = new WqlObjectQuery("select * from win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(objQuery);

            object val;

            foreach (ManagementObject share in searcher.Get())
            {
                val = share["Name"];
                if (null != val)
                {
                    inf.OS = val.ToString().Split('|')[0];
                }
                else
                {
                    inf.OS = string.Empty;
                }

                val = share["Locale"];
                if (null != val)
                {
                    switch (val.ToString())
                    {
                    case "0409":
                        inf.OSLocale = "ENG";
                        break;

                    case "0411":
                        inf.OSLocale = "JPN";
                        break;

                    case "0407":
                        inf.OSLocale = "GER";
                        break;
                    }
                }
                else
                {
                    inf.OSLocale = string.Empty;
                }
            }

            return(inf);
        }
Example #6
0
        private static OsInfo GetMacOsInfo()
        {
            var osInfo = new OsInfo
            {
                Type     = OSType.MacOS,
                FullName = RuntimeInformation.OSDescription
            };

            try
            {
                var          doc = new XmlDocument();
                const string systemVersionPlist = "/System/Library/CoreServices/SystemVersion.plist";
                doc.Load(systemVersionPlist);
                var dictionaryNode = doc.DocumentElement.SelectSingleNode("dict");

                Debug.Assert(dictionaryNode != null && dictionaryNode.ChildNodes.Count % 2 == 0);

                for (var i = 0; i < dictionaryNode.ChildNodes.Count; i += 2)
                {
                    var keyNode   = dictionaryNode.ChildNodes[i];
                    var valueNode = dictionaryNode.ChildNodes[i + 1];

                    switch (keyNode.InnerText)
                    {
                    case "ProductBuildVersion":
                        osInfo.BuildVersion = valueNode.InnerText;
                        break;

                    case "ProductVersion":
                        osInfo.Version = valueNode.InnerText;
                        break;
                    }
                }

                osInfo.FullName = GetMacOsName(osInfo.Version);
            }
            catch (Exception e)
            {
                if (Logger.IsOperationsEnabled)
                {
                    Logger.Operations("Failed to get macOS info", e);
                }
            }

            return(osInfo);
        }
Example #7
0
            public static RuleInfo Parse(JObject json)
            {
                JToken temp;

                string action = null;
                OsInfo os     = new OsInfo();

                if (json.TryGetValue("action", out temp) && temp.Type == JTokenType.String)
                {
                    action = temp.ToString();
                }
                if (json.TryGetValue("os", out temp) && temp.Type == JTokenType.Object)
                {
                    os = OsInfo.Parse(JObject.Parse(temp.ToString()));
                }

                return(new RuleInfo(action, os));
            }
Example #8
0
        public ActionResult Index(string id)
        {
            var enterprise = !string.IsNullOrEmpty(id) && id.ToLowerInvariant() == "enterprise";

            ConnectionSettingsModel     connectionSettings   = null;
            InstallationComponentsModel availableComponents  = CacheHelper.GetAvailableComponents(enterprise);
            InstallationComponentsModel installedComponents  = null;
            InstallationComponentsModel selectedComponents   = null;
            InstallationProgressModel   installationProgress = null;
            OsInfo osInfo = null;

            if (!string.IsNullOrEmpty(UserId))
            {
                connectionSettings = CacheHelper.GetConnectionSettings(UserId);

                if (connectionSettings != null)
                {
                    installedComponents  = CacheHelper.GetInstalledComponents(UserId);
                    selectedComponents   = CacheHelper.GetSelectedComponents(UserId);
                    installationProgress = CacheHelper.GetInstallationProgress(UserId);
                    osInfo = CacheHelper.GetOsInfo(UserId);
                }
                else
                {
                    CookieHelper.ClearCookie();
                    CacheHelper.ClearUserCache(UserId);
                }
            }

            ViewBag.ConnectionSettings   = GetJsonString(connectionSettings);
            ViewBag.AvailableComponents  = GetJsonString(availableComponents);
            ViewBag.InstalledComponents  = GetJsonString(installedComponents);
            ViewBag.SelectedComponents   = GetJsonString(selectedComponents);
            ViewBag.InstallationProgress = GetJsonString(installationProgress);
            ViewBag.OsInfo     = GetJsonString(osInfo);
            ViewBag.Enterprise = enterprise;

            if (!string.IsNullOrEmpty(Settings.CacheKey) && Request.Params["cache"] == Settings.CacheKey)
            {
                CacheHelper.ClearCache();
            }

            return(View());
        }
Example #9
0
        protected override void ProcessReceivedMessageRequest(SocketAsyncEventArgs e, RequestMessage message)
        {
            var token = (AgentAsyncUserToken)e.UserToken;

            ResponseMessage responseMsg;

            switch (message.OpCode)
            {
            case (int)EOpCode.IpConfigData:
                var ipdata = new IpConfigData();
                OpProcessor.GetInfo(ipdata, ((IPEndPoint)token.Socket.LocalEndPoint).Address.ToString());           // fill required data
                responseMsg = new ResponseMessage {
                    Response = ipdata
                };
                SendMessage(e, WoxalizerAdapter.SerializeToXml(responseMsg, TypeResolving.AssemblyResolveHandler));
                break;

            case (int)EOpCode.RunProcess:
                RunCompletedStatus result = OpProcessor.StartProcess((RunProcess)message.Request);
                responseMsg = new ResponseMessage {
                    Response = result
                };
                SendMessage(e, WoxalizerAdapter.SerializeToXml(responseMsg, TypeResolving.AssemblyResolveHandler));
                break;

            case (int)EOpCode.OsInfo:
                var os = new OsInfo();
                OpProcessor.GetInfo(os);



                break;

                //    //TODO:  Add all OpCodes...

                break;

            default:
                throw new ArgumentException("WARNING: Got unknown operation code request!");
            }
        }
Example #10
0
        public void ConfigureTracing()
        {
            try
            {
                this._setupConfig.InstrumentationConfig.AddResourceEnhancers(new List <IResourceEnhancer>
                {
                    OsInfo.GetResourceEnhancer(),
                    AwsInstanceIdentityProvider.GetCloudResourceEnhancer(),
                    AwsInstanceIdentityProvider.GetHostResourceEnhancer()
                });

                this._tracerProvider = TracingSetup.Configure(this._setupConfig.InstrumentationConfig);
                this._periodicUpdater.Start();
                this._periodicMetricsReporter.Start();
                this._configured = true;
            }
            catch (Exception ex)
            {
                this._setupConfig.Logger.Error(nameof(SimpleTracingSetup), "Failed to configure OpenTelemetry", ex);
            }
        }
Example #11
0
        /*public static Dictionary<string, string> BiosInfo()
         * {
         *  List<string> properties = new List<string>() { };
         *  Dictionary<string, string> result = new Dictionary<string, string>(properties.Count);
         *  string query = "SELECT * FROM Win32_BaseBoard";
         *  ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
         *  foreach (ManagementObject info in searcher.Get())
         *  {
         *      foreach (var property in properties)
         *      {
         *          result[property] = info.GetPropertyValue(property).ToString();
         *      }
         *  }
         *
         *  return result;
         * }*/

        public static Dictionary <string, Dictionary <string, string> > Get()
        {
            var info = new Dictionary <string, Dictionary <string, string> >();

            info.Add("OS", OsInfo.ToDictionary());

            var i = 1;

            foreach (var cpuInfo in CPUsInfo)
            {
                info.Add("CPU " + i, cpuInfo.ToDictionary());
                ++i;
            }

            info.Add("RAM", GeneralRamInfo.ToDictionary());

            i = 1;
            foreach (var ramBoard in RamBoardsInfo)
            {
                info.Add("RAM board " + i, ramBoard.ToDictionary());
                ++i;
            }

            /*i = 1;
             * var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_CacheMemory");
             * foreach (var obj in searcher.Get())
             * {
             *  Dictionary<string, string> result = new Dictionary<string, string>(obj.Properties.Count);
             *  foreach (var property in obj.Properties)
             *  {
             *      if (property.Value != null)
             *      result[property.Name] = property.Value.ToString();
             *  }
             *  info.Add("Win32_CacheMemory " + i, result);
             ++i;
             * }*/

            return(info);
        }
Example #12
0
        static void TestNodeFeature_OS_Example2()
        {
            //https://nodejs.org/dist/latest-v11.x/docs/api/os.html
#if DEBUG
            JsBridge.dbugTestCallbacks();
#endif
            //------------

            ////example2: get value from node js
            OsInfo myOsInfo = new OsInfo();
            NodeJsEngineHelper.Run(ss =>
            {
                ss.SetExternalObj("my_osInfo", myOsInfo);

                return(@"                     
                    const os = require('os');                      
                    my_osInfo.Arch = os.arch();
                    my_osInfo.Hostname = os.hostname();
                    ");
            });
            Console.WriteLine("arch=" + myOsInfo.Arch);
            Console.WriteLine("hostname=" + myOsInfo.Hostname);
            string userInput = Console.ReadLine();
        }
Example #13
0
        public static void SetOsInfo(string userId, OsInfo value)
        {
            var key = "osInfo" + userId;

            CacheSet(key, value, TimeSpan.FromDays(1));
        }
Example #14
0
        private static StreamWriter WriteTestLogHeaders(string path, TestSystem ts, string title)
        {
            FileInfo     file = new FileInfo(path + @"\" + TestSystem.ResultsFile);
            StreamWriter w    = file.CreateText();

            w.WriteLine("<html>");
            w.WriteLine("<title>");
            w.WriteLine(title);
            w.WriteLine("</title>");
            w.WriteLine("<table border=\"2\" bordercolor=\"gray\" width=\"40%\" align=\"center\">");
            w.WriteLine("<tr><td align=\"center\" bordercolor=\"white\"><b><font size=\"6\">");
            w.WriteLine(title);
            w.WriteLine("</font></b></td></tr>");

            // Write the test automation machine name to the log.
            w.WriteLine("<tr><td align=\"center\" bordercolor=\"white\"><b><font size=\"4\" color=\"#006666\">");
            w.WriteLine("Machine Information");
            w.WriteLine("</font><br/>");
            w.WriteLine("<font size=\"2\" color=\"#3374EC\">");
            w.WriteLine(Environment.MachineName);
            OsInfo osInformation = GetOSInformation();
            string procArch      = Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER");

            string[] procInfoArray = procArch.Split(' ');
            w.WriteLine("<br/>");
            w.WriteLine(osInformation.OS
                        + " (" + osInformation.OSLocale + ")"
                        + " " + procInfoArray[0]
                        + " " + procInfoArray[procInfoArray.Length - 1]);

            if (!string.IsNullOrEmpty(VisualStudioSkew))
            {
                w.WriteLine("<br/>");
                w.WriteLine(VisualStudioSkew);
            }
            w.WriteLine("</font></b></td></tr>");

            if (!string.IsNullOrEmpty(ts.FullDeviceName))
            {
                w.WriteLine("<tr><td align=\"center\" bordercolor=\"white\"><b><font size=\"3\" color=\"brown\">");
                w.WriteLine("Device: " + ts.FullDeviceName);
                w.WriteLine("</font></b></td></tr>");
            }

            if (!string.IsNullOrEmpty(ts.Transport.ToString()) &&
                !string.Equals(ts.Transport.ToString().ToLower(), "none"))
            {
                w.WriteLine("<tr><td align=\"center\" bordercolor=\"white\"><b><font size=\"3\" color=\"brown\">");
                w.WriteLine("Transport: " + ts.Transport);
                w.WriteLine("</font></b></td></tr>");
            }

            if (!string.IsNullOrEmpty(TestSystem.BuildNumber))
            {
                w.WriteLine("<tr><td align=\"center\" bordercolor=\"white\"><b><font size=\"3\">");
                if (!string.IsNullOrEmpty(ts.BuildFlavor))
                {
                    w.Write(ts.BuildFlavor);
                }
                w.WriteLine(" build " + TestSystem.BuildNumber + "<br>");
                if (!string.IsNullOrEmpty(ts.Branch))
                {
                    w.WriteLine(ts.Branch);
                }
                w.WriteLine("</font></b></td></tr>");
            }

            return(w);
        }
Example #15
0
 public RuleInfo()
 {
     Action = null;
     Os     = new OsInfo();
 }
Example #16
0
 public RuleInfo(string action, OsInfo os)
 {
     Action = action;
     Os     = os;
 }
Example #17
0
        private static OsInfo GetOSInformation()
        {
            OsInfo inf = new OsInfo();
            WqlObjectQuery objQuery = new WqlObjectQuery("select * from win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(objQuery);

            object val; 
            foreach (ManagementObject share in searcher.Get())
            {
                val = share["Name"];
                if (null != val)
                {                    
                    inf.OS = val.ToString().Split('|')[0];
                }
                else
                {
                    inf.OS = string.Empty;
                }

                val = share["Locale"];
                if (null != val)
                {
                    switch(val.ToString())
                    {
                        case "0409":
                            inf.OSLocale = "ENG";
                            break;
                        case "0411":
                            inf.OSLocale = "JPN";
                            break;
                        case "0407":
                            inf.OSLocale = "GER";
                            break;
                    }
                }
                else
                {
                    inf.OSLocale = string.Empty;
                }
            }

            return inf;
        }
Example #18
0
        public JsonResult Connect(ConnectionSettingsModel connectionSettings, RequestInfoModel requestInfo)
        {
            try
            {
                InstallationComponentsModel installedComponents  = null;
                InstallationComponentsModel selectedComponents   = null;
                InstallationProgressModel   installationProgress = null;
                OsInfo osInfo = null;

                if (connectionSettings != null)
                {
                    if (connectionSettings.Enterprise)
                    {
                        if (string.IsNullOrEmpty(connectionSettings.LicenseKey))
                        {
                            throw new ArgumentException("connectionSettings.licenseKey");
                        }

                        if (connectionSettings.LicenseKey == Settings.TrialFileName && requestInfo == null)
                        {
                            throw new ArgumentNullException("requestInfo");
                        }
                    }

                    var data = SshHelper.Connect(UserId, connectionSettings);

                    osInfo = data.Item1;
                    installedComponents  = data.Item2;
                    installationProgress = CacheHelper.GetInstallationProgress(UserId);
                    selectedComponents   = CacheHelper.GetSelectedComponents(UserId);

                    CacheHelper.SetConnectionSettings(UserId, connectionSettings);
                    CacheHelper.SetInstalledComponents(UserId, installedComponents);
                    CacheHelper.SetRequestInfo(UserId, requestInfo);
                }
                else
                {
                    CookieHelper.ClearCookie();
                    CacheHelper.ClearUserCache(UserId);
                }

                return(Json(new
                {
                    success = true,
                    message = string.Empty,
                    connectionSettings = GetJsonString(connectionSettings),
                    installedComponents = GetJsonString(installedComponents),
                    installationProgress = GetJsonString(installationProgress),
                    selectedComponents = GetJsonString(selectedComponents),
                    osInfo = GetJsonString(osInfo)
                }));
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC").Error(ex.Message, ex);

                return(Json(new
                {
                    success = false,
                    message = ex.Message,
                    errorCode = GetErrorCode(ex.Message)
                }));
            }
        }
Example #19
0
        private static OsInfo GetDefaultWindowsOsInformation()
        {
            var osInfo = new OsInfo
            {
                Type     = OSType.Windows,
                FullName = RuntimeInformation.OSDescription
            };

            try
            {
                const string winString = "Windows ";
                var          idx       = osInfo.FullName.IndexOf("Windows ", StringComparison.OrdinalIgnoreCase);
                if (idx < 0)
                {
                    return(osInfo);
                }

                var ver = osInfo.FullName.Substring(idx + winString.Length);
                if (ver == null)
                {
                    return(osInfo);
                }

                var regex  = new Regex(@"([0-9]+.[0-9]+)");
                var result = regex.Matches(ver);
                if (result.Count != 2)
                {
                    return(osInfo);
                }

                osInfo.Version      = result[0].Value;
                osInfo.BuildVersion = result[1].Value;

                if (decimal.TryParse(osInfo.Version, out var version) == false)
                {
                    return(osInfo);
                }

                var isWindowsServer = IsOS(OS_ANYSERVER);
                switch (version)
                {
                case 10.0m:
                    osInfo.FullName = isWindowsServer ? "Windows Server 2016" : "Windows 10";
                    break;

                case 6.3m:
                    osInfo.FullName = isWindowsServer ? "Windows Server 2012 R2" : "Windows 8.1";
                    break;

                case 6.2m:
                    osInfo.FullName = isWindowsServer ? "Windows Server 2012" : "Windows 8";
                    break;

                case 6.1m:
                    osInfo.FullName = isWindowsServer ? "Windows Server 2008" : "Windows 7";
                    break;
                }
            }
            catch (Exception e)
            {
                if (Logger.IsOperationsEnabled)
                {
                    Logger.Operations("Failed to get default Windows OS info", e);
                }
            }

            return(osInfo);
        }