Sami Kobbi
Sami Kobbi

Reputation: 309

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

Upvotes: 2

Views: 3322

Answers (2)

Bakudan
Bakudan

Reputation: 19492

Although the accepted answer is solving the problem, there is a better solution (at least without involving cmd).

Go to the app pool -> Advanced Settings -> Section "Process Model" -> "Load User Profile".

The default is false. When you change it to true, everything should work.

A bit more of what there is (more of an interpretation, further research is needed).

  • psexec and all tools from SysInternals require EULA to be accepted. This can be solved by calling them with -accepteula see psexec at ss64
  • this should be saved in the registry. You have to have a profile for this to be read.

Based on https://nigglingaspirations.blogspot.com/2015/04/psexec-error-deriving-session-key.html

Upvotes: 0

Luis G. Lino
Luis G. Lino

Reputation: 163

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 :)

Upvotes: 2

Related Questions