Search code examples
c#asp.netpsexec

PSEXEC runs successfully via command prompt but fails in ASP .Net/C#


I'm trying to run a command on remote machine using PSEXEC tool, it runs successfully using command prompt but it fails in an asp.net project showing the following output error.

PsExec v2.11 - Execute processes remotely Copyright (C) 2001-2014 Mark Russinovich Sysinternals - www.sysinternals.com

The handle is invalid.

Connecting to lnxdevx...

Starting PSEXESVC service on lnxdevx...

Connecting with PsExec service on lnxdevx...

Error deriving session key:.

Here is my sample c# code.

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.FileName = @"C:\Windows\System32\PsExec.exe";
p.StartInfo.Arguments = "-u xxxxxx -p xxxxxxxxxx \\\\lnxdevx -i -d -w \"C:\\DIRECTORY\" cmd.exe /C dir";
p.Start();
string output = p.StandardOutput.ReadToEnd();
string errormessage = p.StandardError.ReadToEnd();
p.WaitForExit();

Solution

  • The problem is that you don't have to open psexec, but cmd and from there you run psexec.

    The code you're trying to do is wrong too, you need to use

    System.Diagnostics.Process process = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe"; \\if it is in System32
    startInfo.Arguments = "psexec -u xxxxxx -p xxxxxxxxxx \\machine *your stuff*";
    process.StartInfo = startInfo;
    process.Start();
    

    I'm not testing, but I'm quite sure this will work :)