1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
| using System; using System.Diagnostics; using System.Net.NetworkInformation; using System.Threading; using System.Runtime.InteropServices; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Net; using System.Linq;
namespace NetIdleShutdown { public class NetIdleShutdown : IDisposable { #region 配置类 public class AppConfig { public int MaxNoNetMinutes = 3; public int PingTimeoutMs = 1500; public int HttpTimeoutMs = 5000; public int CheckIntervalSeconds = 60; public int UserIdleThresholdSeconds = 60; public List<string> PingTargets; public List<string> HttpTargets; public AppConfig() { PingTargets = new List<string> { "223.5.5.5", "119.29.29.29", "180.76.76.76", "1.1.1.1", "8.8.8.8", "114.114.114.114", "208.67.222.222", "9.9.9.9" }; HttpTargets = new List<string> { "http://connect.rom.miui.com/generate_204", "http://connectivitycheck.gstatic.com/generate_204", "http://www.gstatic.com/generate_204", "http://www.msftncsi.com/ncsi.txt", "http://captive.apple.com/hotspot-detect.html", "http://connectivitycheck.platform.hicloud.com/generate_204" }; } } #endregion
#region Windows API声明 [DllImport("user32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); [StructLayout(LayoutKind.Sequential)] private struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } #endregion
#region 私有字段 private readonly AppConfig _config; private int _noNetCounter = 0; private bool _isRunning = true; private readonly object _counterLock = new object(); #endregion
#region 构造函数 public NetIdleShutdown(AppConfig config = null) { _config = config ?? new AppConfig(); Console.WriteLine("[SYSTEM] 程序配置已加载"); Console.WriteLine("[SYSTEM] 无网络关机阈值: " + _config.MaxNoNetMinutes + " 分钟"); Console.WriteLine("[SYSTEM] 检测间隔: " + _config.CheckIntervalSeconds + " 秒"); Console.WriteLine("[SYSTEM] 用户空闲阈值: " + _config.UserIdleThresholdSeconds + " 秒"); } #endregion
#region 主程序入口 public void Run() { try { PrintBanner(); while (_isRunning) { PerformCheckCycle(); for (int i = 0; i < _config.CheckIntervalSeconds && _isRunning; i++) { Thread.Sleep(1000); } } } catch (Exception ex) { LogError("程序运行异常", ex); throw; } } public void Stop() { _isRunning = false; LogInfo("程序已收到停止指令"); } #endregion
#region 检测周期 private void PerformCheckCycle() { var timestamp = DateTime.Now; LogInfo("开始第 " + (_noNetCounter + 1) + " 次检测"); bool isOnline = CheckConnectivity(); if (isOnline) { HandleOnlineStatus(timestamp); } else { HandleOfflineStatus(timestamp); } } private void HandleOnlineStatus(DateTime timestamp) { lock (_counterLock) { if (_noNetCounter > 0) { LogInfo("网络恢复正常,无网络计数器已重置"); _noNetCounter = 0; } } LogInfo("网络状态: 在线"); } private void HandleOfflineStatus(DateTime timestamp) { bool hasUserActivity = HasUserInputActivity(); if (hasUserActivity) { lock (_counterLock) { if (_noNetCounter > 0) { LogInfo("检测到用户活动,无网络计数器已重置"); _noNetCounter = 0; } } LogInfo("网络状态: 离线 (用户活动中,不计数)"); } else { lock (_counterLock) { _noNetCounter++; } LogInfo("网络状态: 离线"); LogInfo("无网络计数器: " + _noNetCounter + "/" + _config.MaxNoNetMinutes); if (_noNetCounter >= _config.MaxNoNetMinutes) { ExecuteShutdown(); } } } #endregion
#region 网络检测 private bool CheckConnectivity() { LogInfo("开始网络连通性检测"); bool pingSuccess = PerformPingTestsParallel(); if (!pingSuccess) { LogInfo("Ping检测结果: 全部失败,直接判定为网络离线"); return false; } LogInfo("Ping检测结果: 至少有一个成功,开始HTTP检测"); bool httpSuccess = PerformHttpTestsParallel(); bool finalResult = pingSuccess && httpSuccess; if (finalResult) { LogInfo("网络检测最终结果: 在线 (Ping和HTTP检测均通过)"); } else { LogInfo("网络检测最终结果: 离线 (Ping: " + (pingSuccess ? "成功" : "失败") + ", HTTP: " + (httpSuccess ? "成功" : "失败") + ")"); } return finalResult; } private bool PerformPingTestsParallel() { LogInfo("开始并行Ping测试 (目标数: " + _config.PingTargets.Count + ")"); int successCount = 0; var results = new ConcurrentDictionary<string, bool>(); var tasks = new List<Thread>(); foreach (var target in _config.PingTargets) { var thread = new Thread(() => { bool result = PingHostFast(target); results[target] = result; if (result) { Interlocked.Increment(ref successCount); } }); thread.Start(); tasks.Add(thread); } foreach (var thread in tasks) { if (!thread.Join(_config.PingTimeoutMs)) { thread.Abort(); } } var resultBuilder = new StringBuilder(); resultBuilder.AppendLine("PING检测详细结果:"); foreach (var target in _config.PingTargets) { bool result; if (results.TryGetValue(target, out result)) { string status = result ? "成功" : "失败"; resultBuilder.AppendLine(" " + target.PadRight(15) + " => " + status); } else { resultBuilder.AppendLine(" " + target.PadRight(15) + " => 超时"); } } LogInfo(resultBuilder.ToString()); LogInfo("PING检测统计: 成功 " + successCount + "/" + _config.PingTargets.Count); return successCount > 0; } private bool PerformHttpTestsParallel() { LogInfo("开始并行HTTP测试 (目标数: " + _config.HttpTargets.Count + ")"); int successCount = 0; var results = new ConcurrentDictionary<string, bool>(); var tasks = new List<Thread>(); foreach (var url in _config.HttpTargets) { var thread = new Thread(() => { bool result = TestHttpConnectionFast(url); results[url] = result; if (result) { Interlocked.Increment(ref successCount); } }); thread.Start(); tasks.Add(thread); } foreach (var thread in tasks) { if (!thread.Join(_config.HttpTimeoutMs)) { thread.Abort(); } } var resultBuilder = new StringBuilder(); resultBuilder.AppendLine("HTTP检测详细结果:"); foreach (var url in _config.HttpTargets) { bool result; if (results.TryGetValue(url, out result)) { string status = result ? "成功" : "失败"; resultBuilder.AppendLine(" " + url + " => " + status); } else { resultBuilder.AppendLine(" " + url + " => 超时"); } } LogInfo(resultBuilder.ToString()); LogInfo("HTTP检测统计: 成功 " + successCount + "/" + _config.HttpTargets.Count); return successCount > 0; } private bool PingHostFast(string host) { try { using (var ping = new Ping()) { var reply = ping.Send(host, 800); return reply != null && reply.Status == IPStatus.Success; } } catch (Exception) { return false; } } private bool TestHttpConnectionFast(string url) { try { var request = WebRequest.Create(url) as HttpWebRequest; if (request == null) { return false; } request.Timeout = 2000; request.Method = "HEAD"; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"; request.Accept = "*/*"; request.KeepAlive = false; using (var response = request.GetResponse() as HttpWebResponse) { if (response != null) { return (int)response.StatusCode >= 200 && (int)response.StatusCode <= 299; } return false; } } catch (WebException ex) { if (ex.Response != null) { using (var response = ex.Response as HttpWebResponse) { if (response != null) { return (int)response.StatusCode >= 200 && (int)response.StatusCode <= 299; } } } return false; } catch (Exception) { return false; } } #endregion
#region 用户活动检测 private bool HasUserInputActivity() { try { uint idleTimeMs = GetUserIdleTime(); uint thresholdMs = (uint)_config.UserIdleThresholdSeconds * 1000; bool hasActivity = idleTimeMs < thresholdMs; LogInfo("用户活动检测: " + (hasActivity ? "有活动" : "无活动") + " (空闲时间: " + (idleTimeMs / 1000) + " 秒)"); return hasActivity; } catch (Exception ex) { LogError("用户活动检测异常", ex); return false; } } private uint GetUserIdleTime() { var lastInputInfo = new LASTINPUTINFO(); lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo); if (GetLastInputInfo(ref lastInputInfo)) { return (uint)Environment.TickCount - lastInputInfo.dwTime; } return uint.MaxValue; } #endregion
#region 关机操作 private void ExecuteShutdown() { try { LogWarning("已达到关机条件,准备执行关机操作"); if (!IsRunningAsAdministrator()) { LogError("执行关机操作需要管理员权限,请以管理员身份运行本程序"); return; } var psi = new ProcessStartInfo { FileName = "shutdown.exe", Arguments = "/s /f /t 0", CreateNoWindow = true, UseShellExecute = false }; using (var process = Process.Start(psi)) { Thread.Sleep(1000); } LogWarning("关机命令已发送,系统将立即关闭"); Stop(); } catch (Exception ex) { LogError("执行关机操作失败", ex); } } private bool IsRunningAsAdministrator() { try { var identity = System.Security.Principal.WindowsIdentity.GetCurrent(); var principal = new System.Security.Principal.WindowsPrincipal(identity); return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); } catch { return false; } } #endregion
#region 日志输出 private void PrintBanner() { Console.WriteLine("==============================================="); Console.WriteLine("网络空闲关机程序 - NetIdleShutdown"); Console.WriteLine("版本: 1.0"); Console.WriteLine("作者: System"); Console.WriteLine("==============================================="); Console.WriteLine("功能说明:"); Console.WriteLine("- 当网络断开且用户无操作时,自动执行关机"); Console.WriteLine("- 检测策略: 双重检测 (Ping + HTTP)"); Console.WriteLine("- 检测方式: 并行多线程检测"); Console.WriteLine("==============================================="); Console.WriteLine("当前配置:"); Console.WriteLine("- 无网络关机阈值: " + _config.MaxNoNetMinutes + " 分钟"); Console.WriteLine("- 检测间隔: " + _config.CheckIntervalSeconds + " 秒"); Console.WriteLine("- 用户空闲阈值: " + _config.UserIdleThresholdSeconds + " 秒"); Console.WriteLine("- Ping检测目标: " + _config.PingTargets.Count + " 个"); Console.WriteLine("- HTTP检测目标: " + _config.HttpTargets.Count + " 个"); Console.WriteLine("==============================================="); Console.WriteLine(""); } private void LogInfo(string message) { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [INFO] " + message); } private void LogWarning(string message) { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [WARN] " + message); } private void LogError(string message, Exception ex = null) { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [ERROR] " + message); if (ex != null) { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [ERROR] 异常类型: " + ex.GetType().Name); Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [ERROR] 异常消息: " + ex.Message); } } #endregion
#region 资源清理 public void Dispose() { _isRunning = false; LogInfo("程序资源已释放"); } #endregion }
public static class Program { public static void Main(string[] args) { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [SYSTEM] 程序启动中..."); using (var shutdown = new NetIdleShutdown()) { Console.CancelKeyPress += (sender, e) => { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [SYSTEM] 收到中断信号,正在停止程序..."); shutdown.Stop(); e.Cancel = true; }; try { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [SYSTEM] 程序已启动,开始网络监控"); shutdown.Run(); } catch (Exception ex) { Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [SYSTEM] 程序运行失败: " + ex.Message); Environment.Exit(1); } } Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] [SYSTEM] 程序已退出"); } } }
|