翼度科技»论坛 编程开发 .net 查看内容

在System身份运行的.NET程序中以指定的用户身份启动可交互式进程

9

主题

9

帖子

27

积分

新手上路

Rank: 1

积分
27
今天在技术群里,石头哥向大家提了个问题:"如何在一个以System身份运行的.NET程序(Windows Services)中,以其它活动的用户身份启动可交互式进程(桌面应用程序、控制台程序、等带有UI和交互式体验的程序)"?
我以前有过类似的需求,是在GitLab流水线中运行带有UI的自动化测试程序
其中流水线是GitLab Runner执行的,而GitLab Runner则被注册为Windows服务,以System身份启动的。
然后我在流水线里,巴拉巴拉写了一大串PowerShell脚本代码,通过调用任务计划程序实现了这个需求
但我没试过在C#里实现这个功能。
对此,我很感兴趣,于是着手研究,最终捣鼓出来了。
二话不多说,上代码:
  1. using System;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. using System.Runtime.Versioning;
  6. namespace AllenCai.Windows
  7. {
  8.     /// <summary>
  9.     /// 进程工具类
  10.     /// </summary>
  11.     [SupportedOSPlatform("windows")]
  12.     public static class ProcessUtils
  13.     {
  14.         /// <summary>
  15.         /// 在当前活动的用户会话中启动进程
  16.         /// </summary>
  17.         /// <param name="fileName">程序名称或程序路径</param>
  18.         /// <param name="commandLine">命令行参数</param>
  19.         /// <param name="workDir">工作目录</param>
  20.         /// <param name="noWindow">是否无窗口</param>
  21.         /// <param name="minimize">是否最小化</param>
  22.         /// <returns></returns>
  23.         /// <exception cref="ArgumentNullException"></exception>
  24.         /// <exception cref="ApplicationException"></exception>
  25.         /// <exception cref="Win32Exception"></exception>
  26.         public static int StartProcessAsActiveUser(string fileName, string commandLine = null, string workDir = null, bool noWindow = false, bool minimize = false)
  27.         {
  28.             if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentNullException(nameof(fileName));
  29.             // 获取当前活动的控制台会话ID和安全的用户访问令牌
  30.             IntPtr userToken = GetSessionUserToken();
  31.             if (userToken == IntPtr.Zero)
  32.                 throw new ApplicationException("Failed to get user token for the active session.");
  33.             IntPtr duplicateToken = IntPtr.Zero;
  34.             IntPtr environmentBlock = IntPtr.Zero;
  35.             try
  36.             {
  37.                 String file = fileName;
  38.                 bool shell = string.IsNullOrEmpty(workDir) && (!fileName.Contains('/') && !fileName.Contains('\\'));
  39.                 if (shell)
  40.                 {
  41.                     if (string.IsNullOrWhiteSpace(workDir)) workDir = Environment.CurrentDirectory;
  42.                 }
  43.                 else
  44.                 {
  45.                     if (!Path.IsPathRooted(fileName))
  46.                     {
  47.                         file = !string.IsNullOrEmpty(workDir) ? Path.Combine(workDir, fileName).GetFullPath() : fileName.GetFullPath();
  48.                     }
  49.                     if (string.IsNullOrWhiteSpace(workDir)) workDir = Path.GetDirectoryName(file);
  50.                 }
  51.                 if (string.IsNullOrWhiteSpace(commandLine)) commandLine = "";
  52.                 // 复制令牌
  53.                 SecurityAttributes sa = new SecurityAttributes();
  54.                 sa.Length = Marshal.SizeOf(sa);
  55.                 if (!DuplicateTokenEx(userToken, MAXIMUM_ALLOWED, ref sa, SecurityImpersonationLevel.SecurityIdentification, TokenType.TokenPrimary, out duplicateToken))
  56.                     throw new ApplicationException("Could not duplicate token.");
  57.                 // 创建环境块(检索该用户的环境变量)
  58.                 if (!CreateEnvironmentBlock(out environmentBlock, duplicateToken, false))
  59.                     throw new ApplicationException("Could not create environment block.");
  60.                 // 启动信息
  61.                 ProcessStartInfo psi = new ProcessStartInfo
  62.                 {
  63.                     UseShellExecute = shell,
  64.                     FileName = $"{file} {commandLine}", //解决带参数的进程起不来或者起来的进程没有参数的问题
  65.                     Arguments = commandLine,
  66.                     WorkingDirectory = workDir,
  67.                     RedirectStandardError = false,
  68.                     RedirectStandardOutput = false,
  69.                     RedirectStandardInput = false,
  70.                     CreateNoWindow = noWindow,
  71.                     WindowStyle = minimize ? ProcessWindowStyle.Minimized : ProcessWindowStyle.Normal
  72.                 };
  73.                 // 在指定的用户会话中创建进程
  74.                 SecurityAttributes saProcessAttributes = new SecurityAttributes();
  75.                 SecurityAttributes saThreadAttributes = new SecurityAttributes();
  76.                 CreateProcessFlags createProcessFlags = (noWindow ? CreateProcessFlags.CREATE_NO_WINDOW : CreateProcessFlags.CREATE_NEW_CONSOLE) | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT;
  77.                 bool success = CreateProcessAsUser(duplicateToken, null, $"{file} {commandLine}", ref saProcessAttributes, ref saThreadAttributes, false, createProcessFlags, environmentBlock, null, ref psi, out ProcessInformation pi);
  78.                 if (!success)
  79.                 {
  80.                     throw new Win32Exception(Marshal.GetLastWin32Error());
  81.                     //throw new ApplicationException("Could not create process as user.");
  82.                 }
  83.                 return pi.dwProcessId;
  84.             }
  85.             finally
  86.             {
  87.                 // 清理资源
  88.                 if (userToken != IntPtr.Zero) CloseHandle(userToken);
  89.                 if (duplicateToken != IntPtr.Zero) CloseHandle(duplicateToken);
  90.                 if (environmentBlock != IntPtr.Zero) DestroyEnvironmentBlock(environmentBlock);
  91.             }
  92.         }
  93.         /// <summary>
  94.         /// 获取活动会话的用户访问令牌
  95.         /// </summary>
  96.         /// <exception cref="Win32Exception"></exception>
  97.         private static IntPtr GetSessionUserToken()
  98.         {
  99.             // 获取当前活动的控制台会话ID
  100.             uint sessionId = WTSGetActiveConsoleSessionId();
  101.             // 获取活动会话的用户访问令牌
  102.             bool success = WTSQueryUserToken(sessionId, out IntPtr hToken);
  103.             // 如果失败,则从会话列表中获取第一个活动的会话ID,并再次尝试获取用户访问令牌
  104.             if (!success)
  105.             {
  106.                 sessionId = GetFirstActiveSessionOfEnumerateSessions();
  107.                 success = WTSQueryUserToken(sessionId, out hToken);
  108.                 if (!success)
  109.                     throw new Win32Exception(Marshal.GetLastWin32Error());
  110.             }
  111.             return hToken;
  112.         }
  113.         /// <summary>
  114.         /// 枚举所有用户会话,获取第一个活动的会话ID
  115.         /// </summary>
  116.         private static uint GetFirstActiveSessionOfEnumerateSessions()
  117.         {
  118.             IntPtr pSessionInfo = IntPtr.Zero;
  119.             try
  120.             {
  121.                 Int32 sessionCount = 0;
  122.                 // 枚举所有用户会话
  123.                 if (WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref pSessionInfo, ref sessionCount) != 0)
  124.                 {
  125.                     Int32 arrayElementSize = Marshal.SizeOf(typeof(WtsSessionInfo));
  126.                     IntPtr current = pSessionInfo;
  127.                     for (Int32 i = 0; i < sessionCount; i++)
  128.                     {
  129.                         WtsSessionInfo si = (WtsSessionInfo)Marshal.PtrToStructure(current, typeof(WtsSessionInfo));
  130.                         current += arrayElementSize;
  131.                         if (si.State == WtsConnectStateClass.WTSActive)
  132.                         {
  133.                             return si.SessionID;
  134.                         }
  135.                     }
  136.                 }
  137.                 return uint.MaxValue;
  138.             }
  139.             finally
  140.             {
  141.                 WTSFreeMemory(pSessionInfo);
  142.                 CloseHandle(pSessionInfo);
  143.             }
  144.         }
  145.         /// <summary>
  146.         /// 以指定用户的身份启动进程
  147.         /// </summary>
  148.         [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  149.         private static extern bool CreateProcessAsUser(
  150.             IntPtr hToken,
  151.             string lpApplicationName,
  152.             string lpCommandLine,
  153.             ref SecurityAttributes lpProcessAttributes,
  154.             ref SecurityAttributes lpThreadAttributes,
  155.             bool bInheritHandles,
  156.             CreateProcessFlags dwCreationFlags,
  157.             IntPtr lpEnvironment,
  158.             string lpCurrentDirectory,
  159.             ref ProcessStartInfo lpStartupInfo,
  160.             out ProcessInformation lpProcessInformation
  161. );
  162.         /// <summary>
  163.         /// 获取当前活动的控制台会话ID
  164.         /// </summary>
  165.         [DllImport("kernel32.dll", SetLastError = true)]
  166.         private static extern uint WTSGetActiveConsoleSessionId();
  167.         /// <summary>
  168.         /// 枚举所有用户会话
  169.         /// </summary>
  170.         [DllImport("wtsapi32.dll", SetLastError = true)]
  171.         private static extern int WTSEnumerateSessions(IntPtr hServer, int reserved, int version, ref IntPtr ppSessionInfo, ref int pCount);
  172.         /// <summary>
  173.         /// 获取活动会话的用户访问令牌
  174.         /// </summary>
  175.         [DllImport("wtsapi32.dll", SetLastError = true)]
  176.         private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr phToken);
  177.         /// <summary>
  178.         /// 复制访问令牌
  179.         /// </summary>
  180.         [DllImport("advapi32.dll", SetLastError = true)]
  181.         private static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, ref SecurityAttributes lpTokenAttributes, SecurityImpersonationLevel impersonationLevel, TokenType tokenType, out IntPtr phNewToken);
  182.         /// <summary>
  183.         /// 创建环境块(检索指定用户的环境)
  184.         /// </summary>
  185.         [DllImport("userenv.dll", SetLastError = true)]
  186.         private static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
  187.         /// <summary>
  188.         /// 释放环境块
  189.         /// </summary>
  190.         [DllImport("userenv.dll", SetLastError = true)]
  191.         private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);
  192.         [DllImport("wtsapi32.dll", SetLastError = false)]
  193.         private static extern void WTSFreeMemory(IntPtr memory);
  194.         [DllImport("kernel32.dll", SetLastError = true)]
  195.         private static extern bool CloseHandle(IntPtr hObject);
  196.         [StructLayout(LayoutKind.Sequential)]
  197.         private struct WtsSessionInfo
  198.         {
  199.             public readonly uint SessionID;
  200.             [MarshalAs(UnmanagedType.LPStr)]
  201.             public readonly string pWinStationName;
  202.             public readonly WtsConnectStateClass State;
  203.         }
  204.         [StructLayout(LayoutKind.Sequential)]
  205.         private struct SecurityAttributes
  206.         {
  207.             public int Length;
  208.             public IntPtr SecurityDescriptor;
  209.             public bool InheritHandle;
  210.         }
  211.         [StructLayout(LayoutKind.Sequential)]
  212.         private struct ProcessInformation
  213.         {
  214.             public IntPtr hProcess;
  215.             public IntPtr hThread;
  216.             public int dwProcessId;
  217.             public int dwThreadId;
  218.         }
  219.         private const uint TOKEN_DUPLICATE = 0x0002;
  220.         private const uint MAXIMUM_ALLOWED = 0x2000000;
  221.         private const uint STARTF_USESHOWWINDOW = 0x00000001;
  222.         /// <summary>
  223.         /// Process Creation Flags。<br/>
  224.         /// More:https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags
  225.         /// </summary>
  226.         [Flags]
  227.         private enum CreateProcessFlags : uint
  228.         {
  229.             DEBUG_PROCESS = 0x00000001,
  230.             DEBUG_ONLY_THIS_PROCESS = 0x00000002,
  231.             CREATE_SUSPENDED = 0x00000004,
  232.             DETACHED_PROCESS = 0x00000008,
  233.             /// <summary>
  234.             /// The new process has a new console, instead of inheriting its parent's console (the default). For more information, see Creation of a Console. <br />
  235.             /// This flag cannot be used with <see cref="DETACHED_PROCESS"/>.
  236.             /// </summary>
  237.             CREATE_NEW_CONSOLE = 0x00000010,
  238.             NORMAL_PRIORITY_CLASS = 0x00000020,
  239.             IDLE_PRIORITY_CLASS = 0x00000040,
  240.             HIGH_PRIORITY_CLASS = 0x00000080,
  241.             REALTIME_PRIORITY_CLASS = 0x00000100,
  242.             CREATE_NEW_PROCESS_GROUP = 0x00000200,
  243.             /// <summary>
  244.             /// If this flag is set, the environment block pointed to by lpEnvironment uses Unicode characters. Otherwise, the environment block uses ANSI characters.
  245.             /// </summary>
  246.             CREATE_UNICODE_ENVIRONMENT = 0x00000400,
  247.             CREATE_SEPARATE_WOW_VDM = 0x00000800,
  248.             CREATE_SHARED_WOW_VDM = 0x00001000,
  249.             CREATE_FORCEDOS = 0x00002000,
  250.             BELOW_NORMAL_PRIORITY_CLASS = 0x00004000,
  251.             ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000,
  252.             INHERIT_PARENT_AFFINITY = 0x00010000,
  253.             INHERIT_CALLER_PRIORITY = 0x00020000,
  254.             CREATE_PROTECTED_PROCESS = 0x00040000,
  255.             EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
  256.             PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000,
  257.             PROCESS_MODE_BACKGROUND_END = 0x00200000,
  258.             CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
  259.             CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
  260.             CREATE_DEFAULT_ERROR_MODE = 0x04000000,
  261.             /// <summary>
  262.             /// The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set. <br />
  263.             /// This flag is ignored if the application is not a console application, or if it is used with either <see cref="CREATE_NEW_CONSOLE"/> or <see cref="DETACHED_PROCESS"/>.
  264.             /// </summary>
  265.             CREATE_NO_WINDOW = 0x08000000,
  266.             PROFILE_USER = 0x10000000,
  267.             PROFILE_KERNEL = 0x20000000,
  268.             PROFILE_SERVER = 0x40000000,
  269.             CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000,
  270.         }
  271.         private enum WtsConnectStateClass
  272.         {
  273.             WTSActive,
  274.             WTSConnected,
  275.             WTSConnectQuery,
  276.             WTSShadow,
  277.             WTSDisconnected,
  278.             WTSIdle,
  279.             WTSListen,
  280.             WTSReset,
  281.             WTSDown,
  282.             WTSInit
  283.         }
  284.         private enum SecurityImpersonationLevel
  285.         {
  286.             SecurityAnonymous,
  287.             SecurityIdentification,
  288.             SecurityImpersonation,
  289.             SecurityDelegation
  290.         }
  291.         private enum TokenType
  292.         {
  293.             TokenPrimary = 1,
  294.             TokenImpersonation
  295.         }
  296.     }
  297. }
复制代码
用法:
  1. ProcessUtils.StartProcessAsActiveUser("ping.exe", "www.baidu.com -t");
  2. ProcessUtils.StartProcessAsActiveUser("notepad.exe");
  3. ProcessUtils.StartProcessAsActiveUser("C:\\Windows\\System32\\notepad.exe");
复制代码
在 Windows 7~11、Windows Server 2016~2022 操作系统,测试通过。

来源:https://www.cnblogs.com/VAllen/p/18257879/in-dotnet-program-run-as-system-to-start-an-interactive-process-as-the-specified-user
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具