在window service中调用外部exe或.bat等

来源:互联网 发布:fisher 出现奇异矩阵 编辑:程序博客网 时间:2024/05/24 07:44
windows servicesession

在您的服务程序中直接调用:UserProcess.StartProcessAndBypassUAC("your appPath","parameters",processInfo)


[csharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6.   
  7. using System.Security;  
  8. using System.Diagnostics;  
  9. using System.Runtime.InteropServices;  
  10.   
  11.   
  12. namespace Test  
  13. {  
  14.     class UserProcess  
  15.     {  
  16.         #region Structures  
  17.   
  18.   
  19.         [StructLayout(LayoutKind.Sequential)]  
  20.         public struct SECURITY_ATTRIBUTES  
  21.         {  
  22.             public int Length;  
  23.             public IntPtr lpSecurityDescriptor;  
  24.             public bool bInheritHandle;  
  25.         }  
  26.   
  27.   
  28.         [StructLayout(LayoutKind.Sequential)]  
  29.         public struct STARTUPINFO  
  30.         {  
  31.             public int cb;  
  32.             public String lpReserved;  
  33.             public String lpDesktop;  
  34.             public String lpTitle;  
  35.             public uint dwX;  
  36.             public uint dwY;  
  37.             public uint dwXSize;  
  38.             public uint dwYSize;  
  39.             public uint dwXCountChars;  
  40.             public uint dwYCountChars;  
  41.             public uint dwFillAttribute;  
  42.             public uint dwFlags;  
  43.             public short wShowWindow;  
  44.             public short cbReserved2;  
  45.             public IntPtr lpReserved2;  
  46.             public IntPtr hStdInput;  
  47.             public IntPtr hStdOutput;  
  48.             public IntPtr hStdError;  
  49.         }  
  50.   
  51.   
  52.         [StructLayout(LayoutKind.Sequential)]  
  53.         public struct PROCESS_INFORMATION  
  54.         {  
  55.             public IntPtr hProcess;  
  56.             public IntPtr hThread;  
  57.             public uint dwProcessId;  
  58.             public uint dwThreadId;  
  59.         }  
  60.  
  61.  
  62.         #endregion  
  63.  
  64.  
  65.         #region Enumerations  
  66.   
  67.   
  68.         enum TOKEN_TYPE : int  
  69.         {  
  70.             TokenPrimary = 1,  
  71.             TokenImpersonation = 2  
  72.         }  
  73.   
  74.   
  75.         enum SECURITY_IMPERSONATION_LEVEL : int  
  76.         {  
  77.             SecurityAnonymous = 0,  
  78.             SecurityIdentification = 1,  
  79.             SecurityImpersonation = 2,  
  80.             SecurityDelegation = 3,  
  81.         }  
  82.   
  83.   
  84.         enum WTSInfoClass  
  85.         {  
  86.             InitialProgram,  
  87.             ApplicationName,  
  88.             WorkingDirectory,  
  89.             OEMId,  
  90.             SessionId,  
  91.             UserName,  
  92.             WinStationName,  
  93.             DomainName,  
  94.             ConnectState,  
  95.             ClientBuildNumber,  
  96.             ClientName,  
  97.             ClientDirectory,  
  98.             ClientProductId,  
  99.             ClientHardwareId,  
  100.             ClientAddress,  
  101.             ClientDisplay,  
  102.             ClientProtocolType  
  103.         }  
  104.  
  105.  
  106.         #endregion  
  107.  
  108.  
  109.         #region Constants  
  110.   
  111.   
  112.         public const int TOKEN_DUPLICATE = 0x0002;  
  113.         public const uint MAXIMUM_ALLOWED = 0x2000000;  
  114.         public const int CREATE_NEW_CONSOLE = 0x00000010;  
  115.   
  116.   
  117.         public const int IDLE_PRIORITY_CLASS = 0x40;  
  118.         public const int NORMAL_PRIORITY_CLASS = 0x20;  
  119.         public const int HIGH_PRIORITY_CLASS = 0x80;  
  120.         public const int REALTIME_PRIORITY_CLASS = 0x100;  
  121.  
  122.  
  123.         #endregion  
  124.  
  125.  
  126.         #region Win32 API Imports  
  127.   
  128.   
  129.         [DllImport("kernel32.dll", SetLastError = true)]  
  130.         private static extern bool CloseHandle(IntPtr hSnapshot);  
  131.   
  132.   
  133.         [DllImport("kernel32.dll")]  
  134.         static extern uint WTSGetActiveConsoleSessionId();  
  135.   
  136.   
  137.         [DllImport("wtsapi32.dll", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]  
  138.         static extern bool WTSQuerySessionInformation(System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);  
  139.   
  140.   
  141.         [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]  
  142.         public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,  
  143.             ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,  
  144.             String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);  
  145.   
  146.   
  147.         [DllImport("kernel32.dll")]  
  148.         static extern bool ProcessIdToSessionId(uint dwProcessId, ref uint pSessionId);  
  149.   
  150.   
  151.         [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]  
  152.         public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,  
  153.             ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,  
  154.             int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);  
  155.   
  156.   
  157.         [DllImport("kernel32.dll")]  
  158.         static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);  
  159.   
  160.   
  161.         [DllImport("advapi32", SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]  
  162.         static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);  
  163.  
  164.  
  165.         #endregion  
  166.   
  167.   
  168.         public static string GetCurrentActiveUser()  
  169.         {  
  170.             IntPtr hServer = IntPtr.Zero, state = IntPtr.Zero;  
  171.             uint bCount = 0;  
  172.   
  173.   
  174.             // obtain the currently active session id; every logged on user in the system has a unique session id  
  175.             uint dwSessionId = WTSGetActiveConsoleSessionId();  
  176.             string domain = string.Empty, userName = string.Empty;  
  177.   
  178.   
  179.             if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.DomainName, out state, out bCount))  
  180.             {  
  181.                 domain = Marshal.PtrToStringAuto(state);  
  182.             }  
  183.   
  184.   
  185.             if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.UserName, out state, out bCount))  
  186.             {  
  187.                 userName = Marshal.PtrToStringAuto(state);  
  188.             }  
  189.   
  190.   
  191.             return string.Format("{0}\\{1}", domain, userName);  
  192.         }  
  193.   
  194.   
  195.         /// <summary>  
  196.         /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt  
  197.         /// </summary>  
  198.         /// <param name="applicationName">The name of the application to launch</param>  
  199.         /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>  
  200.         /// <returns></returns>  
  201.         public static bool StartProcessAndBypassUAC(String applicationName, String command, out PROCESS_INFORMATION procInfo)  
  202.         {  
  203.             uint winlogonPid = 0;  
  204.             IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;  
  205.             procInfo = new PROCESS_INFORMATION();  
  206.   
  207.   
  208.             // obtain the currently active session id; every logged on user in the system has a unique session id  
  209.             uint dwSessionId = WTSGetActiveConsoleSessionId();  
  210.   
  211.   
  212.             // obtain the process id of the winlogon process that is running within the currently active session  
  213.             Process[] processes = Process.GetProcessesByName("winlogon");  
  214.             foreach (Process p in processes)  
  215.             {  
  216.                 if ((uint)p.SessionId == dwSessionId)  
  217.                 {  
  218.                     winlogonPid = (uint)p.Id;  
  219.                 }  
  220.             }  
  221.   
  222.   
  223.             // obtain a handle to the winlogon process  
  224.             hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);  
  225.   
  226.   
  227.             // obtain a handle to the access token of the winlogon process  
  228.             if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))  
  229.             {  
  230.                 CloseHandle(hProcess);  
  231.                 return false;  
  232.             }  
  233.   
  234.   
  235.             // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser  
  236.             // I would prefer to not have to use a security attribute variable and to just   
  237.             // simply pass null and inherit (by default) the security attributes  
  238.             // of the existing token. However, in C# structures are value types and therefore  
  239.             // cannot be assigned the null value.  
  240.             SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();  
  241.             sa.Length = Marshal.SizeOf(sa);  
  242.   
  243.   
  244.             // copy the access token of the winlogon process; the newly created token will be a primary token  
  245.             if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))  
  246.             {  
  247.                 CloseHandle(hProcess);  
  248.                 CloseHandle(hPToken);  
  249.                 return false;  
  250.             }  
  251.   
  252.   
  253.             // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning  
  254.             // the window station has a desktop that is invisible and the process is incapable of receiving  
  255.             // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user   
  256.             // interaction with the new process.  
  257.             STARTUPINFO si = new STARTUPINFO();  
  258.             si.cb = (int)Marshal.SizeOf(si);  
  259.             si.lpDesktop = @"winsta0\default"// interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop  
  260.   
  261.   
  262.             // flags that specify the priority and creation method of the process  
  263.             int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;  
  264.   
  265.   
  266.             // create a new process in the current user's logon session  
  267.             bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token  
  268.                                             applicationName,        // file to execute  
  269.                                             command,                // command line  
  270.                                             ref sa,                 // pointer to process SECURITY_ATTRIBUTES  
  271.                                             ref sa,                 // pointer to thread SECURITY_ATTRIBUTES  
  272.                                             false,                  // handles are not inheritable  
  273.                                             dwCreationFlags,        // creation flags  
  274.                                             IntPtr.Zero,            // pointer to new environment block   
  275.                                             null,                   // name of current directory   
  276.                                             ref si,                 // pointer to STARTUPINFO structure  
  277.                                             out procInfo            // receives information about new process  
  278.                                             );  
  279.   
  280.   
  281.             // invalidate the handles  
  282.             CloseHandle(hProcess);  
  283.             CloseHandle(hPToken);  
  284.             CloseHandle(hUserTokenDup);  
  285.   
  286.   
  287.             return result; // return the result  
  288.         }  
  289.     }  
  290. }  
0 0