using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.NetworkInformation; using System.Net; using System.Runtime.InteropServices; using System.Security.Policy; using System.Text; using System.Text.Json.Nodes; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Text.Json; using Microsoft.Extensions.Logging; using System.IO; using Microsoft.Extensions.Configuration; using System.Management; using System.Net.Http.Json; namespace TEAMModelOS.SDK { public static class DeviceHelper { public static async Task GetClientInfo(IHttpClientFactory _httpClientFactory, ILogger _logger, IEnumerable? _url) { string hostName = $"{Environment.UserName}-{Dns.GetHostName()}"; string os = RuntimeInformation.OSDescription; //获取当前客户端的服务端口 var _httpClient = _httpClientFactory.CreateClient(); ClientDevice device = new ClientDevice { name =hostName, os= os }; HttpResponseMessage message = await _httpClient.PostAsJsonAsync("https://www.teammodel.cn/core/system-info", new { }); if (message.IsSuccessStatusCode) { JsonNode? json = JsonSerializer.Deserialize(await message.Content.ReadAsStringAsync()); var ip = json?["ip"]; var region = json?["region"]; _logger.LogInformation($"远程地址:{ip}"); _logger.LogInformation($"所属地区:{region}"); device.remote=ip?.ToString(); device.region=region?.ToString(); } _logger.LogInformation($"计算机名:{hostName}"); _logger.LogInformation($"系统名称:{RuntimeInformation.OSDescription}"); int CpuCoreCount = 0; long MenemorySize = 0; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // 获取CPU核心数 //int processorCount = Environment.ProcessorCount; //Console.WriteLine("CPU 核心数: " + processorCount); using (ManagementClass managementClass = new ManagementClass("Win32_Processor")) { using (ManagementObjectCollection managementObjectCollection = managementClass.GetInstances()) { foreach (ManagementObject managementObject in managementObjectCollection) { CpuCoreCount += Convert.ToInt32(managementObject.Properties["NumberOfLogicalProcessors"].Value); } } } using (ManagementClass mc = new ManagementClass("Win32_ComputerSystem")) { using (ManagementObjectCollection moc = mc.GetInstances()) { foreach (ManagementObject mo in moc) { if (mo["TotalPhysicalMemory"]!= null) { MenemorySize = Convert.ToInt64(mo["TotalPhysicalMemory"]); } } } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { //int processorCount = Environment.ProcessorCount; // Console.WriteLine("CPU 核心数: " + processorCount); string[] cpu_lines = File.ReadAllLines("/proc/cpuinfo"); CpuCoreCount= cpu_lines.Count(line => line.StartsWith("processor", StringComparison.OrdinalIgnoreCase)); string[] mem_lines = File.ReadAllLines("/proc/meminfo"); var match = mem_lines.FirstOrDefault(line => line.StartsWith("MemTotal:")); if (match != null) { var matchResult = Regex.Match(match, @"\d+"); if (matchResult.Success) { MenemorySize= long.Parse(matchResult.Value); } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { using (var process = new Process()) { process.StartInfo.FileName = "/usr/sbin/sysctl"; process.StartInfo.Arguments = "-n hw.ncpu"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start(); string output = process.StandardOutput.ReadToEnd().Trim(); int coreCount; if (int.TryParse(output, out coreCount)) { CpuCoreCount= coreCount; } } using (var process = new Process()) { process.StartInfo.FileName = "/usr/sbin/sysctl"; process.StartInfo.Arguments = "-n hw.memsize"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start(); string output = process.StandardOutput.ReadToEnd().Trim(); long memorySize; if (long.TryParse(output, out memorySize)) { MenemorySize= memorySize; } } } //Console.WriteLine("CPU 核心数: " + CpuCoreCount+",RAM 大小:"+MenemorySize); _logger.LogInformation($"内存大小:{MenemorySize}"); _logger.LogInformation($"核心数量:{CpuCoreCount}"); device.cpu=CpuCoreCount; device.ram=MenemorySize; var nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (var nic in nics) { if (nic.OperationalStatus == OperationalStatus.Up) { var name = $"{nic.Name}-{nic.Description}"; var mac = nic.GetPhysicalAddress().ToString(); var properties = nic.GetIPProperties(); var unicastAddresses = properties.UnicastAddresses; foreach (var unicast in unicastAddresses) { if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { var ip = unicast.Address.ToString(); Network network = new Network() { mac=mac, ip=ip, name= name }; if (!string.IsNullOrWhiteSpace(mac.ToString()) && !mac.Equals("000000000000")) { device.networks.Add(network); _logger.LogInformation($"网卡名称: {name}"); _logger.LogInformation($"网卡地址: {mac}"); _logger.LogInformation($"内网地址: {ip}"); } } } } } if (_url!.IsNotEmpty()) { List ports = new List(); foreach (var url in _url) { Uri uri = new Uri(url); ports.Add(uri.Port); } device.port= string.Join(",", ports); _logger.LogInformation($"占用端口: {device.port}"); } else { throw new Exception("未获取到端口信息!"); } string hashData = ShaHashHelper.GetSHA1($"{device.name}-{device.remote}-{device.port}-{device.os}-{string.Join(",", device.networks.Select(x => $"{x.mac}-{x.ip}"))}"); device.deviceId=hashData; return device; } } }