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

本文介绍了一种在Windows系统中以管理员权限启动应用程序并绕过用户账户控制(UAC)的方法。通过使用C#实现的代码片段展示了如何获取当前活动会话用户、复制令牌以及以该用户身份创建新进程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using System.Security;
using System.Diagnostics;
using System.Runtime.InteropServices;


namespace Test
{
    class UserProcess
    {
        #region Structures


        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_ATTRIBUTES
        {
            public int Length;
            public IntPtr lpSecurityDescriptor;
            public bool bInheritHandle;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct STARTUPINFO
        {
            public int cb;
            public String lpReserved;
            public String lpDesktop;
            public String lpTitle;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwXCountChars;
            public uint dwYCountChars;
            public uint dwFillAttribute;
            public uint dwFlags;
            public short wShowWindow;
            public short cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public uint dwProcessId;
            public uint dwThreadId;
        }


        #endregion


        #region Enumerations


        enum TOKEN_TYPE : int
        {
            TokenPrimary = 1,
            TokenImpersonation = 2
        }


        enum SECURITY_IMPERSONATION_LEVEL : int
        {
            SecurityAnonymous = 0,
            SecurityIdentification = 1,
            SecurityImpersonation = 2,
            SecurityDelegation = 3,
        }


        enum WTSInfoClass
        {
            InitialProgram,
            ApplicationName,
            WorkingDirectory,
            OEMId,
            SessionId,
            UserName,
            WinStationName,
            DomainName,
            ConnectState,
            ClientBuildNumber,
            ClientName,
            ClientDirectory,
            ClientProductId,
            ClientHardwareId,
            ClientAddress,
            ClientDisplay,
            ClientProtocolType
        }


        #endregion


        #region Constants


        public const int TOKEN_DUPLICATE = 0x0002;
        public const uint MAXIMUM_ALLOWED = 0x2000000;
        public const int CREATE_NEW_CONSOLE = 0x00000010;


        public const int IDLE_PRIORITY_CLASS = 0x40;
        public const int NORMAL_PRIORITY_CLASS = 0x20;
        public const int HIGH_PRIORITY_CLASS = 0x80;
        public const int REALTIME_PRIORITY_CLASS = 0x100;


        #endregion


        #region Win32 API Imports


        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(IntPtr hSnapshot);


        [DllImport("kernel32.dll")]
        static extern uint WTSGetActiveConsoleSessionId();


        [DllImport("wtsapi32.dll", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        static extern bool WTSQuerySessionInformation(System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);


        [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
            String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);


        [DllImport("kernel32.dll")]
        static extern bool ProcessIdToSessionId(uint dwProcessId, ref uint pSessionId);


        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
        public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,
            int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);


        [DllImport("kernel32.dll")]
        static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);


        [DllImport("advapi32", SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);


        #endregion


        public static string GetCurrentActiveUser()
        {
            IntPtr hServer = IntPtr.Zero, state = IntPtr.Zero;
            uint bCount = 0;


            // obtain the currently active session id; every logged on user in the system has a unique session id
            uint dwSessionId = WTSGetActiveConsoleSessionId();
            string domain = string.Empty, userName = string.Empty;


            if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.DomainName, out state, out bCount))
            {
                domain = Marshal.PtrToStringAuto(state);
            }


            if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.UserName, out state, out bCount))
            {
                userName = Marshal.PtrToStringAuto(state);
            }


