使用C#中的服务执行psexec

时间:2011-06-28 13:27:51

标签: 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?

2 个答案:

答案 0 :(得分:4)

远程运行批处理文件时,我遇到了psexec挂起的问题。 WMI怎么样?在远程计算机上运行时,这对我有用;它适用于* .bat和* .exe。您可能需要单击Project> Add Reference并在.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);

答案 1 :(得分:1)

您必须以具有psexec权限的用户身份运行Administrator远程计算机。 (-u选项的所有选项都是更改用于在远程计算机上执行命令的帐户。)将服务配置为作为具有远程计算机权限的帐户运行,或使用第二个{{ 1}}以适当的用户身份运行psexec的第一个实例。