DeviceHelper.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Net.NetworkInformation;
  7. using System.Net;
  8. using System.Runtime.InteropServices;
  9. using System.Security.Policy;
  10. using System.Text;
  11. using System.Text.Json.Nodes;
  12. using System.Text.RegularExpressions;
  13. using System.Threading.Tasks;
  14. using System.Text.Json;
  15. using Microsoft.Extensions.Logging;
  16. using System.IO;
  17. using Microsoft.Extensions.Configuration;
  18. using System.Management;
  19. using System.Net.Http.Json;
  20. namespace TEAMModelOS.SDK
  21. {
  22. public static class DeviceHelper
  23. {
  24. public static async Task<ClientDevice> GetClientInfo(IHttpClientFactory _httpClientFactory, ILogger _logger, IEnumerable<string>? _url)
  25. {
  26. string hostName = $"{Environment.UserName}-{Dns.GetHostName()}";
  27. string os = RuntimeInformation.OSDescription;
  28. //获取当前客户端的服务端口
  29. var _httpClient = _httpClientFactory.CreateClient();
  30. ClientDevice device = new ClientDevice { name =hostName, os= os };
  31. HttpResponseMessage message = await _httpClient.PostAsJsonAsync("https://www.teammodel.cn/core/system-info", new { });
  32. if (message.IsSuccessStatusCode)
  33. {
  34. JsonNode? json = JsonSerializer.Deserialize<JsonNode>(await message.Content.ReadAsStringAsync());
  35. var ip = json?["ip"];
  36. var region = json?["region"];
  37. _logger.LogInformation($"远程地址:{ip}");
  38. _logger.LogInformation($"所属地区:{region}");
  39. device.remote=ip?.ToString();
  40. device.region=region?.ToString();
  41. }
  42. _logger.LogInformation($"计算机名:{hostName}");
  43. _logger.LogInformation($"系统名称:{RuntimeInformation.OSDescription}");
  44. int CpuCoreCount = 0;
  45. long MenemorySize = 0;
  46. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  47. {
  48. // 获取CPU核心数
  49. //int processorCount = Environment.ProcessorCount;
  50. //Console.WriteLine("CPU 核心数: " + processorCount);
  51. using (ManagementClass managementClass = new ManagementClass("Win32_Processor"))
  52. {
  53. using (ManagementObjectCollection managementObjectCollection = managementClass.GetInstances())
  54. {
  55. foreach (ManagementObject managementObject in managementObjectCollection)
  56. {
  57. CpuCoreCount += Convert.ToInt32(managementObject.Properties["NumberOfLogicalProcessors"].Value);
  58. }
  59. }
  60. }
  61. using (ManagementClass mc = new ManagementClass("Win32_ComputerSystem"))
  62. {
  63. using (ManagementObjectCollection moc = mc.GetInstances())
  64. {
  65. foreach (ManagementObject mo in moc)
  66. {
  67. if (mo["TotalPhysicalMemory"]!= null)
  68. {
  69. MenemorySize = Convert.ToInt64(mo["TotalPhysicalMemory"]);
  70. }
  71. }
  72. }
  73. }
  74. }
  75. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  76. {
  77. //int processorCount = Environment.ProcessorCount;
  78. // Console.WriteLine("CPU 核心数: " + processorCount);
  79. string[] cpu_lines = File.ReadAllLines("/proc/cpuinfo");
  80. CpuCoreCount= cpu_lines.Count(line => line.StartsWith("processor", StringComparison.OrdinalIgnoreCase));
  81. string[] mem_lines = File.ReadAllLines("/proc/meminfo");
  82. var match = mem_lines.FirstOrDefault(line => line.StartsWith("MemTotal:"));
  83. if (match != null)
  84. {
  85. var matchResult = Regex.Match(match, @"\d+");
  86. if (matchResult.Success)
  87. {
  88. MenemorySize= long.Parse(matchResult.Value);
  89. }
  90. }
  91. }
  92. else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  93. {
  94. using (var process = new Process())
  95. {
  96. process.StartInfo.FileName = "/usr/sbin/sysctl";
  97. process.StartInfo.Arguments = "-n hw.ncpu";
  98. process.StartInfo.RedirectStandardOutput = true;
  99. process.StartInfo.UseShellExecute = false;
  100. process.Start();
  101. string output = process.StandardOutput.ReadToEnd().Trim();
  102. int coreCount;
  103. if (int.TryParse(output, out coreCount))
  104. {
  105. CpuCoreCount= coreCount;
  106. }
  107. }
  108. using (var process = new Process())
  109. {
  110. process.StartInfo.FileName = "/usr/sbin/sysctl";
  111. process.StartInfo.Arguments = "-n hw.memsize";
  112. process.StartInfo.RedirectStandardOutput = true;
  113. process.StartInfo.UseShellExecute = false;
  114. process.Start();
  115. string output = process.StandardOutput.ReadToEnd().Trim();
  116. long memorySize;
  117. if (long.TryParse(output, out memorySize))
  118. {
  119. MenemorySize= memorySize;
  120. }
  121. }
  122. }
  123. //Console.WriteLine("CPU 核心数: " + CpuCoreCount+",RAM 大小:"+MenemorySize);
  124. _logger.LogInformation($"内存大小:{MenemorySize}");
  125. _logger.LogInformation($"核心数量:{CpuCoreCount}");
  126. device.cpu=CpuCoreCount;
  127. device.ram=MenemorySize;
  128. var nics = NetworkInterface.GetAllNetworkInterfaces();
  129. foreach (var nic in nics)
  130. {
  131. if (nic.OperationalStatus == OperationalStatus.Up)
  132. {
  133. var name = $"{nic.Name}-{nic.Description}";
  134. var mac = nic.GetPhysicalAddress().ToString();
  135. var properties = nic.GetIPProperties();
  136. var unicastAddresses = properties.UnicastAddresses;
  137. foreach (var unicast in unicastAddresses)
  138. {
  139. if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  140. {
  141. var ip = unicast.Address.ToString();
  142. Network network = new Network() { mac=mac, ip=ip, name= name };
  143. if (!string.IsNullOrWhiteSpace(mac.ToString()) && !mac.Equals("000000000000"))
  144. {
  145. device.networks.Add(network);
  146. _logger.LogInformation($"网卡名称: {name}");
  147. _logger.LogInformation($"网卡地址: {mac}");
  148. _logger.LogInformation($"内网地址: {ip}");
  149. }
  150. }
  151. }
  152. }
  153. }
  154. if (_url!.IsNotEmpty())
  155. {
  156. List<int> ports = new List<int>();
  157. foreach (var url in _url)
  158. {
  159. Uri uri = new Uri(url);
  160. ports.Add(uri.Port);
  161. }
  162. device.port= string.Join(",", ports);
  163. _logger.LogInformation($"占用端口: {device.port}");
  164. }
  165. else {
  166. throw new Exception("未获取到端口信息!");
  167. }
  168. string hashData = ShaHashHelper.GetSHA1($"{device.name}-{device.remote}-{device.port}-{device.os}-{string.Join(",", device.networks.Select(x => $"{x.mac}-{x.ip}"))}");
  169. device.deviceId=hashData;
  170. return device;
  171. }
  172. }
  173. }