            return string.Format("{0}\\{1}", domain, userName);
        }


        /// <summary>
        /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt
        /// </summary>
        /// <param name="applicationName">The name of the application to launch</param>
        /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>
        /// <returns></returns>
        public static bool StartProcessAndBypassUAC(String applicationName, String command, out PROCESS_INFORMATION procInfo)
        {
            uint winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;
            procInfo = new PROCESS_INFORMATION();


            // obtain the currently active session id; every logged on user in the system has a unique session id
            uint dwSessionId = WTSGetActiveConsoleSessionId();


            // obtain the process id of the winlogon process that is running within the currently active session
            Process[] processes = Process.GetProcessesByName("winlogon");
            foreach (Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }


            // obtain a handle to the winlogon process
            hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);


            // obtain a handle to the access token of the winlogon process
            if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
            {
                CloseHandle(hProcess);
                return false;
            }


            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
            // I would prefer to not have to use a security attribute variable and to just 
            // simply pass null and inherit (by default) the security attributes
            // of the existing token. However, in C# structures are value types and therefore
            // cannot be assigned the null value.
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.Length = Marshal.SizeOf(sa);


            // copy the access token of the winlogon process; the newly created token will be a primary token
            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return false;
            }


            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
            // the window station has a desktop that is invisible and the process is incapable of receiving
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user 
            // interaction with the new process.
            STARTUPINFO si = new STARTUPINFO();
            si.cb = (int)Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop


            // flags that specify the priority and creation method of the process
            int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;


            // create a new process in the current user's logon session
            bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token
                                            applicationName,        // file to execute
                                            command,                // command line
                                            ref sa,                 // pointer to process SECURITY_ATTRIBUTES
                                            ref sa,                 // pointer to thread SECURITY_ATTRIBUTES
                                            false,                  // handles are not inheritable
                                            dwCreationFlags,        // creation flags
                                            IntPtr.Zero,            // pointer to new environment block 
                                            null,                   // name of current directory 
                                            ref si,                 // pointer to STARTUPINFO structure
                                            out procInfo            // receives information about new process
                                            );


            // invalidate the handles
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);


            return result; // return the result
        }
    }
}


