ComputerHelper.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using Infrastructure.Extensions;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. namespace Infrastructure
  10. {
  11. public class ComputerHelper
  12. {
  13. /// <summary>
  14. /// 内存使用情况
  15. /// </summary>
  16. /// <returns></returns>
  17. public static MemoryMetrics GetComputerInfo()
  18. {
  19. try
  20. {
  21. MemoryMetricsClient client = new();
  22. MemoryMetrics memoryMetrics = IsUnix() ? client.GetUnixMetrics() : client.GetWindowsMetrics();
  23. memoryMetrics.FreeRam = Math.Round(memoryMetrics.Free / 1024, 2) + "GB";
  24. memoryMetrics.UsedRam = Math.Round(memoryMetrics.Used / 1024, 2) + "GB";
  25. memoryMetrics.TotalRAM = Math.Round(memoryMetrics.Total / 1024, 2) + "GB";
  26. memoryMetrics.RAMRate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total).ToString() + "%";
  27. memoryMetrics.CPURate = Math.Ceiling(GetCPURate().ParseToDouble()) + "%";
  28. return memoryMetrics;
  29. }
  30. catch (Exception ex)
  31. {
  32. Console.WriteLine("获取内存使用出错,msg=" + ex.Message + "," + ex.StackTrace);
  33. }
  34. return new MemoryMetrics();
  35. }
  36. /// <summary>
  37. /// 获取内存大小
  38. /// </summary>
  39. /// <returns></returns>
  40. public static List<DiskInfo> GetDiskInfos()
  41. {
  42. List<DiskInfo> diskInfos = new();
  43. if (IsUnix())
  44. {
  45. try
  46. {
  47. string output = ShellHelper.Bash("df -m / | awk '{print $2,$3,$4,$5,$6}'");
  48. var arr = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
  49. if (arr.Length == 0) return diskInfos;
  50. var rootDisk = arr[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  51. if (rootDisk == null || rootDisk.Length == 0)
  52. {
  53. return diskInfos;
  54. }
  55. DiskInfo diskInfo = new()
  56. {
  57. DiskName = "/",
  58. TotalSize = long.Parse(rootDisk[0]) / 1024,
  59. Used = long.Parse(rootDisk[1]) / 1024,
  60. AvailableFreeSpace = long.Parse(rootDisk[2]) / 1024,
  61. AvailablePercent = decimal.Parse(rootDisk[3].Replace("%", ""))
  62. };
  63. diskInfos.Add(diskInfo);
  64. }
  65. catch (Exception ex)
  66. {
  67. Console.WriteLine("获取磁盘信息出错了" + ex.Message);
  68. }
  69. }
  70. else
  71. {
  72. var driv = DriveInfo.GetDrives();
  73. foreach (var item in driv)
  74. {
  75. try
  76. {
  77. var obj = new DiskInfo()
  78. {
  79. DiskName = item.Name,
  80. TypeName = item.DriveType.ToString(),
  81. TotalSize = item.TotalSize / 1024 / 1024 / 1024,
  82. AvailableFreeSpace = item.AvailableFreeSpace / 1024 / 1024 / 1024,
  83. };
  84. obj.Used = obj.TotalSize - obj.AvailableFreeSpace;
  85. obj.AvailablePercent = decimal.Ceiling(obj.Used / (decimal)obj.TotalSize * 100);
  86. diskInfos.Add(obj);
  87. }
  88. catch (Exception ex)
  89. {
  90. Console.WriteLine("获取磁盘信息出错了" + ex.Message);
  91. continue;
  92. }
  93. }
  94. }
  95. return diskInfos;
  96. }
  97. public static bool IsUnix()
  98. {
  99. var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  100. return isUnix;
  101. }
  102. public static string GetCPURate()
  103. {
  104. string cpuRate;
  105. if (IsUnix())
  106. {
  107. string output = ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
  108. cpuRate = output.Trim();
  109. }
  110. else
  111. {
  112. string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage");
  113. cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
  114. }
  115. return cpuRate;
  116. }
  117. /// <summary>
  118. /// 获取系统运行时间
  119. /// </summary>
  120. /// <returns></returns>
  121. public static string GetRunTime()
  122. {
  123. string runTime = string.Empty;
  124. try
  125. {
  126. if (IsUnix())
  127. {
  128. string output = ShellHelper.Bash("uptime -s").Trim();
  129. runTime = DateTimeHelper.FormatTime((DateTime.Now - output.ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  130. }
  131. else
  132. {
  133. string output = ShellHelper.Cmd("wmic", "OS get LastBootUpTime/Value");
  134. string[] outputArr = output.Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  135. if (outputArr.Length == 2)
  136. {
  137. runTime = DateTimeHelper.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  138. }
  139. }
  140. }
  141. catch (Exception ex)
  142. {
  143. Console.WriteLine("获取runTime出错" + ex.Message);
  144. }
  145. return runTime;
  146. }
  147. }
  148. /// <summary>
  149. /// 内存信息
  150. /// </summary>
  151. public class MemoryMetrics
  152. {
  153. [JsonIgnore]
  154. public double Total { get; set; }
  155. [JsonIgnore]
  156. public double Used { get; set; }
  157. [JsonIgnore]
  158. public double Free { get; set; }
  159. public string UsedRam { get; set; }
  160. /// <summary>
  161. /// CPU使用率%
  162. /// </summary>
  163. public string CPURate { get; set; }
  164. /// <summary>
  165. /// 总内存 GB
  166. /// </summary>
  167. public string TotalRAM { get; set; }
  168. /// <summary>
  169. /// 内存使用率 %
  170. /// </summary>
  171. public string RAMRate { get; set; }
  172. /// <summary>
  173. /// 空闲内存
  174. /// </summary>
  175. public string FreeRam { get; set; }
  176. }
  177. public class DiskInfo
  178. {
  179. /// <summary>
  180. /// 磁盘名
  181. /// </summary>
  182. public string DiskName { get; set; }
  183. public string TypeName { get; set; }
  184. public long TotalFree { get; set; }
  185. public long TotalSize { get; set; }
  186. /// <summary>
  187. /// 已使用
  188. /// </summary>
  189. public long Used { get; set; }
  190. /// <summary>
  191. /// 可使用
  192. /// </summary>
  193. public long AvailableFreeSpace { get; set; }
  194. public decimal AvailablePercent { get; set; }
  195. }
  196. public class MemoryMetricsClient
  197. {
  198. #region 获取内存信息
  199. /// <summary>
  200. /// windows系统获取内存信息
  201. /// </summary>
  202. /// <returns></returns>
  203. public MemoryMetrics GetWindowsMetrics()
  204. {
  205. string output = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
  206. var metrics = new MemoryMetrics();
  207. var lines = output.Trim().Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  208. if (lines.Length <= 0) return metrics;
  209. var freeMemoryParts = lines[0].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  210. var totalMemoryParts = lines[1].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  211. metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
  212. metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);//m
  213. metrics.Used = metrics.Total - metrics.Free;
  214. return metrics;
  215. }
  216. /// <summary>
  217. /// Unix系统获取
  218. /// </summary>
  219. /// <returns></returns>
  220. public MemoryMetrics GetUnixMetrics()
  221. {
  222. string output = ShellHelper.Bash("free -m | awk '{print $2,$3,$4,$5,$6}'");
  223. var metrics = new MemoryMetrics();
  224. var lines = output.Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  225. if (lines.Length <= 0) return metrics;
  226. if (lines != null && lines.Length > 0)
  227. {
  228. var memory = lines[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  229. if (memory.Length >= 3)
  230. {
  231. metrics.Total = double.Parse(memory[0]);
  232. metrics.Used = double.Parse(memory[1]);
  233. metrics.Free = double.Parse(memory[2]);//m
  234. }
  235. }
  236. return metrics;
  237. }
  238. #endregion
  239. }
  240. }