ComputerUtil.cs 11 KB

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