ComputerUtil.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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;
  20. if (IsMacOS())
  21. {
  22. memoryMetrics = client.GetMacOSMetrics();
  23. }
  24. else if (IsUnix())
  25. {
  26. memoryMetrics = client.GetUnixMetrics();
  27. }
  28. else
  29. {
  30. memoryMetrics = client.GetWindowsMetrics();
  31. }
  32. memoryMetrics.FreeRam = Math.Round(memoryMetrics.Free / 1024, 2) + "GB";
  33. memoryMetrics.UsedRam = Math.Round(memoryMetrics.Used / 1024, 2) + "GB";
  34. memoryMetrics.TotalRam = Math.Round(memoryMetrics.Total / 1024, 2) + "GB";
  35. memoryMetrics.RamRate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total).ToString() + "%";
  36. memoryMetrics.CpuRate = Math.Ceiling(GetCPURate().ParseToDouble()) + "%";
  37. return memoryMetrics;
  38. }
  39. /// <summary>
  40. /// 获取正确的操作系统版本(Linux获取发行版本)
  41. /// </summary>
  42. /// <returns></returns>
  43. public static String GetOSInfo()
  44. {
  45. string opeartion = string.Empty;
  46. if (IsMacOS())
  47. {
  48. var output = ShellHelper.Bash("sw_vers | awk 'NR<=2{printf \"%s \", $NF}'");
  49. if (output != null)
  50. {
  51. opeartion = output.Replace("%", string.Empty);
  52. }
  53. }
  54. else if (IsUnix())
  55. {
  56. var output = ShellHelper.Bash("awk -F= '/^VERSION_ID/ {print $2}' /etc/os-release | tr -d '\"'");
  57. opeartion = output ?? string.Empty;
  58. }
  59. else
  60. {
  61. opeartion = RuntimeInformation.OSDescription;
  62. }
  63. return opeartion;
  64. }
  65. /// <summary>
  66. /// 磁盘信息
  67. /// </summary>
  68. /// <returns></returns>
  69. public static List<DiskInfo> GetDiskInfos()
  70. {
  71. var diskInfos = new List<DiskInfo>();
  72. if (IsMacOS())
  73. {
  74. var output = ShellHelper.Bash(@"df -m | awk '/^\/dev\/disk/ {print $1,$2,$3,$4,$5}'");
  75. var disks = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
  76. if (disks.Length < 1) return diskInfos;
  77. foreach (var item in disks)
  78. {
  79. var disk = item.Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  80. if (disk == null || disk.Length < 5)
  81. continue;
  82. var diskInfo = new DiskInfo()
  83. {
  84. DiskName = disk[0],
  85. TypeName = ShellHelper.Bash("diskutil info " + disk[0] + " | awk '/File System Personality/ {print $4}'").Replace("\n",string.Empty),
  86. TotalSize = long.Parse(disk[1]) / 1024,
  87. Used = long.Parse(disk[2]) / 1024,
  88. AvailableFreeSpace = long.Parse(disk[3]) / 1024,
  89. AvailablePercent = decimal.Parse(disk[4].Replace("%", ""))
  90. };
  91. diskInfos.Add(diskInfo);
  92. }
  93. }
  94. else if (IsUnix())
  95. {
  96. var output = ShellHelper.Bash(@"df -mT | awk '/^\/dev\/(sd|vd|xvd|nvme|sda|vda)/ {print $1,$2,$3,$4,$5,$6}'");
  97. var disks = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
  98. if (disks.Length < 1) return diskInfos;
  99. //var rootDisk = disks[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  100. //if (rootDisk == null || rootDisk.Length < 1)
  101. // return diskInfos;
  102. foreach (var item in disks)
  103. {
  104. var disk = item.Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  105. if (disk == null || disk.Length < 6)
  106. continue;
  107. var diskInfo = new DiskInfo()
  108. {
  109. DiskName = disk[0],
  110. TypeName = disk[1],
  111. TotalSize = long.Parse(disk[2]) / 1024,
  112. Used = long.Parse(disk[3]) / 1024,
  113. AvailableFreeSpace = long.Parse(disk[4]) / 1024,
  114. AvailablePercent = decimal.Parse(disk[5].Replace("%", ""))
  115. };
  116. diskInfos.Add(diskInfo);
  117. }
  118. }
  119. else
  120. {
  121. var driv = DriveInfo.GetDrives().Where(u => u.IsReady);
  122. foreach (var item in driv)
  123. {
  124. if (item.DriveType == DriveType.CDRom) continue;
  125. var obj = new DiskInfo()
  126. {
  127. DiskName = item.Name,
  128. TypeName = item.DriveType.ToString(),
  129. TotalSize = item.TotalSize / 1024 / 1024 / 1024,
  130. AvailableFreeSpace = item.AvailableFreeSpace / 1024 / 1024 / 1024,
  131. };
  132. obj.Used = obj.TotalSize - obj.AvailableFreeSpace;
  133. obj.AvailablePercent = decimal.Ceiling(obj.Used / (decimal)obj.TotalSize * 100);
  134. diskInfos.Add(obj);
  135. }
  136. }
  137. return diskInfos;
  138. }
  139. /// <summary>
  140. /// 获取外网IP地址
  141. /// </summary>
  142. /// <returns></returns>
  143. public static string GetIpFromOnline()
  144. {
  145. var url = "http://myip.ipip.net";
  146. var stream = url.GetAsStreamAsync().GetAwaiter().GetResult();
  147. var streamReader = new StreamReader(stream.Stream, stream.Encoding);
  148. var html = streamReader.ReadToEnd();
  149. return !html.Contains("当前 IP:") ? "未知" : html.Replace("当前 IP:", "").Replace("来自于:", "");
  150. }
  151. public static bool IsUnix()
  152. {
  153. return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  154. }
  155. public static bool IsMacOS()
  156. {
  157. return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
  158. }
  159. public static string GetCPURate()
  160. {
  161. string cpuRate;
  162. if (IsMacOS())
  163. {
  164. string output = ShellUtil.Bash("top -l 1 | grep \"CPU usage\" | awk '{print $3 + $5}'");
  165. cpuRate = output.Trim();
  166. }
  167. else if (IsUnix())
  168. {
  169. string output = ShellUtil.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
  170. cpuRate = output.Trim();
  171. }
  172. else
  173. {
  174. string output = ShellUtil.Cmd("wmic", "cpu get LoadPercentage");
  175. cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
  176. }
  177. return cpuRate;
  178. }
  179. /// <summary>
  180. /// 获取系统运行时间
  181. /// </summary>
  182. /// <returns></returns>
  183. public static string GetRunTime()
  184. {
  185. string runTime = string.Empty;
  186. if (IsMacOS())
  187. {
  188. //macOS 获取系统启动时间:
  189. //sysctl -n kern.boottime | awk '{print $4}' | tr -d ','
  190. //返回:1705379131
  191. //使用date格式化即可
  192. string output = ShellUtil.Bash("date -r $(sysctl -n kern.boottime | awk '{print $4}' | tr -d ',') +\"%Y-%m-%d %H:%M:%S\"").Trim();
  193. runTime = DateTimeUtil.FormatTime((DateTime.Now - output.ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  194. }
  195. else if (IsUnix())
  196. {
  197. string output = ShellUtil.Bash("uptime -s").Trim();
  198. runTime = DateTimeUtil.FormatTime((DateTime.Now - output.ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  199. }
  200. else
  201. {
  202. string output = ShellUtil.Cmd("wmic", "OS get LastBootUpTime/Value");
  203. string[] outputArr = output.Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  204. if (outputArr.Length == 2)
  205. runTime = DateTimeUtil.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
  206. }
  207. return runTime;
  208. }
  209. }
  210. /// <summary>
  211. /// 内存信息
  212. /// </summary>
  213. public class MemoryMetrics
  214. {
  215. [Newtonsoft.Json.JsonIgnore]
  216. [System.Text.Json.Serialization.JsonIgnore]
  217. public double Total { get; set; }
  218. [Newtonsoft.Json.JsonIgnore]
  219. [System.Text.Json.Serialization.JsonIgnore]
  220. public double Used { get; set; }
  221. [Newtonsoft.Json.JsonIgnore]
  222. [System.Text.Json.Serialization.JsonIgnore]
  223. public double Free { get; set; }
  224. /// <summary>
  225. /// 已用内存
  226. /// </summary>
  227. public string UsedRam { get; set; }
  228. /// <summary>
  229. /// CPU使用率%
  230. /// </summary>
  231. public string CpuRate { get; set; }
  232. /// <summary>
  233. /// 总内存 GB
  234. /// </summary>
  235. public string TotalRam { get; set; }
  236. /// <summary>
  237. /// 内存使用率 %
  238. /// </summary>
  239. public string RamRate { get; set; }
  240. /// <summary>
  241. /// 空闲内存
  242. /// </summary>
  243. public string FreeRam { get; set; }
  244. }
  245. /// <summary>
  246. /// 磁盘信息
  247. /// </summary>
  248. public class DiskInfo
  249. {
  250. /// <summary>
  251. /// 磁盘名
  252. /// </summary>
  253. public string DiskName { get; set; }
  254. /// <summary>
  255. /// 类型名
  256. /// </summary>
  257. public string TypeName { get; set; }
  258. /// <summary>
  259. /// 总剩余
  260. /// </summary>
  261. public long TotalFree { get; set; }
  262. /// <summary>
  263. /// 总量
  264. /// </summary>
  265. public long TotalSize { get; set; }
  266. /// <summary>
  267. /// 已使用
  268. /// </summary>
  269. public long Used { get; set; }
  270. /// <summary>
  271. /// 可使用
  272. /// </summary>
  273. public long AvailableFreeSpace { get; set; }
  274. /// <summary>
  275. /// 使用百分比
  276. /// </summary>
  277. public decimal AvailablePercent { get; set; }
  278. }
  279. public class MemoryMetricsClient
  280. {
  281. /// <summary>
  282. /// windows系统获取内存信息
  283. /// </summary>
  284. /// <returns></returns>
  285. public MemoryMetrics GetWindowsMetrics()
  286. {
  287. string output = ShellUtil.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
  288. var metrics = new MemoryMetrics();
  289. var lines = output.Trim().Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  290. if (lines.Length <= 0) return metrics;
  291. var freeMemoryParts = lines[0].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  292. var totalMemoryParts = lines[1].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
  293. metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
  294. metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);//m
  295. metrics.Used = metrics.Total - metrics.Free;
  296. return metrics;
  297. }
  298. /// <summary>
  299. /// Unix系统获取
  300. /// </summary>
  301. /// <returns></returns>
  302. public MemoryMetrics GetUnixMetrics()
  303. {
  304. string output = ShellUtil.Bash("free -m | awk '{print $2,$3,$4,$5,$6}'");
  305. var metrics = new MemoryMetrics();
  306. var lines = output.Split('\n', (char)StringSplitOptions.RemoveEmptyEntries);
  307. if (lines.Length <= 0) return metrics;
  308. if (lines != null && lines.Length > 0)
  309. {
  310. var memory = lines[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
  311. if (memory.Length >= 3)
  312. {
  313. metrics.Total = double.Parse(memory[0]);
  314. metrics.Used = double.Parse(memory[1]);
  315. metrics.Free = double.Parse(memory[2]);//m
  316. }
  317. }
  318. return metrics;
  319. }
  320. /// <summary>
  321. /// macOS系统获取
  322. /// </summary>
  323. /// <returns></returns>
  324. public MemoryMetrics GetMacOSMetrics()
  325. {
  326. var metrics = new MemoryMetrics();
  327. //物理内存大小
  328. var total = ShellUtil.Bash("sysctl -n hw.memsize | awk '{printf \"%.2f\", $1/1024/1024}'");
  329. metrics.Total = float.Parse(total.Replace("%", string.Empty));
  330. //TODO:占用内存,检查效率
  331. var free = ShellUtil.Bash("top -l 1 -s 0 | awk '/PhysMem/ {print $6+$8}'");
  332. metrics.Free = float.Parse(free);
  333. metrics.Used = metrics.Total - metrics.Free;
  334. return metrics;
  335. }
  336. }
  337. public class ShellUtil
  338. {
  339. /// <summary>
  340. /// linux 系统命令
  341. /// </summary>
  342. /// <param name="command"></param>
  343. /// <returns></returns>
  344. public static string Bash(string command)
  345. {
  346. var escapedArgs = command.Replace("\"", "\\\"");
  347. var process = new Process()
  348. {
  349. StartInfo = new ProcessStartInfo
  350. {
  351. FileName = "/bin/bash",
  352. Arguments = $"-c \"{escapedArgs}\"",
  353. RedirectStandardOutput = true,
  354. UseShellExecute = false,
  355. CreateNoWindow = true,
  356. }
  357. };
  358. process.Start();
  359. string result = process.StandardOutput.ReadToEnd();
  360. process.WaitForExit();
  361. process.Dispose();
  362. return result;
  363. }
  364. /// <summary>
  365. /// windows系统命令
  366. /// </summary>
  367. /// <param name="fileName"></param>
  368. /// <param name="args"></param>
  369. /// <returns></returns>
  370. public static string Cmd(string fileName, string args)
  371. {
  372. string output = string.Empty;
  373. var info = new ProcessStartInfo();
  374. info.FileName = fileName;
  375. info.Arguments = args;
  376. info.RedirectStandardOutput = true;
  377. using (var process = Process.Start(info))
  378. {
  379. output = process.StandardOutput.ReadToEnd();
  380. }
  381. return output;
  382. }
  383. }
  384. public class ShellHelper
  385. {
  386. /// <summary>
  387. /// Linux 系统命令
  388. /// </summary>
  389. /// <param name="command"></param>
  390. /// <returns></returns>
  391. public static string Bash(string command)
  392. {
  393. var escapedArgs = command.Replace("\"", "\\\"");
  394. var process = new Process()
  395. {
  396. StartInfo = new ProcessStartInfo
  397. {
  398. FileName = "/bin/bash",
  399. Arguments = $"-c \"{escapedArgs}\"",
  400. RedirectStandardOutput = true,
  401. UseShellExecute = false,
  402. CreateNoWindow = true,
  403. }
  404. };
  405. process.Start();
  406. string result = process.StandardOutput.ReadToEnd();
  407. process.WaitForExit();
  408. process.Dispose();
  409. return result;
  410. }
  411. /// <summary>
  412. /// Windows 系统命令
  413. /// </summary>
  414. /// <param name="fileName"></param>
  415. /// <param name="args"></param>
  416. /// <returns></returns>
  417. public static string Cmd(string fileName, string args)
  418. {
  419. string output = string.Empty;
  420. var info = new ProcessStartInfo();
  421. info.FileName = fileName;
  422. info.Arguments = args;
  423. info.RedirectStandardOutput = true;
  424. using (var process = Process.Start(info))
  425. {
  426. output = process.StandardOutput.ReadToEnd();
  427. }
  428. return output;
  429. }
  430. }