57

如何EXE使用 C# 从 Windows 服务运行程序?

这是我的代码:

System.Diagnostics.Process.Start(@"E:\PROJECT XL\INI SQLLOADER\ConsoleApplication2\ConsoleApplication2\ConsoleApplication2\bin\Debug\ConsoleApplication2.exe");

当我运行此服务时,应用程序未启动。
我的代码有什么问题?

4

9 回答 9

72

这永远行不通,至少在 Windows Vista 或更高版本下不行。关键问题是您试图从 Windows 服务中执行此操作,而不是标准 Windows 应用程序。您展示的代码将在 Windows 窗体、WPF 或控制台应用程序中完美运行,但在 Windows 服务中根本无法运行。

Windows 服务无法启动其他应用程序,因为它们没有在任何特定用户的上下文中运行。与常规 Windows 应用程序不同,服务现在在隔离会话中运行,并且被禁止与用户或桌面交互。这没有为应用程序运行留下任何空间。

这些相关问题的答案中提供了更多信息:

您现在可能已经想到,解决问题的最佳方法是创建标准的 Windows 应用程序而不是服务。这些设计为由特定用户运行并与该用户的桌面相关联。这样,您可以随时使用已显示的代码运行其他应用程序。

另一种可能的解决方案是,假设您的控制台应用程序不需要任何类型的接口或输出,是指示进程不要创建窗口。这将防止 Windows 阻止创建您的进程,因为它不再请求创建控制台窗口。您可以在相关问题的答案中找到相关代码。

于 2011-03-15T05:55:09.203 回答
14

我已经尝试过这篇文章 Code Project,它对我来说工作正常。我也用过代码。文章用截图解释得很好。

我正在为这种情况添加必要的解释

您刚刚启动计算机并即将登录。当您登录时,系统会为您分配一个唯一的会话 ID。在 Windows Vista 中,操作系统为第一个登录计算机的用户分配了一个会话 ID 1。下一个要登录的用户将被分配一个会话 ID 2。依此类推。您可以从任务管理器的用户选项卡中查看分配给每个登录用户的会话 ID。 在此处输入图像描述

但是您的 Windows 服务的会话 ID 为 0。此会话与其他会话隔离。这最终会阻止 Windows 服务调用在用户会话 1 或 2 下运行的应用程序。

为了从 Windows 服务调用应用程序,您需要从作为当前登录用户的 winlogon.exe 复制控件,如下面的屏幕截图所示。 在此处输入图像描述

重要代码

// 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;
    }

 STARTUPINFO si = new STARTUPINFO();
 si.cb = (int)Marshal.SizeOf(si);

// interactive window station parameter; basically this indicates 
// that the process created can display a GUI on the desktop
si.lpDesktop = @"winsta0\default";

// 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
                            null,             // file to execute
                            applicationName,  // 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
                            );
于 2016-11-28T08:13:21.067 回答
10

您可以从 Windows 任务计划程序中使用此目的,有许多库,如TaskScheduler可以帮助您。

例如,考虑我们要安排一个将在五秒后执行一次的任务:

using (var ts = new TaskService())
        {

            var t = ts.Execute("notepad.exe")
                .Once()
                .Starting(DateTime.Now.AddSeconds(5))
                .AsTask("myTask");

        }

notepad.exe 将在五秒后执行。

有关详细信息和更多信息,请访问wiki

如果您知道您需要该程序集中的哪个类和方法,您可以像这样自己调用它:

        Assembly assembly = Assembly.LoadFrom("yourApp.exe");
        Type[] types = assembly.GetTypes();
        foreach (Type t in types)
        {
            if (t.Name == "YourClass")
            {
                MethodInfo method = t.GetMethod("YourMethod",
                BindingFlags.Public | BindingFlags.Instance);
                if (method != null)
                {
                    ParameterInfo[] parameters = method.GetParameters();
                    object classInstance = Activator.CreateInstance(t, null);

                    var result = method.Invoke(classInstance, parameters.Length == 0 ? null : parameters);
                    
                    break;
                }
            }
                         
        }
    
于 2018-07-03T14:06:11.253 回答
6

大多数赞成票的最佳答案没有错,但仍然与我要发布的相反。我说它完全可以启动一个 exe 文件,您可以在任何用户的上下文中执行此操作。从逻辑上讲,您不能拥有任何用户界面或要求用户输入...

这是我的建议:

  1. 创建一个简单的控制台应用程序,该应用程序在无需用户交互的情况下执行您的服务应在启动时立即执行的操作。我真的建议不要使用 Windows 服务项目类型,尤其是因为您(当前)不能使用 .NET Core。
  2. 添加代码以启动要从服务调用的 exe

启动示例,例如 plink.exe。你甚至可以听输出:

