ComputerUtil.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 = ShellHelper.Bash(@"df -mT | awk '/^\/dev\/vd/ {print $1,$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. foreach (var item in arr)
  43. {
  44. var rootDisk = item.Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  45. if (rootDisk == null || rootDisk.Length == 0)
  46. {
  47. return diskInfos;
  48. }
  49. DiskInfo diskInfo = new DiskInfo()
  50. {
  51. DiskName = rootDisk[0],
  52. TypeName = rootDisk[1],
  53. TotalSize = long.Parse(rootDisk[2]) / 1024,
  54. Used = long.Parse(rootDisk[3]) / 1024,
  55. AvailableFreeSpace = long.Parse(rootDisk[4]) / 1024,
  56. AvailablePercent = decimal.Parse(rootDisk[5].Replace("%", ""))
  57. };
  58. diskInfos.Add(diskInfo);
  59. }
  60. }
  61. else
  62. {
  63. var driv = DriveInfo.GetDrives().Where(u => u.IsReady);
  64. foreach (var item in driv)
  65. {
  66. if (item.DriveType == DriveType.CDRom) continue;
  67. var obj = new DiskInfo()
  68. {
  69. DiskName = item.Name,
  70. TypeName = item.DriveType.ToString(),
  71. TotalSize = item.TotalSize / 1024 / 1024 / 1024,
  72. AvailableFreeSpace = item.AvailableFreeSpace / 1024 / 1024 / 1024,
  73. };
  74. obj.Used = obj.TotalSize - obj.AvailableFreeSpace;
  75. obj.AvailablePercent = decimal.Ceiling(obj.Used / (decimal)obj.TotalSize * 100);
  76. diskInfos.Add(obj);
  77. }
  78. }
  79. return diskInfos;
  80. }
  81. /// <summary>
  82. /// 获取外网IP地址
  83. /// </summary>
  84. /// <returns></returns>
  85. public static string GetIpFromOnline()
  86. {
  87. var url = "http://myip.ipip.net";
  88. var stream = url.GetAsStreamAsync().GetAwaiter().GetResult();
  89. var streamReader = new StreamReader(stream.Stream, stream.Encoding);
  90. var html = streamReader.ReadToEnd();
  91. return html.Replace("当前 IP:", "").Replace("来自于:", "");
  92. }
  93. public static bool IsUnix()
  94. {
  95. return RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  96. }
  97. public static string GetCPURate()
  98. {
  99. string cpuRate;
  100. if (IsUnix())
  101. {
  102. string output = ShellUtil.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
  103. cpuRate = output.Trim();
  104. }
  105. else
  106. {
  107. string output = ShellUtil.Cmd("wmic", "cpu get LoadPercentage");
  108. cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
  109. }
  110. return cpuRate;
  111. }
  112. /// <summary>
  113. /// 获取系统运行时间
  114. /// </summary>
  115. /// <returns></returns>
  116. public static string GetRunTime()
  117. {
  118. string runTime = string.Empty;
  119. if (IsUnix())
  120. {
  121. string output = ShellUtil.Bash("uptime -s").Trim();
  122. runTime = DateTimeUtil.FormatTime((DateTime.Now - output.ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  123. }
  124. else
  125. {
  126. string output = ShellUtil.Cmd("wmic", "OS get LastBootUpTime/Value");
  127. string[] outputArr = output.Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  128. if (outputArr.Length == 2)
  129. runTime = DateTimeUtil.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  130. }
  131. return runTime;
  132. }
  133. }
  134. /// <summary>
  135. /// 内存信息
  136. /// </summary>
  137. public class MemoryMetrics
  138. {
  139. [JsonIgnore]
  140. public double Total { get; set; }
  141. [JsonIgnore]
  142. public double Used { get; set; }
  143. [JsonIgnore]
  144. public double Free { get; set; }
  145. /// <summary>
  146. /// 已用内存
  147. /// </summary>
  148. public string UsedRam { get; set; }
  149. /// <summary>
  150. /// CPU使用率%
  151. /// </summary>
  152. public string CpuRate { get; set; }
  153. /// <summary>
  154. /// 总内存 GB
  155. /// </summary>
  156. public string TotalRam { get; set; }
  157. /// <summary>
  158. /// 内存使用率 %
  159. /// </summary>
  160. public string RamRate { get; set; }
  161. /// <summary>
  162. /// 空闲内存
  163. /// </summary>
  164. public string FreeRam { get; set; }
  165. }
  166. /// <summary>
  167. /// 磁盘信息
  168. /// </summary>
  169. public class DiskInfo
  170. {
  171. /// <summary>
  172. /// 磁盘名
  173. /// </summary>
  174. public string DiskName { get; set; }
  175. /// <summary>
  176. /// 类型名
  177. /// </summary>
  178. public string TypeName { get; set; }
  179. /// <summary>
  180. /// 总剩余
  181. /// </summary>
  182. public long TotalFree { get; set; }
  183. /// <summary>
  184. /// 总量
  185. /// </summary>
  186. public long TotalSize { get; set; }
  187. /// <summary>
  188. /// 已使用
  189. /// </summary>
  190. public long Used { get; set; }
  191. /// <summary>
  192. /// 可使用
  193. /// </summary>
  194. public long AvailableFreeSpace { get; set; }
  195. /// <summary>
  196. /// 使用百分比
  197. /// </summary>
  198. public decimal AvailablePercent { get; set; }
  199. }
  200. public class MemoryMetricsClient
  201. {
  202. /// <summary>
  203. /// windows系统获取内存信息
  204. /// </summary>
  205. /// <returns></returns>
  206. public MemoryMetrics GetWindowsMetrics()
  207. {
  208. string output = ShellUtil.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
  209. var metrics = new MemoryMetrics();
  210. var lines = output.Trim().Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  211. if (lines.Length <= 0) return metrics;
  212. var freeMemoryParts = lines[0].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  213. var totalMemoryParts = lines[1].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  214. metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
  215. metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);//m
  216. metrics.Used = metrics.Total - metrics.Free;
  217. return metrics;
  218. }
  219. /// <summary>
  220. /// Unix系统获取
  221. /// </summary>
  222. /// <returns></returns>
  223. public MemoryMetrics GetUnixMetrics()
  224. {
  225. string output = ShellUtil.Bash("free -m | awk '{print $2,$3,$4,$5,$6}'");
  226. var metrics = new MemoryMetrics();
  227. var lines = output.Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  228. if (lines.Length <= 0) return metrics;
  229. if (lines != null && lines.Length > 0)
  230. {
  231. var memory = lines[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  232. if (memory.Length >= 3)
  233. {
  234. metrics.Total = double.Parse(memory[0]);
  235. metrics.Used = double.Parse(memory[1]);
  236. metrics.Free = double.Parse(memory[2]);//m
  237. }
  238. }
  239. return metrics;
  240. }
  241. }
  242. public class ShellUtil
  243. {
  244. /// <summary>
  245. /// linux 系统命令
  246. /// </summary>
  247. /// <param name="command"></param>
  248. /// <returns></returns>
  249. public static string Bash(string command)
  250. {
  251. var escapedArgs = command.Replace("\"", "\\\"");
  252. var process = new Process()
  253. {
  254. StartInfo = new ProcessStartInfo
  255. {
  256. FileName = "/bin/bash",
  257. Arguments = $"-c \"{escapedArgs}\"",
  258. RedirectStandardOutput = true,
  259. UseShellExecute = false,
  260. CreateNoWindow = true,
  261. }
  262. };
  263. process.Start();
  264. string result = process.StandardOutput.ReadToEnd();
  265. process.WaitForExit();
  266. process.Dispose();
  267. return result;
  268. }
  269. /// <summary>
  270. /// windows系统命令
  271. /// </summary>
  272. /// <param name="fileName"></param>
  273. /// <param name="args"></param>
  274. /// <returns></returns>
  275. public static string Cmd(string fileName, string args)
  276. {
  277. string output = string.Empty;
  278. var info = new ProcessStartInfo();
  279. info.FileName = fileName;
  280. info.Arguments = args;
  281. info.RedirectStandardOutput = true;
  282. using (var process = Process.Start(info))
  283. {
  284. output = process.StandardOutput.ReadToEnd();
  285. }
  286. return output;
  287. }
  288. }