<think>首先,用户的问题是:“请问如何在新应用程序中运行打开.bat文件 Windows 解决方案”。这似乎是在询问如何在Windows系统中运行打开一个.bat文件,特别是涉及到新应用程序。 我需要参考系统级指令: - 所有行内数学表达式用$...$格式。 - 独立公式用$$...$$格式。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾添加引用标识。 - 回答结构清晰,帮助用户逐步解决问题。 - 参考提供的引用内容。 提供的引用: - [^1]: 关于创建批处理文件来控制应用程序启动和窗口位置。 - [^2]: 关于.hlp文件和winhlp32.exe的问题,但似乎不直接相关。 - [^3]: 关于IDEA无法打开,通过重新下载Visual C++解决。 用户的需求是“在新应用程序中运行打开.bat文件”。这可能意味着用户想在另一个应用程序中运行.bat文件者更一般地,如何在Windows中运行.bat文件。引用[^1]提到了批处理文件,所以我可以参考那个。 关键点:用户说“在新应用程序中”,这有点模糊。可能用户想从一个新应用程序中执行.bat文件.bat文件本身启动新应用程序。从引用[^1]看,它展示了如何在批处理文件启动应用程序。 所以,我应该解释如何运行.bat文件,以及如何将.bat文件集成到其他应用程序中。 步骤: 1. **理解.bat文件**:批处理文件是包含一系列命令的文本文件,扩展名为.bat,在Windows命令提示符中运行。 2. **运行.bat文件**: - 双击.bat文件文件资源管理器中运行。 - 使用命令提示符PowerShell运行。 3. **在应用程序中运行.bat文件**:用户可能想从另一个程序(如Python脚本、Java应用等)执行.bat文件。这可以通过编程方式调用命令提示符来实现。 4. **解决方案**:基于引用[^1],我可以展示如何创建和使用批处理文件来控制应用程序启动。 结构化回答: - 介绍.bat文件。 - 解释如何运行.bat文件。 - 提供在应用程序中运行.bat文件的示例。 - 生成相关问题。 使用中文回答。 添加引用:在引用的段落末尾添加[^1]等。 生成相关问题。 参考引用[^1]的内容:它展示了批处理文件示例。 所以,我的回答应该包括: - 什么是.bat文件。 - 如何运行.bat文件。 - 如何在其他应用程序中运行.bat文件(例如,从Python调用)。 - 示例代码,如引用[^1]中的批处理文件。 - 生成相关问题。 确保回答真实可靠。</think>### 如何在新应用程序中运行打开.bat文件Windows解决方案) 在Windows系统中,.bat文件(批处理文件)是一种包含一系列命令的脚本文件,通常用于自动化任务启动应用程序。您的问题可能涉及两种场景:(1) 直接运行.bat文件启动新应用程序;(2) 从另一个应用程序(如Python、JavaC#程序)中调用.bat文件。下面我将分步骤解释解决方案,确保内容真实可靠,并基于最佳实践。 #### 步骤1: 理解.bat文件的基本运行方式 .bat文件Windows中可以直接执行,它会启动命令提示符(cmd.exe)并运行文件中的命令。如果您只想运行.bat文件启动一个新应用程序(例如,启动一个游戏工具),操作很简单: - **双击运行**:在文件资源管理器中找到.bat文件,双击即可执行。如果文件包含启动应用程序的命令(如`start "C:\Path\To\App.exe"`),它会自动打开新应用程序。 - **使用命令提示符**:打开命令提示符(按Win+R,输入`cmd`),然后导航到.bat文件所在目录,输入文件名(例如`mybatch.bat`)并按Enter。 如果.bat文件需要参数来控制应用程序行为(如窗口位置),可以参考引用[^1]中的示例,创建一个批处理文件来指定参数。例如: ```batch @echo off start "" "C:\Program Files\MyApp\app.exe" --window-position=1920,0 ``` 这段代码会启动`app.exe`,并将窗口定位在屏幕坐标(1920,0)处[^1]。 #### 步骤2: 在新应用程序中运行.bat文件(编程方式) 如果您想在另一个应用程序(如Python脚本、Java程序C#应用)中执行.bat文件,这需要调用Windows的系统命令。以下是常见编程语言的实现方法,确保使用完整路径以避免权限问题。 - **Python示例**:使用`subprocess`模块调用.bat文件。这适用于自动化任务集成到Python应用中。 ```python import subprocess # 指定.bat文件的完整路径 bat_path = r"C:\Path\To\Your\batchfile.bat" # 运行.bat文件,并等待完成(使用shell=True以处理路径空格) result = subprocess.run(bat_path, shell=True, capture_output=True, text=True) print("输出:", result.stdout) # 打印命令输出 ``` 这会在Python环境中启动.bat文件,并执行其命令,包括启动新应用程序[^1]。 - **Java示例**:使用`Runtime``ProcessBuilder`类执行.bat文件。 ```java import java.io.IOException; public class RunBat { public static void main(String[] args) { try { // 指定.bat文件路径 String batPath = "C:\\Path\\To\\Your\\batchfile.bat"; // 创建进程并执行 Process process = Runtime.getRuntime().exec(batPath); process.waitFor(); // 等待执行完成 System.out.println("批处理文件执行完毕"); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 这会在Java应用中调用.bat文件,适合桌面应用后台服务。 - **C#示例**:在.NET应用中,使用`Process.Start`方法。 ```csharp using System; using System.Diagnostics; class Program { static void Main() { // 指定.bat文件路径 string batPath = @"C:\Path\To\Your\batchfile.bat"; // 启动进程 Process.Start(new ProcessStartInfo { FileName = batPath, UseShellExecute = true // 使用系统shell执行 }); Console.WriteLine("批处理文件启动"); } } ``` 这适用于Windows窗体控制台应用,能无缝集成.bat文件[^1]。 #### 注意事项和常见问题 - **权限问题**:如果.bat文件无法运行,确保以管理员身份运行命令提示符应用程序(右键单击 > “以管理员身份运行”)。 - **路径处理**:路径中包含空格时,使用双引号包裹(如`"C:\Program Files\App\app.exe"`),避免错误。 - **错误排查**:如果.bat文件启动失败,检查命令语法依赖项(如某些应用程序需要Visual C++库,类似引用[^3]中提到的问题)。 - **安全提示**:.bat文件可能包含恶意命令,只运行来源可信的文件。在开发中,建议测试在沙箱环境中。 通过以上方法,您可以轻松在Windows中运行.bat文件,并集成到各种应用程序中。如果您遇到具体错误(如文件路径无效权限不足),请提供更多细节以便进一步帮助。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值