c# - 在 C# 中使用服务执行 psexec

标签 c# windows-services visual-studio-2005

我需要在远程计算机上执行一个程序,所以我创建了一个服务来调用psexec(使用该服务很重要)。但是,此服务无法调用 psexec。

代码如下:

            String cmd = "", arguments = "";
            cmd = @"C:\PsTools\psexec.exe";

            arguments = @"\\remoteComputer -u "user" -p "password" "C:\program.exe"";

            Process process = new Process();
            process.StartInfo.FileName = cmd;
            process.StartInfo.Arguments = arguments;

            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            process.Start();
            result = process.StandardOutput.ReadToEnd();
            sError = process.StandardError.ReadToEnd();

            result += "Program has finished its execution";

有谁知道为什么服务不能调用 psexec?

最佳答案

远程运行批处理文件时,我也遇到了 psexec 挂起的问题。 WMI 怎么样?在远程计算机上运行某些东西时,这对我有用;它也适用于 *.bat 和 *.exe。您可能需要单击“项目”>“添加引用”并在 .NET 选项卡上选择“System.Management”——在我手动添加之前,VS 2010 中不存在该引用。

        System.Management.ConnectionOptions connOptions =
            new System.Management.ConnectionOptions();

        connOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;
        connOptions.EnablePrivileges = true;

        string compName = "RemoteComputerName";
        System.Management.ManagementScope manScope =
            new System.Management.ManagementScope(
                String.Format(@"\\{0}\ROOT\CIMV2", compName), connOptions);
        manScope.Connect();

        System.Management.ObjectGetOptions objectGetOptions =
            new System.Management.ObjectGetOptions();

        System.Management.ManagementPath managementPath =
            new System.Management.ManagementPath("Win32_Process");

        System.Management.ManagementClass processClass =
            new System.Management.ManagementClass(manScope, managementPath, objectGetOptions);

        System.Management.ManagementBaseObject inParams =
            processClass.GetMethodParameters("Create");

        inParams["CommandLine"] = @"c:\MyBatchFile.bat";

        System.Management.ManagementBaseObject outParams =
            processClass.InvokeMethod("Create", inParams, null);

关于c# - 在 C# 中使用服务执行 psexec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6507196/

相关文章:

c# - 自动化 Windows 服务部署的最佳方式是什么?

c# - 尝试停止 C# Windows 服务时拒绝访问

asp.net - 在 VS 2005 中启动调试时 w3wp 崩溃

c# - 在运行时更改内部表示

c# - MongoDB C# 驱动程序 2.0 : How to get the result from MapReduceAsync

azure - 无法通过 Azure VM 中运行的 Windows 服务在 Azure 文件共享中创建新文件夹

powershell - 从 Powershell 运行 NServiceBusHost.exe

c++ - 想在某个未知系统上运行程序

c# - 如何使用 Orderby 创建动态 linq 查询?

c# - try catch 并重新抛出异常