123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436 |
- using IES.ExamServer.Helpers;
- using Microsoft.Extensions.Caching.Memory;
- using System.Diagnostics;
- using System.Net.NetworkInformation;
- using System.Net;
- using System.Runtime.InteropServices;
- using System.Text.Json;
- using System.Text.Json.Nodes;
- using System.Text.RegularExpressions;
- using System.Management;
- namespace IES.ExamServer.Services
- {
- public static class IndexService
- {
- public static ServerDevice GetServerDevice( string remote,string region, IEnumerable<string>? _url)
- {
- string hostName = $"{Environment.UserName}-{Dns.GetHostName()}";
- string os = RuntimeInformation.OSDescription;
- //获取当前客户端的服务端口
- string currentUserName = Environment.UserName;
-
- ServerDevice device = new ServerDevice { name =hostName, userName=currentUserName, os= os,region=region,remote=remote };
- 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"]);
- }
- }
- }
- }
- if (Environment.Is64BitOperatingSystem)
- {
- device.bit="64";
- }
- else
- {
- device.bit="32";
- }
- ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name, MaxClockSpeed FROM Win32_Processor");
- foreach (ManagementObject mo in searcher.Get())
- {
- string? cpuName = mo["Name"].ToString();
- string? clockSpeed = mo["MaxClockSpeed"].ToString();
- //Console.WriteLine($"CPU 名称: {cpuName}");
- //Console.WriteLine($"CPU 主频: {clockSpeed} MHz");
- device.cpuInfos.Add(new CPUInfo { name = cpuName, hz = clockSpeed });
- }
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
- {
- //int processorCount = Environment.ProcessorCount;
- // Console.WriteLine("CPU 核心数: " + processorCount);
- try {
- string cpuInfo = File.ReadAllText("/proc/cpuinfo");
- string[] cpu_lines = cpuInfo.Split('\n');
-
- CpuCoreCount= cpu_lines.Count(line => line.StartsWith("processor", StringComparison.OrdinalIgnoreCase));
- string? cpuNameLine = cpuInfo.Split('\n').FirstOrDefault(line => line.StartsWith("model name"));
- string? clockSpeedLine = cpuInfo.Split('\n').FirstOrDefault(line => line.StartsWith("cpu MHz"));
- string cpuName = string.Empty;
- string clockSpeed = string.Empty;
- if (cpuNameLine!= null)
- {
- cpuName = cpuNameLine.Split(':').Last().Trim();
- }
- if (clockSpeedLine!= null)
- {
- clockSpeed = clockSpeedLine.Split(':').Last().Trim();
- }
- device.cpuInfos.Add(new CPUInfo { name = cpuName, hz = clockSpeed });
- } catch (Exception ex)
- {
-
- }
- 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))
- {
- try {
- 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;
- }
- }
- }
- catch (Exception ex) { }
- try
- {
- 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;
- }
- }
- }
- catch (Exception ex) { }
- try
- {
- using (var process = new Process())
- {
- process.StartInfo.FileName = "/usr/sbin/sysctl";
- process.StartInfo.Arguments = "-n machdep.cpu.brand_string";
- process.StartInfo.RedirectStandardOutput = true;
- process.StartInfo.UseShellExecute = false;
- process.Start();
- string cpuName = process.StandardOutput.ReadToEnd().Trim();
- process.StartInfo.FileName = "/usr/sbin/sysctl";
- process.StartInfo.Arguments = "-n hw.cpu.frequency";
- process.StartInfo.RedirectStandardOutput = true;
- process.StartInfo.UseShellExecute = false;
- process.Start();
- string clockSpeed = process.StandardOutput.ReadToEnd().Trim();
- //Console.WriteLine($"CPU 名称: {cpuName}");
- //Console.WriteLine($"CPU 主频: {clockSpeed} Hz");
- device.cpuInfos.Add(new CPUInfo { name = cpuName, hz = clockSpeed });
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"出现错误: {ex.Message}");
- }
- if (Environment.Is64BitOperatingSystem)
- {
- device.bit="64";
- }
- else
- {
- device.bit="32";
- }
- }
- if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
- {
- device.arch="ARM64";
- }
- else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm)
- {
- device.arch="ARM32";
- }
- else if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
- {
- device.arch="X64";
- }
- else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
- {
- device.arch="X86";
- }
- else
- {
- device.arch=$"未知({device.arch})";
- }
- //Console.WriteLine("CPU 核心数: " + CpuCoreCount+",RAM 大小:"+MenemorySize);
- 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);
- }
- }
- }
- }
- }
- 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);
- }
- 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;
- }
- /// <summary>
- /// 初始化设备
- /// </summary>
- /// <param name="httpContext"></param>
- /// <param name="fingerprint">浏览器指纹</param>
- /// <param name="IP"></param>
- /// <param name="device_timeSpan"></param>
- /// <param name="_azureRedis"></param>
- /// <returns></returns>
- public static string GetDeviceInit(this HttpContext httpContext, string fingerprint, string IP, IMemoryCache _memoryCache)
- {
- string device = $"{fingerprint}-{IP}";
- List<string> cookieString = new List<string>();
- var cookie = httpContext.Request.Cookies;
- int status = 1;
- if (cookie != null)
- {
- ///设备是否存在
- foreach (var ck in cookie)
- {
- if (ck.Key.Equals("device"))
- {
- if (device.Contains("-") && device.Contains("."))
- {
- //如果匹配的是fingerprint-IP 则是已经存在的。
- if (ck.Value.Equals(device))
- {
- //redis如果存在则
- _memoryCache.TryGetValue<JsonNode>($"device:{fingerprint}:{IP}", out JsonNode device_exist);
- // 返回的则应该是ck.Value=exist_device_exist的数据
- if (device_exist!=null)
- {
- if (!string.IsNullOrWhiteSpace($"{device_exist["device"]}"))
- {
- //0是代表指纹和IP匹配,正常返回的
- status = 1;
- }
- else
- {
- //需要新建 fingerprint-IP
- status = 1;
- }
- }
- else
- {
- status = 1;
- }
- }
- else
- {
- string ck_ip = ck.Value.Split("-")[1];
- if (ck_ip.Equals(IP))
- {
- //传入的指纹和cookie的不一致,仍然以cookie的为准。
- status = 1;
- fingerprint = ck.Value.Split("-").First();
- device = ck.Value;
- }
- }
- }
- else
- {
- //如果匹配的是fingerprint则是一个新的设备。
- if (ck.Value.Equals(fingerprint))
- {
- //检查设备是否被占用
- //var device_exist = _azureRedis.GetRedisClient(8).HashExists($"device:{fingerprint}", IP);
- _memoryCache.TryGetValue<JsonNode>($"device:{fingerprint}:{IP}", out JsonNode device_exist);
- if (device_exist!=null)
- {
- //需要新建 sha1(fingerprint+uuid)-IP
- status = 2;
- }
- else
- {
- //0是代表指纹和IP匹配,正常返回的
- status = 1;
- }
- }
- else
- {
- //匹配的都不是,新设备。
- status = 1;
- }
- }
- }
- else
- {
- cookieString.Add($"{ck.Key}{ck.Value}");
- }
- }
- }
- /*
- httpContext.Request.Headers.TryGetValue("accept-language", out var accept_language);
- httpContext.Request.Headers.TryGetValue("sec-ch-ua", out var chua);
- httpContext.Request.Headers.TryGetValue("sec-ch-ua-platform", out var platform);
- httpContext.Request.Headers.TryGetValue("user-agent", out var useragent);
- httpContext.Request.Headers.TryGetValue("accept", out var accept);
- httpContext.Request.Headers.TryGetValue("accept-encoding", out var accept_encoding);
- device = ShaHashHelper.GetSHA1($"{IP}{accept_language}{chua}{platform}{useragent}{accept}{accept_encoding}{string.Join("", cookieString)}");
- */
- if (status == 2)
- {
- fingerprint = ShaHashHelper.GetSHA1(fingerprint + Guid.NewGuid().ToString());
- device = $"{fingerprint}-{IP}";
- }
- //else if (status == 1)
- //{
- // device = $"{fingerprint}-{IP}";
- //}
- //await _azureRedis.GetRedisClient(8).HashSetAsync($"device:{fingerprint}", IP, new { device }.ToJsonString());
- //await _azureRedis.GetRedisClient(8).KeyExpireAsync($"device:{fingerprint}", device_timeSpan);
- _memoryCache.Set($"device:{fingerprint}:{IP}", new { device });
- httpContext.Response.Cookies.Append("device", device, new CookieOptions { HttpOnly = true, MaxAge = new TimeSpan(24 * 7, 0, 0) });
- return device;
- }
- }
- public class ServerDevice
- {
-
- /// <summary>
- /// 设备id
- /// </summary>
- public string? deviceId { get; set; }
- public string? userName { get; set; }
- /// <summary>
- /// 机器名
- /// </summary>
- public string? name { get; set; }
- /// <summary>
- /// 操作系统
- /// </summary>
- public string? os { get; set; }
- /// <summary>
- /// 操作系统位数 64位/32位
- /// </summary>
- public string? bit { get; set; }
- /// <summary>
- /// 操作系统指令架构 x86/x64, arm arm64 其他
- /// </summary>
- public string? arch { get; set; }
- /// <summary>
- /// CPU核心数量
- /// </summary>
- public int cpu { get; set; }
- public List<CPUInfo> cpuInfos { get; set; } = new List<CPUInfo>();
- /// <summary>
- /// 内存大小
- /// </summary>
- public long ram { get; set;}
- /// <summary>
- /// 远程ip
- /// </summary>
- public string? remote { get; set; }
- /// <summary>
- /// 端口,可能有多个端口
- /// </summary>
- public string? port { get; set; }
- /// <summary>
- /// 地区
- /// </summary>
- public string? region { get; set; }
- /// <summary>
- /// 网卡 IP信息
- /// </summary>
- public List<Network> networks { get; set; } = new List<Network>();
- }
- public class CPUInfo
- {
- public string? name { get; set; }
- public string? hz { get; set; }
- }
- public class Network
- {
- public string? name { get; set; }
- public string? mac { get; set; }
- public string? ip { get; set; }
- }
- }
|