ComputerUtil.cs 9.0 KB

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