var psi = new ProcessStartInfo()
{
    FileName = "./Client/plink.exe", //path to your *.exe
    Arguments = "-telnet -P 23 127.0.0.1 -l myUsername -raw", //arguments
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    UseShellExecute = false,
    CreateNoWindow = true //no window, you can't show it anyway
};

var p = Process.Start(psi);
  1. 使用 NSSM(非吸吮服务管理器)将该控制台应用程序注册为服务。NSSM 可以通过命令行进行控制,并且可以显示一个 UI 来配置服务,或者您可以通过命令行对其进行配置。如果您知道该用户的登录数据,则可以在任何用户的上下文中运行该服务。

我使用了默认的 LocalSystem 帐户,而不是本地服务。它工作正常,无需输入特定用户的登录信息。如果您需要更高的权限,我什至没有勾选“允许服务与桌面交互”复选框。

允许服务与桌面交互的选项

最后,我只想说,最有趣的答案与我的答案完全相反,但我们俩都是对的,这只是你解释问题的方式:-D。如果你现在说,但你不能使用 Windows 服务项目类型 - 你可以,但我以前有这个,安装很粗略,在我找到 NSSM 之前,这可能是一种无意的黑客攻击。

于 2019-04-11T09:04:37.193 回答
2

您可以在 Windows XP 中很好地执行来自 Windows 服务的 .exe。我过去自己做过。

您需要确保已在 Windows 服务属性中选中“允许与桌面交互”选项。如果不这样做,它将不会执行。

我需要检查 Windows 7 或 Vista,因为这些版本需要额外的安全权限,因此可能会引发错误,但我很确定它可以直接或间接实现。对于 XP,我确信我自己已经完成了。

于 2012-01-09T12:57:25.217 回答
2

首先,我们将创建一个在系统帐户下运行的 Windows 服务。该服务将负责在当前活动的用户会话中生成一个交互式进程。这个新创建的进程将显示一个 UI 并以完全管理员权限运行。当第一个用户登录计算机时,该服务将被启动并运行在 Session0 中;但是,此服务产生的进程将在当前登录用户的桌面上运行。我们将此服务称为 LoaderService。

接下来,winlogon.exe 进程负责管理用户登录和注销过程。我们知道,每个登录计算机的用户都会有一个唯一的 Session ID 和一个与其 Session 相关联的对应 winlogon.exe 进程。现在,我们在上面提到,LoaderService 在 System 帐户下运行。我们还确认了计算机上的每个 winlogon.exe 进程都在系统帐户下运行。因为 System 帐户是 LoaderService 和 winlogon.exe 进程的所有者,所以我们的 LoaderService 可以复制 winlogon.exe 进程的访问令牌(和 Session ID),然后调用 Win32 API 函数 CreateProcessAsUser 启动一个进程到登录用户的当前活动会话。由于会话 ID 位于复制的 winlogon 的访问令牌内。

试试这个。 在 32 位和 64 位架构中颠覆 Vista UAC

于 2015-09-24T04:42:24.660 回答
1

您应该查看这篇文章Impact of Session 0 Isolation on Services and Drivers in Windows并下载.docx 文件并仔细阅读,这对我很有帮助。

