ComputerUtil.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. namespace Admin.NET.Core;
  10. public static class ComputerUtil
  11. {
  12. /// <summary>
  13. /// 内存信息
  14. /// </summary>
  15. /// <returns></returns>
  16. public static MemoryMetrics GetComputerInfo()
  17. {
  18. MemoryMetricsClient client = new();
  19. MemoryMetrics memoryMetrics = IsUnix() ? client.GetUnixMetrics() : client.GetWindowsMetrics();
  20. memoryMetrics.FreeRam = Math.Round(memoryMetrics.Free / 1024, 2) + "GB";
  21. memoryMetrics.UsedRam = Math.Round(memoryMetrics.Used / 1024, 2) + "GB";
  22. memoryMetrics.TotalRam = Math.Round(memoryMetrics.Total / 1024, 2) + "GB";
  23. memoryMetrics.RamRate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total).ToString() + "%";
  24. memoryMetrics.CpuRate = Math.Ceiling(GetCPURate().ParseToDouble()) + "%";
  25. return memoryMetrics;
  26. }
  27. /// <summary>
  28. /// 磁盘信息
  29. /// </summary>
  30. /// <returns></returns>
  31. public static List<DiskInfo> GetDiskInfos()
  32. {
  33. List<DiskInfo> diskInfos = new();
  34. if (IsUnix())
  35. {
  36. string output = ShellUtil.Bash("df -m / | awk '{print $2,$3,$4,$5,$6}'");
  37. var arr = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
  38. if (arr.Length == 0) return diskInfos;
  39. var rootDisk = arr[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  40. if (rootDisk == null || rootDisk.Length == 0)
  41. return diskInfos;
  42. DiskInfo diskInfo = new()
  43. {
  44. DiskName = "/",
  45. TotalSize = long.Parse(rootDisk[0]) / 1024,
  46. Used = long.Parse(rootDisk[1]) / 1024,
  47. AvailableFreeSpace = long.Parse(rootDisk[2]) / 1024,
  48. AvailablePercent = decimal.Parse(rootDisk[3].Replace("%", ""))
  49. };
  50. diskInfos.Add(diskInfo);
  51. }
  52. else
  53. {
  54. var driv = DriveInfo.GetDrives().Where(u => u.IsReady);
  55. foreach (var item in driv)
  56. {
  57. if (item.DriveType == DriveType.CDRom) continue;
  58. var obj = new DiskInfo()
  59. {
  60. DiskName = item.Name,
  61. TypeName = item.DriveType.ToString(),
  62. TotalSize = item.TotalSize / 1024 / 1024 / 1024,
  63. AvailableFreeSpace = item.AvailableFreeSpace / 1024 / 1024 / 1024,
  64. };
  65. obj.Used = obj.TotalSize - obj.AvailableFreeSpace;
  66. obj.AvailablePercent = decimal.Ceiling(obj.Used / (decimal)obj.TotalSize * 100);
  67. diskInfos.Add(obj);
  68. }
  69. }
  70. return diskInfos;
  71. }
  72. /// <summary>
  73. /// 获取外网IP地址
  74. /// </summary>
  75. /// <returns></returns>
  76. public static string GetIpFromOnline()
  77. {
  78. var url = "http://myip.ipip.net";
  79. var stream = url.GetAsStreamAsync().GetAwaiter().GetResult();
  80. var streamReader = new StreamReader(stream.Stream, stream.Encoding);
  81. var html = streamReader.ReadToEnd();
  82. return html.Replace("当前 IP:", "").Replace("来自于:", "");
  83. }
  84. public static bool IsUnix()
  85. {
  86. return RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  87. }
  88. public static string GetCPURate()
  89. {
  90. string cpuRate;
  91. if (IsUnix())
  92. {
  93. string output = ShellUtil.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
  94. cpuRate = output.Trim();
  95. }
  96. else
  97. {
  98. string output = ShellUtil.Cmd("wmic", "cpu get LoadPercentage");
  99. cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
  100. }
  101. return cpuRate;
  102. }
  103. /// <summary>
  104. /// 获取系统运行时间
  105. /// </summary>
  106. /// <returns></returns>
  107. public static string GetRunTime()
  108. {
  109. string runTime = string.Empty;
  110. if (IsUnix())
  111. {
  112. string output = ShellUtil.Bash("uptime -s").Trim();
  113. runTime = DateTimeUtil.FormatTime((DateTime.Now - output.ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  114. }
  115. else
  116. {
  117. string output = ShellUtil.Cmd("wmic", "OS get LastBootUpTime/Value");
  118. string[] outputArr = output.Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  119. if (outputArr.Length == 2)
  120. runTime = DateTimeUtil.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  121. }
  122. return runTime;
  123. }
  124. }
  125. /// <summary>
  126. /// 内存信息
  127. /// </summary>
  128. public class MemoryMetrics
  129. {
  130. [JsonIgnore]
  131. public double Total { get; set; }
  132. [JsonIgnore]
  133. public double Used { get; set; }
  134. [JsonIgnore]
  135. public double Free { get; set; }
  136. /// <summary>
  137. /// 已用内存
  138. /// </summary>
  139. public string UsedRam { get; set; }
  140. /// <summary>
  141. /// CPU使用率%
  142. /// </summary>
  143. public string CpuRate { get; set; }
  144. /// <summary>
  145. /// 总内存 GB
  146. /// </summary>
  147. public string TotalRam { get; set; }
  148. /// <summary>
  149. /// 内存使用率 %
  150. /// </summary>
  151. public string RamRate { get; set; }
  152. /// <summary>
  153. /// 空闲内存
  154. /// </summary>
  155. public string FreeRam { get; set; }
  156. }
  157. /// <summary>
  158. /// 磁盘信息
  159. /// </summary>
  160. public class DiskInfo
  161. {
  162. /// <summary>
  163. /// 磁盘名
  164. /// </summary>
  165. public string DiskName { get; set; }
  166. /// <summary>
  167. /// 类型名
  168. /// </summary>
  169. public string TypeName { get; set; }
  170. /// <summary>
  171. /// 总剩余
  172. /// </summary>
  173. public long TotalFree { get; set; }
  174. /// <summary>
  175. /// 总量
  176. /// </summary>
  177. public long TotalSize { get; set; }
  178. /// <summary>
  179. /// 已使用
  180. /// </summary>
  181. public long Used { get; set; }
  182. /// <summary>
  183. /// 可使用
  184. /// </summary>
  185. public long AvailableFreeSpace { get; set; }
  186. /// <summary>
  187. /// 使用百分比
  188. /// </summary>
  189. public decimal AvailablePercent { get; set; }
  190. }
  191. public class MemoryMetricsClient
  192. {
  193. /// <summary>
  194. /// windows系统获取内存信息
  195. /// </summary>
  196. /// <returns></returns>
  197. public MemoryMetrics GetWindowsMetrics()
  198. {
  199. string output = ShellUtil.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
  200. var metrics = new MemoryMetrics();
  201. var lines = output.Trim().Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  202. if (lines.Length <= 0) return metrics;
  203. var freeMemoryParts = lines[0].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  204. var totalMemoryParts = lines[1].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  205. metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
  206. metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);//m
  207. metrics.Used = metrics.Total - metrics.Free;
  208. return metrics;
  209. }
  210. /// <summary>
  211. /// Unix系统获取
  212. /// </summary>
  213. /// <returns></returns>
  214. public MemoryMetrics GetUnixMetrics()
  215. {
  216. string output = ShellUtil.Bash("free -m | awk '{print $2,$3,$4,$5,$6}'");
  217. var metrics = new MemoryMetrics();
  218. var lines = output.Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  219. if (lines.Length <= 0) return metrics;
  220. if (lines != null && lines.Length > 0)
  221. {
  222. var memory = lines[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  223. if (memory.Length >= 3)
  224. {
  225. metrics.Total = double.Parse(memory[0]);
  226. metrics.Used = double.Parse(memory[1]);
  227. metrics.Free = double.Parse(memory[2]);//m
  228. }
  229. }
  230. return metrics;
  231. }
  232. }
  233. public class ShellUtil
  234. {
  235. /// <summary>
  236. /// linux 系统命令
  237. /// </summary>
  238. /// <param name="command"></param>
  239. /// <returns></returns>
  240. public static string Bash(string command)
  241. {
  242. var escapedArgs = command.Replace("\"", "\\\"");
  243. var process = new Process()
  244. {
  245. StartInfo = new ProcessStartInfo
  246. {
  247. FileName = "/bin/bash",
  248. Arguments = $"-c \"{escapedArgs}\"",
  249. RedirectStandardOutput = true,
  250. UseShellExecute = false,
  251. CreateNoWindow = true,
  252. }
  253. };
  254. process.Start();
  255. string result = process.StandardOutput.ReadToEnd();
  256. process.WaitForExit();
  257. process.Dispose();
  258. return result;
  259. }
  260. /// <summary>
  261. /// windows系统命令
  262. /// </summary>
  263. /// <param name="fileName"></param>
  264. /// <param name="args"></param>
  265. /// <returns></returns>
  266. public static string Cmd(string fileName, string args)
  267. {
  268. string output = string.Empty;
  269. var info = new ProcessStartInfo();
  270. info.FileName = fileName;
  271. info.Arguments = args;
  272. info.RedirectStandardOutput = true;
  273. using (var process = Process.Start(info))
  274. {
  275. output = process.StandardOutput.ReadToEnd();
  276. }
  277. return output;
  278. }
  279. }