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

时间:2011-03-15 05:47:25

标签: c# .net windows windows-services process.start

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

这是我的代码:

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

当我运行此服务时,应用程序无法启动 我的代码出了什么问题?

9 个答案:

答案 0 :(得分:64)

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

Windows服务无法启动其他应用程序,因为它们未在任何特定用户的上下文中运行。与常规Windows应用程序不同,services are now run in an isolated session禁止与用户或桌面交互。这使得应用程序无法运行。

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

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

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

答案 1 :(得分:7)

我试过这篇文章Code Project,它对我来说很好。 我也使用过代码。文章在截图中的解释非常好。

我正在为这个场景添加必要的解释

您刚刚启动计算机并即将登录。登录时,系统会为您分配唯一的会话ID。在Windows Vista中,操作系统会为第一个登录计算机的用户分配一个会话ID为1。下一个登录用户将被分配一个会话ID为2.依此类推。您可以从“任务管理器”的“用户”选项卡中查看分配给每个登录用户的会话ID。      enter image description here

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

要从Windows服务调用应用程序,您需要从winlogon.exe复制控件,该控件充当当前登录用户,如下面的屏幕截图所示。 enter image description here

重要代码

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

答案 2 :(得分:2)

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

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

我需要检查Windows 7或Vista,因为这些版本需要额外的安全权限,因此可能会出错,但我确信它可以直接或间接实现。对于XP我肯定是因为我自己做过。

答案 3 :(得分:2)

  

首先,我们将创建一个在该服务器下运行的Windows服务   系统帐户。这项服务将负责产生一个   当前活动用户会话中的交互式过程。这个   新创建的流程将显示一个用户界面并使用完整管理员运行   权利。当第一个用户登录到计算机时,此服务将   启动并将在Session0中运行;然而这个过程   此服务生成将在当前的桌面上运行   登录用户。我们将此服务称为LoaderService。

     

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

试试这个。 Subverting Vista UAC in Both 32 and 64 bit Architectures

答案 4 :(得分:2)

您可以从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;
                }
            }

        }

答案 5 :(得分:0)

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

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

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

更新

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

答案 6 :(得分:0)

大多数投票的最佳答案没有错,但与我发布的内容相反。我说这完全可以工作以启动exe文件,您可以在任何用户的上下文中执行此操作。从逻辑上讲,您只是没有任何用户界面或要求用户输入...

这是我的建议:

  1. 创建一个简单的控制台应用程序,该应用程序一开始就可以执行您的服务应做的事情,而无需用户干预。我真的建议不要使用Windows Service项目类型,尤其是因为(当前)您不能使用.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帐户,该帐户是默认帐户,比Local Service帐户更多。它工作正常,而无需输入特定用户的登录信息。我什至没有勾选“允许服务与桌面交互”复选框,如果需要更高的权限,则可以选择。

Option to allow service to interact with desktop

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

答案 7 :(得分:0)

您应该检查this MSDN article并下载.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);

答案 8 :(得分:-13)

System.Diagnostics.Process.Start(“Exe Name”);

相关问题