然而,这是一个适用于我的案例的类:

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public uint dwProcessId;
        public uint dwThreadId;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    internal struct SECURITY_ATTRIBUTES
    {
        public uint nLength;
        public IntPtr lpSecurityDescriptor;
        public bool bInheritHandle;
    }


    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFO
    {
        public uint 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;

    }

    internal enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    internal enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    public static class ProcessAsUser
    {

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool CreateProcessAsUser(
            IntPtr hToken,
            string lpApplicationName,
            string lpCommandLine,
            ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            bool bInheritHandles,
            uint dwCreationFlags,
            IntPtr lpEnvironment,
            string lpCurrentDirectory,
            ref STARTUPINFO lpStartupInfo,
            out PROCESS_INFORMATION lpProcessInformation);


        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
        private static extern bool DuplicateTokenEx(
            IntPtr hExistingToken,
            uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            Int32 ImpersonationLevel,
            Int32 dwTokenType,
            ref IntPtr phNewToken);


        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenProcessToken(
            IntPtr ProcessHandle,
            UInt32 DesiredAccess,
            ref IntPtr TokenHandle);

        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool CreateEnvironmentBlock(
                ref IntPtr lpEnvironment,
                IntPtr hToken,
                bool bInherit);


        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool DestroyEnvironmentBlock(
                IntPtr lpEnvironment);

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

        private const short SW_SHOW = 5;
        private const uint TOKEN_QUERY = 0x0008;
        private const uint TOKEN_DUPLICATE = 0x0002;
        private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
        private const int GENERIC_ALL_ACCESS = 0x10000000;
        private const int STARTF_USESHOWWINDOW = 0x00000001;
        private const int STARTF_FORCEONFEEDBACK = 0x00000040;
        private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;


        private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
        {
            bool result = false;


            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
            SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
            saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
            saThread.nLength = (uint)Marshal.SizeOf(saThread);

            STARTUPINFO si = new STARTUPINFO();
            si.cb = (uint)Marshal.SizeOf(si);


            //if this member is NULL, the new process inherits the desktop
            //and window station of its parent process. If this member is
            //an empty string, the process does not inherit the desktop and
            //window station of its parent process; instead, the system
            //determines if a new desktop and window station need to be created.
            //If the impersonated user already has a desktop, the system uses the
            //existing desktop.

            si.lpDesktop = @"WinSta0\Default"; //Modify as needed
            si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
            si.wShowWindow = SW_SHOW;
            //Set other si properties as required.

            result = CreateProcessAsUser(
                token,
                null,
                cmdLine,
                ref saProcess,
                ref saThread,
                false,
                CREATE_UNICODE_ENVIRONMENT,
                envBlock,
                null,
                ref si,
                out pi);


            if (result == false)
            {
                int error = Marshal.GetLastWin32Error();
                string message = String.Format("CreateProcessAsUser Error: {0}", error);
                FilesUtilities.WriteLog(message,FilesUtilities.ErrorType.Info);

            }

            return result;
        }


        private static IntPtr GetPrimaryToken(int processId)
        {
            IntPtr token = IntPtr.Zero;
            IntPtr primaryToken = IntPtr.Zero;
            bool retVal = false;
            Process p = null;

            try
            {
                p = Process.GetProcessById(processId);
            }

            catch (ArgumentException)
            {

                string details = String.Format("ProcessID {0} Not Available", processId);
                FilesUtilities.WriteLog(details, FilesUtilities.ErrorType.Info);
                throw;
            }


            //Gets impersonation token
            retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
            if (retVal == true)
            {

                SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                sa.nLength = (uint)Marshal.SizeOf(sa);

                //Convert the impersonation token into Primary token
                retVal = DuplicateTokenEx(
                    token,
                    TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
                    ref sa,
                    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                    (int)TOKEN_TYPE.TokenPrimary,
                    ref primaryToken);

                //Close the Token that was previously opened.
                CloseHandle(token);
                if (retVal == false)
                {
                    string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
                    FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

                }

            }

            else
            {

                string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }

            //We'll Close this token after it is used.
            return primaryToken;

        }

        private static IntPtr GetEnvironmentBlock(IntPtr token)
        {

            IntPtr envBlock = IntPtr.Zero;
            bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
            if (retVal == false)
            {

                //Environment Block, things like common paths to My Documents etc.
                //Will not be created if "false"
                //It should not adversley affect CreateProcessAsUser.

                string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }
            return envBlock;
        }

        public static bool Launch(string appCmdLine /*,int processId*/)
        {

            bool ret = false;

            //Either specify the processID explicitly
            //Or try to get it from a process owned by the user.
            //In this case assuming there is only one explorer.exe

            Process[] ps = Process.GetProcessesByName("explorer");
            int processId = -1;//=processId
            if (ps.Length > 0)
            {
                processId = ps[0].Id;
            }

            if (processId > 1)
            {
                IntPtr token = GetPrimaryToken(processId);

                if (token != IntPtr.Zero)
                {

                    IntPtr envBlock = GetEnvironmentBlock(token);
                    ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
                    if (envBlock != IntPtr.Zero)
                        DestroyEnvironmentBlock(envBlock);

                    CloseHandle(token);
                }

            }
            return ret;
        }

    }

要执行,只需像这样调用:

string szCmdline = "AbsolutePathToYourExe\\ExeNameWithoutExtension";
ProcessAsUser.Launch(szCmdline);
于 2020-08-11T13:24:05.457 回答
0

我认为您正在将 .exe 复制到不同的位置。这可能是我猜的问题。当您复制 exe 时,您并没有复制它的依赖项。

因此,您可以做的是,将所有依赖的 dll 放在 GAC 中,以便任何 .net exe 都可以访问它

否则,请勿将 exe 复制到新位置。只需创建一个环境变量并在您的 c# 中调用 exe。由于路径是在环境变量中定义的,因此您的 c# 程序可以访问该 exe。

更新:

以前我在我的 c#.net 3.5 项目中遇到了一些同样的问题,我试图从 c#.net 代码运行一个 .exe 文件,而那个 exe 只不过是另一个项目 exe(我为我添加了一些支持 dll功能)以及我在 exe 应用程序中使用的那些 dll 方法。最后,我通过将该应用程序创建为同一解决方案的单独项目来解决此问题,并将该项目输出添加到我的部署项目中。根据这种情况我回答说,如果不是他想要的,那我非常抱歉。

于 2011-03-15T05:53:56.370 回答
-16

System.Diagnostics.Process.Start("Exe 名称");

于 2012-01-09T13:03:47.383 回答