123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174 |
- 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<ClientDevice> GetClientInfo(IHttpClientFactory _httpClientFactory, ILogger _logger, IEnumerable<string>? _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<JsonNode>(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<int> ports = new List<int>();
- 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;
- }
- }
- }
|