[OS/WINDOWS] sc query 명령 : 인텔 HAXM(Hardware Accelerated Execution Manager) 지원 여부 구하기
■ sc query 명령을 사용해 인텔 HAXM(Hardware Accelerated Execution Manager) 지원 여부를 구하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서
■ sc query 명령을 사용해 인텔 HAXM(Hardware Accelerated Execution Manager) 지원 여부를 구하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서
■ 윈도우즈 서비스에서 시스템 권한으로 프로세스를 실행하는 방법을 보여준다. [TestLibrary 프로젝트] ▶ ProcessHelper.cs
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 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 |
using System; using System.Runtime.InteropServices; using System.Security.Principal; namespace TestLibrary { /// <summary> /// 프로세스 헬퍼 /// </summary> public static class ProcessHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration ////////////////////////////////////////////////////////////////////////////////////////// Private #region 윈도우 표시 타입 - ShowWindowType /// <summary> /// 윈도우 표시 타입 /// </summary> private enum ShowWindowType { /// <summary> /// SW_HIDE /// </summary> SW_HIDE = 1, /// <summary> /// SW_SHOWNORMAL /// </summary> SW_SHOWNORMAL = 1, /// <summary> /// SW_NORMAL /// </summary> SW_NORMAL = 1, /// <summary> /// SW_SHOWMINIMIZED /// </summary> SW_SHOWMINIMIZED = 2, /// <summary> /// SW_SHOWMAXIMIZED /// </summary> SW_SHOWMAXIMIZED = 3, /// <summary> /// SW_MAXIMIZE /// </summary> SW_MAXIMIZE = 3, /// <summary> /// SW_SHOWNOACTIVATE /// </summary> SW_SHOWNOACTIVATE = 4, /// <summary> /// SW_SHOW /// </summary> SW_SHOW = 5, /// <summary> /// SW_MINIMIZE /// </summary> SW_MINIMIZE = 6, /// <summary> /// SW_SHOWMINNOACTIVE /// </summary> SW_SHOWMINNOACTIVE = 7, /// <summary> /// SW_SHOWN /// </summary> SW_SHOWN = 8, /// <summary> /// SW_RESTORE /// </summary> SW_RESTORE = 9, /// <summary> /// SW_SHOWDEFAULT /// </summary> SW_SHOWDEFAULT = 10, /// <summary> /// SW_MAX /// </summary> SW_MAX = 10 } #endregion #region WTS 연결 상태 클래스 - WTS_CONNECTSTATE_CLASS /// <summary> /// WTS 연결 상태 클래스 /// </summary> private enum WTS_CONNECTSTATE_CLASS { /// <summary> /// WTSActive /// </summary> WTSActive, /// <summary> /// WTSConnected /// </summary> WTSConnected, /// <summary> /// WTSConnectQuery /// </summary> WTSConnectQuery, /// <summary> /// WTSShadow /// </summary> WTSShadow, /// <summary> /// WTSDisconnected /// </summary> WTSDisconnected, /// <summary> /// WTSIdle /// </summary> WTSIdle, /// <summary> /// WTSListen /// </summary> WTSListen, /// <summary> /// WTSReset /// </summary> WTSReset, /// <summary> /// WTSDown /// </summary> WTSDown, /// <summary> /// WTSInit /// </summary> WTSInit } #endregion #region 보안 가장 레벨 - SECURITY_IMPERSONATION_LEVEL /// <summary> /// 보안 가장 레벨 /// </summary> private enum SECURITY_IMPERSONATION_LEVEL { /// <summary> /// SecurityAnonymous /// </summary> SecurityAnonymous = 0, /// <summary> /// SecurityIdentification /// </summary> SecurityIdentification = 1, /// <summary> /// SecurityImpersonation /// </summary> SecurityImpersonation = 2, /// <summary> /// SecurityDelegation /// </summary> SecurityDelegation = 3 } #endregion #region 토큰 타입 - TOKEN_TYPE /// <summary> /// 토큰 타입 /// </summary> private enum TOKEN_TYPE { /// <summary> /// TokenPrimary /// </summary> TokenPrimary = 1, /// <summary> /// TokenImpersonation /// </summary> TokenImpersonation = 2 } #endregion #region 토큰 정보 클래스 - TOKEN_INFORMATION_CLASS /// <summary> /// 토큰 정보 클래스 /// </summary> private enum TOKEN_INFORMATION_CLASS { /// <summary> /// TokenUser /// </summary> TokenUser = 1, /// <summary> /// TokenGroups /// </summary> TokenGroups, /// <summary> /// TokenPrivileges /// </summary> TokenPrivileges, /// <summary> /// TokenOwner /// </summary> TokenOwner, /// <summary> /// TokenPrimaryGroup /// </summary> TokenPrimaryGroup, /// <summary> /// TokenDefaultDACL /// </summary> TokenDefaultDACL, /// <summary> /// TokenSource /// </summary> TokenSource, /// <summary> /// TokenType /// </summary> TokenType, /// <summary> /// TokenImpersonationLevel /// </summary> TokenImpersonationLevel, /// <summary> /// TokenStatistics /// </summary> TokenStatistics, /// <summary> /// TokenRestrictedSIDs /// </summary> TokenRestrictedSIDs, /// <summary> /// TokenSessionID /// </summary> TokenSessionID, /// <summary> /// TokenGroupsAndPrivileges /// </summary> TokenGroupsAndPrivileges, /// <summary> /// TokenSessionReference /// </summary> TokenSessionReference, /// <summary> /// TokenSandBoxInert /// </summary> TokenSandBoxInert, /// <summary> /// TokenAuditPolicy /// </summary> TokenAuditPolicy, /// <summary> /// TokenOrigin /// </summary> TokenOrigin, /// <summary> /// TokenElevationType /// </summary> TokenElevationType, /// <summary> /// TokenLinkedToken /// </summary> TokenLinkedToken, /// <summary> /// TokenElevation /// </summary> TokenElevation, /// <summary> /// TokenHasRestrictions /// </summary> TokenHasRestrictions, /// <summary> /// TokenAccessInformation /// </summary> TokenAccessInformation, /// <summary> /// TokenVirtualizationAllowed /// </summary> TokenVirtualizationAllowed, /// <summary> /// TokenVirtualizationEnabled /// </summary> TokenVirtualizationEnabled, /// <summary> /// TokenIntegrityLevel /// </summary> TokenIntegrityLevel, /// <summary> /// TokenUIAccess /// </summary> TokenUIAccess, /// <summary> /// TokenMandatoryPolicy /// </summary> TokenMandatoryPolicy, /// <summary> /// TokenLogonSid /// </summary> TokenLogonSID, /// <summary> /// MaxTokenInfoClass /// </summary> MaxTokenInfoClass } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 프로세스 정보 - PROCESS_INFORMATION /// <summary> /// 프로세스 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 프로세스 핸들 /// </summary> public IntPtr ProcessHandle; /// <summary> /// 스레드 핸들 /// </summary> public IntPtr ThreadHandle; /// <summary> /// 프로세스 ID /// </summary> public uint ProcessID; /// <summary> /// 스레드 ID /// </summary> public uint ThreadID; #endregion } #endregion #region 시작 정보 - STARTUPINFO /// <summary> /// 시작 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 바이트 카운트 /// </summary> public int ByteCount; /// <summary> /// 예약 문자열 /// </summary> public string ReservedString; /// <summary> /// 데스크톱 /// </summary> public string Desktop; /// <summary> /// 제목 /// </summary> public string Title; /// <summary> /// X /// </summary> public uint X; /// <summary> /// ㅛ /// </summary> public uint Y; /// <summary> /// X 크기 /// </summary> public uint XSize; /// <summary> /// Y 크기 /// </summary> public uint YSize; /// <summary> /// X 카운트 (문자 단위) /// </summary> public uint XCountCharacter; /// <summary> /// Y 카운트 (문자 단위) /// </summary> public uint YCountCharacter; /// <summary> /// 채우기 어트리뷰트 /// </summary> public uint FillAttribute; /// <summary> /// 플래그 /// </summary> public uint Flag; /// <summary> /// 윈도우 표시 /// </summary> public short ShowWindow; /// <summary> /// 예약 핸들 바이트 카운트 /// </summary> public short ByteCountReservedHandle; /// <summary> /// 예약 핸들 /// </summary> public IntPtr ReservedHandle; /// <summary> /// 표준 입력 핸들 /// </summary> public IntPtr StandardInputHandle; /// <summary> /// 표준 출력 핸들 /// </summary> public IntPtr StandardOutputHandle; /// <summary> /// 표준 에러 핸들 /// </summary> public IntPtr StandardErrorHandle; #endregion } #endregion #region WTS 세션 정보 - WTS_SESSION_INFO /// <summary> /// WTS 세션 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct WTS_SESSION_INFO { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 세션 ID /// </summary> public readonly uint SessionID; /// <summary> /// WIN 스테이션명 /// </summary> [MarshalAs(UnmanagedType.LPStr)] public readonly string WinStationName; /// <summary> /// 상태 /// </summary> public readonly WTS_CONNECTSTATE_CLASS State; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static #region 사용자로 프로세스 생성하기 - CreateProcessAsUser(tokenHandle, applicationName, commandLine, processAttributeHandle, threadAttributeHandle, inheritHandle, creationFlag, environmentHandle, currentDirectoryPath, startupInfo, processInformation) /// <summary> /// 사용자로 프로세스 생성하기 /// </summary> /// <param name="tokenHandle">토큰 핸들</param> /// <param name="applicationName">애플리케이션명</param> /// <param name="commandLine">명령줄</param> /// <param name="processAttributeHandle">프로세스 어트리뷰트 핸들</param> /// <param name="threadAttributeHandle">스레드 어트리뷰트 핸들</param> /// <param name="inheritHandle">상속 핸들</param> /// <param name="creationFlag">생성 플래그</param> /// <param name="environmentHandle">환경 핸들</param> /// <param name="currentDirectoryPath">현재 디렉토리 경로</param> /// <param name="startupInfo">시작 정보</param> /// <param name="processInformation">프로세스 정보</param> /// <returns>처리 결과</returns> [DllImport("advapi32", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] private static extern bool CreateProcessAsUser ( IntPtr tokenHandle, string applicationName, string commandLine, IntPtr processAttributeHandle, IntPtr threadAttributeHandle, bool inheritHandle, uint creationFlag, IntPtr environmentHandle, string currentDirectoryPath, ref STARTUPINFO startupInfo, out PROCESS_INFORMATION processInformation ); #endregion #region 토큰 복제하기 (확장) - DuplicateTokenEx(existingTokenHandle, desiredAccess, threadAttributeHandle, tokenType, impersonationLevel, duplicateTokenHandle) /// <summary> /// 토큰 복제하기 (확장) /// </summary> /// <param name="existingTokenHandle">기존 토클 핸들</param> /// <param name="desiredAccess">희망 액세스</param> /// <param name="threadAttributeHandle">스레드 어트리뷰트 핸들</param> /// <param name="tokenType">토큰 타입</param> /// <param name="impersonationLevel">가장 레벨</param> /// <param name="duplicateTokenHandle">복제 토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("advapi32", EntryPoint = "DuplicateTokenEx")] private static extern bool DuplicateTokenEx ( IntPtr existingTokenHandle, uint desiredAccess, IntPtr threadAttributeHandle, int tokenType, int impersonationLevel, ref IntPtr duplicateTokenHandle ); #endregion #region 환경 블럭 생성하기 - CreateEnvironmentBlock(environmentHandle, tokenHandle, inherit) /// <summary> /// 환경 블럭 생성하기 /// </summary> /// <param name="environmentHandle">환경 핸들</param> /// <param name="tokenHandle">토큰 핸들</param> /// <param name="inherit">상속 여부</param> /// <returns>처리 결과</returns> [DllImport("userenv", SetLastError = true)] private static extern bool CreateEnvironmentBlock(ref IntPtr environmentHandle, IntPtr tokenHandle, bool inherit); #endregion #region 환경 블럭 제거하기 - DestroyEnvironmentBlock(environmentHandle) /// <summary> /// 환경 블럭 제거하기 /// </summary> /// <param name="environmentHandle">환경 핸들</param> /// <returns>처리 결과</returns> [DllImport("userenv", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DestroyEnvironmentBlock(IntPtr environmentHandle); #endregion #region 핸들 닫기 - CloseHandle(snapshotHandle) /// <summary> /// 핸들 닫기 /// </summary> /// <param name="snapshotHandle">스냅샷 핸들</param> /// <returns>처리 결과</returns> [DllImport("kernel32", SetLastError = true)] private static extern bool CloseHandle(IntPtr snapshotHandle); #endregion #region WTS 활성 콘솔 세션 ID 구하기 - WTSGetActiveConsoleSessionId() /// <summary> /// WTS 활성 콘솔 세션 ID 구하기 /// </summary> /// <returns>활성 콘솔 세션 ID</returns> [DllImport("kernel32")] private static extern uint WTSGetActiveConsoleSessionId(); #endregion #region WTS 사용자 토큰 질의하기 - WTSQueryUserToken(sessionID, tokenHandle) /// <summary> /// WTS 사용자 토큰 질의하기 /// </summary> /// <param name="sessionID">세션 ID</param> /// <param name="tokenHandle">토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("wtsapi32")] private static extern uint WTSQueryUserToken(uint sessionID, ref IntPtr tokenHandle); #endregion #region WTS 세션 열거하기 - WTSEnumerateSessions(serverHandle, reserved, version, sessionInfoHandle, count) /// <summary> /// WTS 세션 열거하기 /// </summary> /// <param name="serverHandle">서버 핸들</param> /// <param name="reserved">예약</param> /// <param name="version">버전</param> /// <param name="sessionInfoHandle">세션 정보 핸들</param> /// <param name="count">카운트</param> /// <returns>처리 결과</returns> [DllImport("wtsapi32", SetLastError = true)] private static extern int WTSEnumerateSessions ( IntPtr serverHandle, int reserved, int version, ref IntPtr sessionInfoHandle, ref int count ); #endregion #region WTF 메모리 해제하기 - WTSFreeMemory(memoryHandle) /// <summary> /// WTF 메모리 해제하기 /// </summary> /// <param name="memoryHandle">메모리 핸들</param> [DllImport("wtsapi32")] private static extern void WTSFreeMemory(IntPtr memoryHandle); #endregion #region 토큰 정보 설정하기 - SetTokenInformation(tokenHandle, tokenInformationClass, tokenInformation, tokenInformationLenth) /// <summary> /// 토큰 정보 설정하기 /// </summary> /// <param name="tokenHandle">토큰 핸들</param> /// <param name="tokenInformationClass">토큰 정보 클래스</param> /// <param name="tokenInformation">토큰 정보</param> /// <param name="tokenInformationLenth">토큰 정보 길이</param> /// <returns>처리 결과</returns> [DllImport("advapi32", SetLastError = true)] private static extern bool SetTokenInformation(IntPtr tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, ref uint tokenInformation, uint tokenInformationLenth); #endregion #region 프로세스 토큰 열기 - OpenProcessToken(processHandle, desiredAccess, tokenHandle) /// <summary> /// 프로세스 토큰 열기 /// </summary> /// <param name="processHandle">프로세스 핸들</param> /// <param name="desiredAccess">희망 액세스</param> /// <param name="tokenHandle">토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// WTS_CURRENT_SERVER_HANDLE /// </summary> private static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// CREATE_UNICODE_ENVIRONMENT /// </summary> private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400; /// <summary> /// CREATE_NO_WINDOW /// </summary> private const int CREATE_NO_WINDOW = 0x08000000; /// <summary> /// CREATE_NEW_CONSOLE /// </summary> private const int CREATE_NEW_CONSOLE = 0x00000010; /// <summary> /// INVALID_SESSION_ID /// </summary> private const uint INVALID_SESSION_ID = 0xffffffff; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 현재 사용자로 프로세스 실행하기 - ExecuteProcessAsCurrentUser(applicationFilePath, processInformation, commandLine, workingDirectoryPath, visible) /// <summary> /// 현재 사용자로 프로세스 실행하기 /// </summary> /// <param name="applicationFilePath">애플리케이션 경로</param> /// <param name="processInformation">프로세스 정보</param> /// <param name="commandLine">명령줄</param> /// <param name="workingDirectoryPath">작업 디렉토리 경로</param> /// <param name="visible">표시 여부</param> /// <returns>처리 결과</returns> public static bool ExecuteProcessAsCurrentUser ( string applicationFilePath, out PROCESS_INFORMATION processInformation, string commandLine = null, string workingDirectoryPath = null, bool visible = true ) { IntPtr userTokenHandle = IntPtr.Zero; IntPtr systemTokenHandle = IntPtr.Zero; IntPtr environmentHandle = IntPtr.Zero; processInformation = new PROCESS_INFORMATION(); try { uint activeSessionID = GetActiveConsoleSessionID(); if(activeSessionID == INVALID_SESSION_ID) { return false; } if(!GetSessionUserToken(activeSessionID, ref userTokenHandle)) { throw new Exception("ExecuteProcessAsCurrentUser : GetSessionUserToken failed."); } if(!GetSystemToken(activeSessionID, ref systemTokenHandle)) { throw new Exception("ExecuteProcessAsCurrentUser : GetSystemToken failed."); } if(!CreateEnvironmentBlock(ref environmentHandle, userTokenHandle, false)) { throw new Exception("ExecuteProcessAsCurrentUser : CreateEnvironmentBlock failed."); } uint creationFlag = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW); STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.ByteCount = Marshal.SizeOf(typeof(STARTUPINFO)); startupInfo.ShowWindow = (short)(visible ? ShowWindowType.SW_SHOW : ShowWindowType.SW_HIDE); startupInfo.Desktop = "winsta0\\default"; if ( !CreateProcessAsUser ( systemTokenHandle, applicationFilePath, commandLine, IntPtr.Zero, IntPtr.Zero, false, creationFlag, environmentHandle, workingDirectoryPath, ref startupInfo, out processInformation ) ) { int errorCode = Marshal.GetLastWin32Error(); string errorMessage = $"ExecuteProcessAsCurrentUser: CreateProcessAsUser failed."; throw new Exception(errorMessage); } } finally { CloseHandle(userTokenHandle); CloseHandle(systemTokenHandle); if(environmentHandle != IntPtr.Zero) { DestroyEnvironmentBlock(environmentHandle); } CloseHandle(processInformation.ThreadHandle); CloseHandle(processInformation.ProcessHandle); } return true; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 세션 사용자 토큰 구하기 - GetSessionUserToken(activeSessionID, userTokenHandle) /// <summary> /// 세션 사용자 토큰 구하기 /// </summary> /// <param name="activeSessionID">활성 세션 ID</param> /// <param name="userTokenHandle">사용자 토큰 핸들</param> /// <returns>처리 결과</returns> private static bool GetSessionUserToken(uint activeSessionID, ref IntPtr userTokenHandle) { bool result = false; IntPtr impersonationTokenHandle = IntPtr.Zero; if(WTSQueryUserToken(activeSessionID, ref impersonationTokenHandle) != 0) { result = DuplicateTokenEx ( impersonationTokenHandle, 0, IntPtr.Zero, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary, ref userTokenHandle ); CloseHandle(impersonationTokenHandle); } return result; } #endregion #region 시스템 토큰 구하기 - GetSystemToken(activeSessionID, systemTokenHandle) /// <summary> /// 시스템 토큰 구하기 /// </summary> /// <param name="activeSessionID">활성 세션 ID</param> /// <param name="systemTokenHandle">시스템 토큰 핸들</param> /// <returns>처리 결과</returns> private static bool GetSystemToken(uint activeSessionID, ref IntPtr systemTokenHandle) { using ( WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent ( TokenAccessLevels.AssignPrimary | TokenAccessLevels.Duplicate | TokenAccessLevels.Impersonate | TokenAccessLevels.AdjustDefault | TokenAccessLevels.AdjustSessionId | TokenAccessLevels.Read ) ) { IntPtr impersonationTokenHandle = windowsIdentity.Token; if(impersonationTokenHandle == IntPtr.Zero) { return false; } if ( DuplicateTokenEx ( impersonationTokenHandle, 0, IntPtr.Zero, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary, ref systemTokenHandle ) ) { if(SetTokenInformation(systemTokenHandle, TOKEN_INFORMATION_CLASS.TokenSessionID, ref activeSessionID, (uint)Marshal.SizeOf(activeSessionID))) { return true; } else { CloseHandle(systemTokenHandle); } } } return false; } #endregion #region 활성 콘솔 세션 ID 구하기 - GetActiveConsoleSessionID() /// <summary> /// 활성 콘솔 세션 ID 구하기 /// </summary> /// <returns>활성 콘솔 세션 ID</returns> private static uint GetActiveConsoleSessionID() { uint activeSessionID = INVALID_SESSION_ID; IntPtr sessionInfoHandle = IntPtr.Zero; int sessionCount = 0; if(WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref sessionInfoHandle, ref sessionCount) != 0) { int arrayElementSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSessionHandle = sessionInfoHandle; for(int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO sessionInfo = (WTS_SESSION_INFO)Marshal.PtrToStructure(currentSessionHandle, typeof(WTS_SESSION_INFO)); currentSessionHandle += arrayElementSize; if(sessionInfo.State == WTS_CONNECTSTATE_CLASS.WTSActive) { activeSessionID = sessionInfo.SessionID; break; } } WTSFreeMemory(sessionInfoHandle); if(activeSessionID == INVALID_SESSION_ID) { activeSessionID = WTSGetActiveConsoleSessionId(); } } return activeSessionID; } #endregion } } |
▶ TestNode.cs
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 |
using System; using System.Diagnostics; using System.IO; namespace TestLibrary { /// <summary> /// 테스트 노드 /// </summary> public class TestNode { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field #region 로그 /// <summary> /// 로그 헬퍼 /// </summary> private ILogHelper logHelper; #endregion #region 실행 작업자 /// <summary> /// 실행 작업자 주기 (단위 : 밀리초) /// </summary> private int executeWorkerInterval = 1000; // 1초 /// <summary> /// 실행 작업자 /// </summary> private RepeatWorker executeWorker = null; #endregion /// <summary> /// 실행 여부 /// </summary> private bool isRunning = false; /// <summary> /// 틱 카운트 /// </summary> private int tickCount = 0; /// <summary> /// 첫번째 여부 /// </summary> private bool isFirst = true; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 실행 여부 - IsRunning /// <summary> /// 실행 여부 /// </summary> public bool IsRunning { get { return this.isRunning; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TestNode() /// <summary> /// 생성자 /// </summary> public TestNode() { #region 로그 헬퍼를 설정한다. this.logHelper = new FileLogHelper("d:\\", "TestNode.log"); #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { try { File.Delete(@"D:\TestNode.log"); this.logHelper?.WriteLog("BEGIN START FUNCTION"); if(this.isRunning) { this.logHelper?.WriteLog("STOP START FUNCTION : AlreadyRunning"); return; } this.isRunning = true; #region 실행 작업자를 설정한다. if(this.executeWorker != null) { if(this.executeWorker.IsRunning) { this.executeWorker.Stop(); } this.executeWorker = null; } this.executeWorker = new RepeatWorker(new Action<object>(ProcessExecute), null, this.executeWorkerInterval); #endregion this.executeWorker.Start(); this.logHelper?.WriteLog("END START FUNCTION"); } catch(Exception exception) { this.isRunning = false; this.logHelper?.WriteErrorLog(exception, "ERROR START FUNCTION"); throw exception; } } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { try { this.logHelper?.WriteLog("BEGIN STOP FUNCTION"); if(!this.isRunning) { this.logHelper?.WriteLog("STOP STOP FUNCTION : AlreadyStopped"); return; } this.isRunning = false; #region 실행 작업자를 중단한다. this.executeWorker.Stop(); this.executeWorker = null; #endregion this.logHelper?.WriteLog("END STOP FUNCTION"); } catch(Exception exception) { this.isRunning = false; this.logHelper?.WriteErrorLog(exception, "ERROR STOP FUNCTION"); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 프로세스 죽이기 - KillProcess(string filePath) /// <summary> /// 프로세스 죽이기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>처리 결과</returns> private bool KillProcess(string filePath) { if(string.IsNullOrWhiteSpace(filePath)) { return false; } bool result = false; try { string processName = Path.GetFileNameWithoutExtension(filePath); foreach(Process process in Process.GetProcessesByName(processName)) { try { if ( process.MainModule != null && process.MainModule.FileName != null && string.Compare(process.MainModule.FileName, filePath, true) == 0 ) { process.Kill(); result = true; } } catch { } } } catch { } return result; } #endregion #region 메모장 실행하기 - ExecuteNotepad() /// <summary> /// 메모장 실행하기 /// </summary> private void ExecuteNotepad() { string filePath = @"C:\Windows\System32\notepad.exe"; string workingDirectoryPath = Path.GetDirectoryName(filePath); KillProcess(filePath); try { ProcessHelper.ExecuteProcessAsCurrentUser(filePath, out ProcessHelper.PROCESS_INFORMATION processInformation, "", workingDirectoryPath); this.logHelper?.WriteLog("EXECUTE PROCESS AS CURRENT USER"); } catch(Exception exception) { this.logHelper?.WriteErrorLog(exception, "ERROR EXECUTE PROCESS AS CURRENT USER"); } } #endregion #region 실행 처리하기 - ProcessExecute(parameter) /// <summary> /// 실행 처리하기 /// </summary> /// <param name="parameter">매개 변수</param> private void ProcessExecute(object parameter) { try { this.logHelper?.WriteLog("테스트 메시지"); if(this.isFirst) { this.tickCount++; if(this.tickCount == 30) { this.isFirst = false; ExecuteNotepad(); } } } catch(Exception exception) { this.logHelper?.WriteErrorLog(exception, "ERROR PROCESS EXECUTE FUNCTION"); } } #endregion } } |
[TestService 프로젝트] ▶ ProcessInstaller.cs
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 |
using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; namespace TestService { /// <summary> /// 프로젝트 설치자 /// </summary> [RunInstaller(true)] public partial class ProjectInstaller : Installer { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 서비스 프로세스 설치자 /// </summary> private ServiceProcessInstaller serviceProcessInstaller; /// <summary> /// 서비스 설치자 /// </summary> private ServiceInstaller serviceInstaller; /// <summary> /// 서비스명 /// </summary> private const string SERVICE_NAME = "TestNode"; /// <summary> /// 서비스 설명 /// </summary> private const string SERVICE_DESCRIPTION = "테스트 노드"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ProjectInstaller() /// <summary> /// 생성자 /// </summary> public ProjectInstaller() { this.serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = ServiceAccount.LocalSystem; serviceProcessInstaller.Password = null; serviceProcessInstaller.Username = null; this.serviceInstaller = new ServiceInstaller(); serviceInstaller.ServiceName = SERVICE_NAME; serviceInstaller.DisplayName = SERVICE_NAME; serviceInstaller.Description = SERVICE_DESCRIPTION; serviceInstaller.StartType = ServiceStartMode.Automatic; Installers.AddRange(new Installer[] { this.serviceProcessInstaller, this.serviceInstaller }); } #endregion } } |
■ ManagementObject 클래스를 사용해 윈도우즈 서비스의 파일 경로를 구하는 방법을 보여준다. ▶ Program.cs
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 |
using System; using System.Management; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { string filePath = GetWindowsServiceFilePath("wscsvc"); Console.WriteLine(filePath); } #endregion #region 윈도우즈 서비스 파일 경로 구하기 - GetWindowsServiceFilePath(serviceName) /// <summary> /// 윈도우즈 서비스 파일 경로 구하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <returns>윈도우즈 서비스 파일 경로</returns> private static string GetWindowsServiceFilePath(string serviceName) { using(ManagementObject managementObject = new ManagementObject($"Win32_Service.Name='{serviceName}'")) { managementObject.Get(); string filePath = managementObject["PathName"].ToString(); return filePath; } } #endregion } } |
TestProject.zip
■ Get-WmiObject 명령을 사용해 윈도우즈 서비스의 프로세스 ID를 구하는 방법을 보여준다. ▶ 실행 명령
1 2 3 4 5 6 7 |
$id = Get-WmiObject -Class Win32_Service -Filter "Name LIKE 'DcomLaunch'" | Select-Object -ExpandProperty ProcessId $process = Get-Process -Id $id $process |
※ DcomLaunch는 윈도우즈 서비스 이름이다.
■ tasklist 명령을 사용해 윈도우즈 서비스의 프로세스 ID를 구하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을 실행한다. ▶
■ 윈도우즈 서비스를 사용하는 방법을 보여준다. [TestLibrary 프로젝트] ▶ ILogHelper.cs
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 |
using System; namespace TestLibrary { /// <summary> /// 로그 헬퍼 인터페이스 /// </summary> public interface ILogHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method #region 메시지 쓰기 - WriteMessage(message) /// <summary> /// 메시지 쓰기 /// </summary> /// <param name="message">메시지</param> void WriteMessage(string message); #endregion #region 로그 쓰기 - WriteLog(format, parameterArray) /// <summary> /// 로그 쓰기 /// </summary> /// <param name="format">포맷 문자열</param> /// <param name="parameterArray">매개 변수 배열</param> void WriteLog(string format, params object[] parameterArray); #endregion #region 에러 로그 쓰기 - WriteErrorLog(exception, caption) /// <summary> /// 에러 로그 쓰기 /// </summary> /// <param name="exception">예외</param> /// <param name="caption">제목 문자열</param> void WriteErrorLog(Exception exception, string caption); #endregion #region 에러 로그 쓰기 - WriteErrorLog(exception, caption) /// <summary> /// 에러 로그 쓰기 /// </summary> /// <param name="message">예외 메시지</param> /// <param name="caption">제목 문자열</param> void WriteErrorLog(string message, string caption); #endregion #region 덤프 로그 쓰기 - WriteDumpLog(sourceObject, caption) /// <summary> /// 덤프 로그 쓰기 /// </summary> /// <param name="sourceObject">예외</param> /// <param name="caption">제목 문자열</param> void WriteDumpLog(object sourceObject, string caption); #endregion } } |
▶ FileLogHelper.cs
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 |
using System; using System.IO; namespace TestLibrary { /// <summary> /// 파일 로그 헬퍼 /// </summary> public class FileLogHelper : ILogHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 동기 객체 /// </summary> private object syncObject; /// <summary> /// 로그 루트 디렉토리 경로 /// </summary> private string logRootDirectoryPath; /// <summary> /// 파일명 /// </summary> private string fileName; /// <summary> /// 파일 경로 /// </summary> private string filePath; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - FileLogHelper(logRootDirectoryPath, fileName) /// <summary> /// 생성자 /// </summary> /// <param name="logRootDirectoryPath">로그 루트 디렉토리 경로</param> /// <param name="fileName">파일명</param> public FileLogHelper(string logRootDirectoryPath, string fileName) { this.syncObject = new object(); this.logRootDirectoryPath = logRootDirectoryPath; this.fileName = fileName; this.filePath = Path.Combine(this.logRootDirectoryPath, this.fileName); if(!Directory.Exists(this.logRootDirectoryPath)) { Directory.CreateDirectory(this.logRootDirectoryPath); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메시지 쓰기 - WriteMessage(message) /// <summary> /// 메시지 쓰기 /// </summary> /// <param name="message">메시지</param> public void WriteMessage(string message) { lock(this.syncObject) { using(StreamWriter writer = File.AppendText(this.filePath)) { writer.WriteLine(message); } } } #endregion #region 로그 쓰기 - WriteLog(format, parameterArray) /// <summary> /// 로그 쓰기 /// </summary> /// <param name="format">포맷 문자열</param> /// <param name="parameterArray">매개 변수 배열</param> public void WriteLog(string format, params object[] parameterArray) { string message; if(parameterArray.Length == 0) { message = format; } else { message = string.Format(format, parameterArray); } string log = string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss"), message); WriteMessage(log); } #endregion #region 에러 로그 쓰기 - WriteErrorLog(exception, source) /// <summary> /// 에러 로그 쓰기 /// </summary> /// <param name="exception">예외</param> /// <param name="source">소스 문자열</param> public void WriteErrorLog(Exception exception, string source) { lock(this.syncObject) { string title = string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss"), source); using(StreamWriter writer = File.AppendText(this.filePath)) { writer.WriteLine(title); writer.WriteLine("--------------------------------------------------"); writer.WriteLine(exception.ToString()); writer.WriteLine("--------------------------------------------------"); } } } #endregion #region 에러 로그 쓰기 - WriteErrorLog(message, source) /// <summary> /// 에러 로그 쓰기 /// </summary> /// <param name="message">예외 메시지</param> /// <param name="source">소스 문자열</param> public void WriteErrorLog(string message, string source) { lock (this.syncObject) { string title = string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss"), source); using (StreamWriter writer = File.AppendText(this.filePath)) { writer.WriteLine(title); writer.WriteLine("--------------------------------------------------"); writer.WriteLine(message); writer.WriteLine("--------------------------------------------------"); } } } #endregion #region 덤프 로그 쓰기 - WriteDumpLog(sourceObject, caption) /// <summary> /// 덤프 로그 쓰기 /// </summary> /// <param name="sourceObject">예외</param> /// <param name="caption">제목 문자열</param> public void WriteDumpLog(object sourceObject, string caption) { lock(this.syncObject) { string title = string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss"), caption); using(StreamWriter writer = File.AppendText(this.filePath)) { writer.WriteLine(title); writer.WriteLine("--------------------------------------------------"); writer.WriteLine(sourceObject.ToString()); writer.WriteLine("--------------------------------------------------"); } } } #endregion } } |
▶ RepeatWorker.cs
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 |
using System; using System.Threading; namespace TestLibrary { /// <summary> /// 반복 작업자 /// </summary> public class RepeatWorker : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Protected #region Field /// <summary> /// 로그 헬퍼 /// </summary> protected ILogHelper logHelper = null; /// <summary> /// 스레드 /// </summary> protected Thread thread = null; /// <summary> /// 루프 계속 여부 /// </summary> protected bool continueLoop = true; /// <summary> /// 휴지 여부 /// </summary> protected bool isSleep = false; /// <summary> /// 휴지 시간 (단위 : 밀리초) /// </summary> protected int sleepTime; /// <summary> /// 작업 액션 /// </summary> protected Action<object> workAction; /// <summary> /// 작업 매개 변수 /// </summary> protected object workParameter; /// <summary> /// 실행 여부 /// </summary> protected bool isRunning = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 로그 헬퍼 - LogHelper /// <summary> /// 로그 헬퍼 /// </summary> public ILogHelper LogHelper { get { return this.logHelper; } set { this.logHelper = value; } } #endregion #region 스레드 - Thread /// <summary> /// 스레드 /// </summary> public Thread Thread { get { return this.thread; } } #endregion #region 휴지 시간 (단위 : 밀리초) - SleepTime /// <summary> /// 휴지 시간 (단위 : 밀리초) /// </summary> public int SleepTime { get { return this.sleepTime; } set { this.sleepTime = value; } } #endregion #region 작업 액션 - WorkAction /// <summary> /// 작업 액션 /// </summary> public Action<object> WorkAction { get { return this.workAction; } set { this.workAction = value; } } #endregion #region 작업 매개 변수 - WorkParameter /// <summary> /// 작업 매개 변수 /// </summary> public object WorkParameter { get { return this.workParameter; } set { this.workParameter = value; } } #endregion #region 실행 여부 - IsRunning /// <summary> /// 실행 여부 /// </summary> public bool IsRunning { get { return this.isRunning; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - RepeatWorker(workAction, workParameter, sleepTime) /// <summary> /// 생성자 /// </summary> /// <param name="workAction">작업 액션</param> /// <param name="workParameter">작업 매개 변수</param> /// <param name="sleepTime">휴지 시간 (단위 : 밀리초(</param> public RepeatWorker(Action<object> workAction, object workParameter, int sleepTime = 1000) { this.workAction = workAction; this.workParameter = workParameter; this.sleepTime = sleepTime; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { try { if(this.isRunning) { return; } this.isRunning = true; #region 스레드를 설정한다. if(this.thread != null) { if(this.thread.IsAlive) { this.thread.Abort(); } this.thread = null; } this.thread = new Thread(new ThreadStart(ProcessThread)); this.thread.IsBackground = true; #endregion this.thread.Start(); } catch(Exception exception) { this.isRunning = false; this.logHelper?.WriteErrorLog(exception, "ERROR START FUNCTION"); throw exception; } } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { try { if(!this.isRunning) { return; } this.isRunning = false; #region 스레드를 중단한다. this.continueLoop = false; Thread.Sleep(500); if(this.thread != null && this.thread.IsAlive) { if(this.isSleep) { this.thread.Abort(); } } #endregion } catch(Exception exception) { this.logHelper?.WriteErrorLog(exception, "ERROR STOP FUNCTION"); } } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Stop(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 스레드 처리하기 - ProcessThread() /// <summary> /// 스레드 처리하기 /// </summary> private void ProcessThread() { while(this.continueLoop) { try { this.workAction?.Invoke(this.workParameter); } catch(Exception exception) { this.logHelper?.WriteErrorLog(exception, "ERROR WHEN PROCESS THREAD"); } if(!this.continueLoop) { break; } this.isSleep = true; Thread.Sleep(this.sleepTime); this.isSleep = false; } } #endregion } } |
▶ TestNode.cs
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 |
using System; namespace TestLibrary { /// <summary> /// 테스트 노드 /// </summary> public class TestNode { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field #region 로그 /// <summary> /// 로그 헬퍼 /// </summary> private ILogHelper logHelper; #endregion #region 실행 작업자 /// <summary> /// 실행 작업자 주기 (단위 : 밀리초) /// </summary> private int executeWorkerInterval = 1000; // 0.1초 /// <summary> /// 실행 작업자 /// </summary> private RepeatWorker executeWorker = null; #endregion /// <summary> /// 실행 여부 /// </summary> private bool isRunning = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 실행 여부 - IsRunning /// <summary> /// 실행 여부 /// </summary> public bool IsRunning { get { return this.isRunning; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TestNode() /// <summary> /// 생성자 /// </summary> public TestNode() { #region 로그 헬퍼를 설정한다. this.logHelper = new FileLogHelper("d:\\", "TestNode.log"); #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { try { this.logHelper?.WriteLog("BEGIN START FUNCTION"); if(this.isRunning) { this.logHelper?.WriteLog("STOP START FUNCTION : AlreadyRunning"); return; } this.isRunning = true; #region 실행 작업자를 설정한다. if(this.executeWorker != null) { if(this.executeWorker.IsRunning) { this.executeWorker.Stop(); } this.executeWorker = null; } this.executeWorker = new RepeatWorker(new Action<object>(ProcessExecute), null, this.executeWorkerInterval); #endregion this.executeWorker.Start(); this.logHelper?.WriteLog("END START FUNCTION"); } catch(Exception exception) { this.isRunning = false; this.logHelper?.WriteErrorLog(exception, "ERROR START FUNCTION"); throw exception; } } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { try { this.logHelper?.WriteLog("BEGIN STOP FUNCTION"); if(!this.isRunning) { this.logHelper?.WriteLog("STOP STOP FUNCTION : AlreadyStopped"); return; } this.isRunning = false; #region 실행 작업자를 중단한다. this.executeWorker.Stop(); this.executeWorker = null; #endregion this.logHelper?.WriteLog("END STOP FUNCTION"); } catch(Exception exception) { this.isRunning = false; this.logHelper?.WriteErrorLog(exception, "ERROR STOP FUNCTION"); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 실행 처리하기 - ProcessExecute(parameter) /// <summary> /// 실행 처리하기 /// </summary> /// <param name="parameter">매개 변수</param> private void ProcessExecute(object parameter) { try { this.logHelper?.WriteLog("테스트 메시지"); } catch(Exception exception) { this.logHelper?.WriteErrorLog(exception, "ERROR PROCESS EXECUTE FUNCTION"); } } #endregion } } |
[TestService 프로젝트]
■ 윈도우즈 서비스를 특정 계정으로 시작하는 방법을 보여준다. 1. [명령 프롬프트]에서 아래와 같이 [로컬 보안 정책]을 실행한다. ▶ 실행 명령
1 2 3 |
secpol.msc |
2.
■ 윈도우즈 서비스 내에서 사용자 계정을 변경하는 방법을 보여준다. ▶ ImpersonationHelper.cs
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 |
using System; using System.Runtime.InteropServices; using System.Security.Principal; namespace TestService { /// <summary> /// 가장 헬퍼 /// </summary> public class ImpersonationHelper : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 사용자 로그온 하기 - LogonUser(userAccount, domain, password, logonType, logonProvider, tokenHandle) /// <summary> /// 사용자 로그온 하기 /// </summary> /// <param name="userAccount">사용자 계정</param> /// <param name="domain">도메인</param> /// <param name="password">패스워드</param> /// <param name="logonType">로그온 타입</param> /// <param name="logonProvider">로그온 제공자</param> /// <param name="tokenHandle">토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("advapi32.dll", SetLastError = true)] private static extern bool LogonUser(string userAccount, string domain, string password, int logonType, int logonProvider, ref IntPtr tokenHandle); #endregion #region 핸들 닫기 - CloseHandle(tokenHandle) /// <summary> /// 핸들 닫기 /// </summary> /// <param name="tokenHandle">토큰 핸들</param> /// <returns>처리 결과</returns> [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private extern static bool CloseHandle(IntPtr tokenHandle); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 토큰 핸들 /// </summary> private IntPtr tokenHandle = IntPtr.Zero; /// <summary> /// 윈도우즈 식별자 /// </summary> private WindowsIdentity windowsIdentity; /// <summary> /// 윈도우즈 가장 컨텍스트 /// </summary> private WindowsImpersonationContext windowsImpersonationContext; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ImpersonationHelper(domain, userAccount, password) /// <summary> /// 생성자 /// </summary> /// <param name="domain">도메인</param> /// <param name="userAccount">사용자 계정</param> /// <param name="password">패스워드</param> public ImpersonationHelper(string domain, string userAccount, string password) { if(LogonUser(userAccount, domain, password, 3, 0, ref this.tokenHandle)) { this.windowsIdentity = new WindowsIdentity(this.tokenHandle); this.windowsImpersonationContext = this.windowsIdentity.Impersonate(); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { this.windowsImpersonationContext.Undo(); this.windowsImpersonationContext.Dispose(); this.windowsIdentity.Dispose(); if(this.tokenHandle != IntPtr.Zero) { CloseHandle(this.tokenHandle); } this.tokenHandle = IntPtr.Zero; } #endregion } } |
▶ WindowService.cs
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 |
using System; using System.Security.Principal; using System.ServiceProcess; namespace TestService { /// <summary> /// 윈도우 서비스 /// </summary> public partial class WindowService : ServiceBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - WindowService() /// <summary> /// 생성자 /// </summary> public WindowService() { AutoLog = false; ServiceName = "ServiceName"; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 테스트 하기 - Test(argumentArray) /// <summary> /// 테스트 하기 /// </summary> /// <param name="argumentArray">인자 배열</param> /// <remarks>디버그 모드시 실행된다.</remarks> public void Test(string[] argumentArray) { OnStart(argumentArray); Console.ReadLine(); OnStop(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 시작시 처리하기 - OnStart(argumentArray) /// <summary> /// 시작시 처리하기 /// </summary> /// <param name="argumentArray">인자 배열</param> protected override void OnStart(string[] argumentArray) { FileLogHelper logHelper = new FileLogHelper("d:\\", "service.log"); WindowsIdentity windowsIdentity; windowsIdentity = WindowsIdentity.GetCurrent(); logHelper.WriteLog("현재 윈도우즈 신원"); logHelper.WriteLog("----------------------------------------" ); logHelper.WriteLog("사용자 계정 : {0}", windowsIdentity.Name ); logHelper.WriteLog("사용자 SDDL : {0}", windowsIdentity.User.Value); using(ImpersonationHelper helper = new ImpersonationHelper("kingdom", "test", "1234")) { windowsIdentity = WindowsIdentity.GetCurrent(); logHelper.WriteLog("현재 윈도우즈 신원"); logHelper.WriteLog("----------------------------------------" ); logHelper.WriteLog("사용자 계정 : {0}", windowsIdentity.Name ); logHelper.WriteLog("사용자 SDDL : {0}", windowsIdentity.User.Value); } windowsIdentity = WindowsIdentity.GetCurrent(); logHelper.WriteLog("현재 윈도우즈 신원"); logHelper.WriteLog("----------------------------------------" ); logHelper.WriteLog("사용자 계정 : {0}", windowsIdentity.Name ); logHelper.WriteLog("사용자 SDDL : {0}", windowsIdentity.User.Value); } #endregion #region 중단시 처리하기 - OnStop() /// <summary> /// 중단시 처리하기 /// </summary> protected override void OnStop() { } #endregion } } |
TestService.zip
■ Process 클래스를 사용해 윈도우즈 서비스를 실행하는 방법을 보여준다. ▶ WindowsServiceHelper.cs
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 |
using System.Diagnostics; namespace TestProject { /// <summary> /// 윈도우즈 서비스 헬퍼 /// </summary> public static class WindowsServiceHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 윈도우즈 서비스 생성하기 - CreateWindowsService(serviceName, argumentList) /// <summary> /// 윈도우즈 서비스 생성하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <param name="argumentList">인자 리스트</param> /// <returns>처리 결과</returns> public static int CreateWindowsService(string serviceName, string argumentList) { Process process = GetProcess("sc.exe", $"create {serviceName} binPath= \"{argumentList}\""); process.Start(); process.WaitForExit(); return process.ExitCode; } #endregion #region 윈도우즈 서비스 시작하기 - StartWindowsService(serviceName) /// <summary> /// 윈도우즈 서비스 시작하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <returns>처리 결과</returns> public static int StartWindowsService(string serviceName) { Process process = GetProcess("sc.exe", $"start {serviceName}"); process.Start(); process.WaitForExit(); return process.ExitCode; } #endregion #region 윈도우즈 서비스 중단하기 - StopWindowsService(serviceName) /// <summary> /// 윈도우즈 서비스 중단하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <returns>처리 결과</returns> public static int StopWindowsService(string serviceName) { Process process = GetProcess("sc.exe", $"stop {serviceName}"); process.Start(); process.WaitForExit(); return process.ExitCode; } #endregion #region 윈도우즈 서비스 제거하기 - DeleteWindowsService(serviceName) /// <summary> /// 윈도우즈 서비스 제거하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <returns>처리 결과</returns> public static int DeleteWindowsService(string serviceName) { Process process = GetProcess("sc.exe", $"delete {serviceName}"); process.Start(); process.WaitForExit(); return process.ExitCode; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 프로세스 구하기 - GetProcess(filePath, argumentList) /// <summary> /// 프로세스 구하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <param name="argumentList">인자 리스트</param> /// <returns>프로세스</returns> private static Process GetProcess(string filePath, string argumentList) { Process process = new Process(); process.StartInfo.UseShellExecute = true; process.StartInfo.FileName = filePath; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.Verb = "runas"; process.StartInfo.Arguments = argumentList; return process; } #endregion } } |
▶ Program.cs
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 |
using System; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main(string[] argumentArray) { string serviceName = "nats01"; string argumentList = @"d:\nats\bin\gnatsd.exe --config d:\nats\config\server.conf"; int exitCode; exitCode = WindowsServiceHelper.CreateWindowsService(serviceName, argumentList); if(exitCode != 0) { Console.WriteLine("윈도우즈 서비스 생성을 실패했습니다 : {0}", exitCode); return; } exitCode = WindowsServiceHelper.StartWindowsService(serviceName); if(exitCode != 0) { Console.WriteLine("윈도우즈 서비스 시작을 실패했습니다 : {0}", exitCode); return; } exitCode = WindowsServiceHelper.StopWindowsService(serviceName); if(exitCode != 0) { Console.WriteLine("윈도우즈 서비스 중단을 실패했습니다 : {0}", exitCode); return; } exitCode = WindowsServiceHelper.DeleteWindowsService(serviceName); if(exitCode != 0) { Console.WriteLine("윈도우즈 서비스 삭제를 실패했습니다 : {0}", exitCode); return; } Console.WriteLine("작업을 성공적으로 처리했습니다."); } #endregion } } |
TestProject.zip
■ Environment 클래스의 GetCommandLineArgs 정적 메소드를 사용해 윈도우즈 서비스에 인자를 전달하는 방법을 보여준다. 1. 명령 프롬프트를 실행한다. (윈도우즈 10에서는 관리자 권한으로 실행한다)
■ NATS 서버를 윈도우즈 서비스로 실행하는 방법을 보여준다. ▶ 윈도우즈 서비스 설치하기
1 2 3 |
sc.exe create gnatsd1 binPath= "d:\NATS\Server01\Bin\gnatsd.exe --config d:\NATS\Server01\Config\server.conf" |
▶ 윈도우즈 서비스 시작하기
1 2 3 |
sc.exe start gnatsd1 |
▶ 윈도우즈 서비스 중단하기
■ 윈도우즈 서비스를 실행하는 방법을 보여준다. (인자 전달 포함) [Test.Common 프로젝트] ▶ ControllerConfiguration.cs
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 |
using System.IO; using System.Reflection; using System.Web.Hosting; namespace Test.Common { /// <summary> /// 컨트롤러 구성 /// </summary> public class ControllerConfiguration { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스명 - ServiceName /// <summary> /// 서비스명 /// </summary> public string ServiceName { get; set; } #endregion #region 서비스 설명 - ServiceDescription /// <summary> /// 서비스 설명 /// </summary> public string ServiceDescription { get; set; } #endregion #region 서비스 파일 경로 - ServiceFilePath /// <summary> /// 서비스 파일 경로 /// </summary> public string ServiceFilePath { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 로드하기 - Load(sourceDirectoryPath) /// <summary> /// 로드하기 /// </summary> /// <param name="sourceDirectoryPath">소스 디렉토리 경로</param> /// <returns>구성 인스턴스</returns> public static ControllerConfiguration Load(string sourceDirectoryPath) { string filePath = Path.Combine(sourceDirectoryPath, $"{nameof(ControllerConfiguration)}.json"); string json = File.ReadAllText(filePath); ControllerConfiguration configuration = JSONHelper.GetObject<ControllerConfiguration>(json); return configuration; } #endregion #region 로드하기 - Load(assembly) /// <summary> /// 로드하기 /// </summary> /// <param name="assembly">어셈블리</param> /// <returns>구성 인스턴스</returns> public static ControllerConfiguration Load(Assembly assembly) { string currentDirectoryPath = HostingEnvironment.ApplicationPhysicalPath != null ? Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin") : Path.GetDirectoryName(assembly.Location); string filePath = Path.Combine(currentDirectoryPath, $"{nameof(ControllerConfiguration)}.json"); string json = File.ReadAllText(filePath); ControllerConfiguration configuration = JSONHelper.GetObject<ControllerConfiguration>(json); return configuration; } #endregion } } |
▶ ServerConfiguration.cs
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 |
using System.IO; using System.Reflection; using System.Web.Hosting; namespace Test.Common { /// <summary> /// 서버 구성 /// </summary> public class ServerConfiguration { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스명 - ServiceName /// <summary> /// 서비스명 /// </summary> public string ServiceName { get; set; } #endregion #region 서비스 설명 - ServiceDescription /// <summary> /// 서비스 설명 /// </summary> public string ServiceDescription { get; set; } #endregion #region 서비스 파일 경로 - ServiceFilePath /// <summary> /// 서비스 파일 경로 /// </summary> public string ServiceFilePath { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 로드하기 - Load(sourceDirectoryPath) /// <summary> /// 로드하기 /// </summary> /// <param name="sourceDirectoryPath">소스 디렉토리 경로</param> /// <returns>구성 인스턴스</returns> public static ServerConfiguration Load(string sourceDirectoryPath) { string filePath = Path.Combine(sourceDirectoryPath, $"{nameof(ServerConfiguration)}.json"); string json = File.ReadAllText(filePath); ServerConfiguration configuration = JSONHelper.GetObject<ServerConfiguration>(json); return configuration; } #endregion #region 로드하기 - Load(assembly) /// <summary> /// 로드하기 /// </summary> /// <param name="assembly">어셈블리</param> /// <returns>구성 인스턴스</returns> public static ServerConfiguration Load(Assembly assembly) { string currentDirectoryPath = HostingEnvironment.ApplicationPhysicalPath != null ? Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin") : Path.GetDirectoryName(assembly.Location); string filePath = Path.Combine(currentDirectoryPath, $"{nameof(ServerConfiguration)}.json"); string json = File.ReadAllText(filePath); ServerConfiguration configuration = JSONHelper.GetObject<ServerConfiguration>(json); return configuration; } #endregion } } |
▶ ServiceStatus.cs
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 |
namespace Test.Common { /// <summary> /// 서비스 상태 /// </summary> public class ServiceStatus { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 설치 여부 - IsServiceInstalled /// <summary> /// 서비스 설치 여부 /// </summary> public bool IsServiceInstalled { get; set; } #endregion #region 서비스 실행 여부 - IsServerRunning /// <summary> /// 서비스 실행 여부 /// </summary> public bool IsServiceRunning { get; set; } #endregion } } |
▶ ServiceHelper.cs
■ AssemblyInstaller 클래스를 사용해 윈도우즈 서비스 설치를 취소하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System.Configuration.Install; #region 서비스 설치 취소하기 - UninstallService(serviceFilePath, argumentArray) /// <summary> /// 서비스 설치 취소하기 /// </summary> /// <param name="serviceFilePath">서비스 파일 경로</param> /// <param name="argumentArray">인자 배열</param> public void UninstallService(string serviceFilePath, string[] argumentArray) { AssemblyInstaller installer = new AssemblyInstaller(serviceFilePath, argumentArray); installer.UseNewContext = true; installer.Uninstall(null); } #endregion |
■ AssemblyInstaller 클래스를 사용해 윈도우즈 서비스를 설치하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System.Configuration.Install; #region 서비스 설치하기 - InstallService(serviceFilePath, argumentArray) /// <summary> /// 서비스 설치하기 /// </summary> /// <param name="serviceFilePath">서비스 파일 경로</param> /// <param name="argumentArray">인자 배열</param> public void InstallService(string serviceFilePath, string[] argumentArray) { AssemblyInstaller Installer = new AssemblyInstaller(serviceFilePath, argumentArray); Installer.UseNewContext = true; Installer.Install(null); Installer.Commit(null); } #endregion |
■ ServiceController 클래스 : 윈도우즈 서비스 재시작하기 ———————————————————————————————————————— using System; using System.ServiceProcess; #region 서비스 재시작하기 – RestartService(serviceName, timeOut) /// <summary> /// 서비스
■ ServiceController 클래스를 사용해 윈도우즈 서비스 설치 여부를 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
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 |
using System.ServiceProcess; #region 서비스 설치 여부 구하기 - IsServiceInstalled(serviceName) /// <summary> /// 서비스 설치 여부 구하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <returns>서비스 설치 여부</returns> public static bool IsServiceInstalled(string serviceName) { ServiceController[] serviceControllerArray = ServiceController.GetServices(); foreach(ServiceController serviceController in serviceControllerArray) { if(serviceController.ServiceName == serviceName) { return true; } } return false; } #endregion |
■ ServiceController 클래스를 사용해 윈도우즈 서비스를 중단하는 방법을 보여준다. ▶ 예제 코드 (C#)
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 |
using System; using System.ServiceProcess; #region 서비스 중단하기 - StopService(serviceName, timeOut) /// <summary> /// 서비스 중단하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <param name="timeOut">타임아웃 (밀리초)</param> public void StopService(string serviceName, int timeOut) { ServiceController serviceController = new ServiceController(serviceName); try { TimeSpan timeOutTimeSpan = TimeSpan.FromMilliseconds(timeOut); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeOutTimeSpan); } catch { } } #endregion |
■ ServiceController 클래스를 사용해 윈도우즈 서비스를 시작하는 방법을 보여준다. ▶ 예제 코드 (C#)
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 |
using System; using System.ServiceProcess; #region 서비스 시작하기 - StartService(serviceName, timeOut) /// <summary> /// 서비스 시작하기 /// </summary> /// <param name="serviceName">서비스명</param> /// <param name="timeOut">타임아웃 (밀리초)</param> public void StartService(string serviceName, int timeOut) { ServiceController serviceController = new ServiceController(serviceName); try { TimeSpan timeOutTimeSpan = TimeSpan.FromMilliseconds(timeOut); serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, timeOutTimeSpan); } catch { } } #endregion |
■ 윈도우즈 서비스 배열을 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System.ServiceProcess; ServiceController[] serviceControllerArray = ServiceController.GetServices(); foreach(ServiceController serviceController in serviceControllerArray) { if(serviceController.Status == ServiceControllerStatus.Running) { // 코드를 수행한다. } } |