Process standard output cannot be captured? - c#

I am launching a process and attempting to read the StdOut... I am very familiar with the normal way of launching a process, redirecting, and capturing the output.
However, I have run across an app which I can launch manually at the command prompt and see output in the console, but does not provide any output on the StdOut or StdErr streams. I have attempted launching cmd.exe first and I am able to capture the Output from cmd.exe, but not this process when launched that way either.
To be more clear, when I run app.exe manually, I see this on the console:
Trying to connect to VP
Trying to connect to VP
When I launch it from System.Diagnostics.Process directly:
[blank]
When I launch it from System.Diagnostics.Process via cmd.exe:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
Again, the class I am using to do this runs many process and has only has an issue getting the output with this app.exe, so this is not a "hey maybe try redirecting the standard output" type of problem. I know that works in my implementation.
Ideas? I've simply never encountered this before.. How can a process put something on the console window when running manually, but not when running via the Process object?
Here's my code:
process = new Process();
process.StartInfo.FileName = f.FullName;
process.StartInfo.Arguments = arguments;
process.StartInfo.WorkingDirectory = workingDir;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.OutputDataReceived += p_OutputDataReceived;
process.ErrorDataReceived += p_ErrorDataReceived;
if (!process.Start())
{
throw new Exception("Failed to start [" + f.Name + "]. Exit code " + process.ExitCode);
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
processRunning = true;
process.WaitForExit();
exitCode = process.ExitCode;

Related

process.start() not working when not in debug mode. Works fine when debugging

I have a pretty simple C# program that needs to silently uninstall an old product. So I set up a process and run it with the right parameters and when I step through the code it works fine every time. When I run it from the command line it fails every time. I'm capturing StandardOut and StandardError and StandardOut just contains the text:
This action is only valid for products that are currently installed.
If I then immediately run it in debug mode it works fine so it's clearly not true that the product isn't installed.
Here's the code:
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = processToRun;
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
File.WriteAllText("stdout.txt", output);
string err = process.StandardError.ReadToEnd();
File.WriteAllText("stderr.txt", err);
process.WaitForExit();
And here are the values of:
StartInfo.FileName = "C:\Program Files (x86)\InstallShield Installation Information{325FAC03-900A-4BB2-B45E-1D0EB4D414BE}\setup.exe"
StartInfo.args = /s /f1"C:\Users\User\CommonCustomActions\Uninstall 5.0.0-5.3.2\Uninstall 5.0.0-5.3.2\bin\Debug\Uninstall response files\5.2.1\UNINST-5.2.1.iss"
Any ideas?
p.s. The original installation was built as an InstallShield InstallScript MSI project which is why I need to pass the "response file"

Issue executing command line command in .NET c#

Attempting to run ntdsutil from a C# executable and encountering an error. In case anyone is wondering, this is for a automated auditing process as part of a managed service provider - not trying to create a trojan/malware.
The command is: ntdsutil "ac i ntds" "ifm" "create full c:\audit" q q
This is Windows server specific, am running on Windows 2016.
I am using System.Diagnostics.Process and have tried various combinations of properties but getting same result. The following is an example, there is a standard output redirect so can see results of execution:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = #"C:\Windows\System32\ntdsutil.exe";
startInfo.Arguments = "\"ac i ntds\" \"ifm\" \"create full c:\\audit\" q q";
//Set output of program to be written to process output stream
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError= true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
// Get program output
string strOutput = process.StandardOutput.ReadToEnd();
//Wait for process to finish
process.WaitForExit();
File.WriteAllText("out.txt", strOutput);
The output looks like this:
C:\Windows\System32\ntdsutil.exe: ifm
ifm: create full c:\audit
error 0x80042302(A Volume Shadow Copy Service component encountered an unexpected error. Check the Application event log for more information.)
ifm: q
C:\Windows\System32\ntdsutil.exe: q
Have checked event logs as mention (nothing obvious) and done various searches on error but nothing useful appears. Running the command on command line works fine.
It is running a Administrator level user. Is it possible related to app.manifest priveleges?
Any help is appreciated.

Telnet from command line doesn't work

I want to open Telnet session from command line via .NET.
This command works fine manually:
telnet towel.blinkenlights.nl
So i try to open it via .NET
Process process = new Process();
process.StartInfo.FileName = #"C:\windows\system32\cmd.exe";
process.StartInfo.Arguments = "telnet towel.blinkenlights.nl";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit();
I am using Wireshark to check if this start the traffic and here it seems that nothing happen and i cannot see any Telnet traffic.
If you use ProcessWindowStyle.Normal instead you would see you are not actually executing telnet. You must add the "/C" parameter if you want the CMD window to close after finishing or "/K" if you want it to remain open.
Process process = new Process();
process.StartInfo.FileName = #"C:\windows\system32\cmd.exe";
process.StartInfo.Arguments = "/k telnet towel.blinkenlights.nl";
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.Start();
process.WaitForExit();
After you get the behavior you want, then of course switch back to Hidden.

How to end a ruby script in a process in C# application or in general how to end a process?

I have a ruby script which I am trying to execute using Process from my program. After certain event, I want to stop its execution. I tried sending the ctrl + c using the solution provided in the quetsion How do I send ctrl+c to a process in c#? however its not working for me. Can anyone provide better solution?
Below is the code:
string command = #"/c ruby C:\MyRubyProgram GetThis GetThat";
ProcessStartInfo start_info = new ProcessStartInfo("cmd", command);
start_info.UseShellExecute = false;
start_info.RedirectStandardOutput = true;
start_info.RedirectStandardInput=true;
Process process = new Process();
process.StartInfo = start_info;
process.Start();
process.WaitForExit();
process.StandardInput.WriteLine("\x3");
process.StandardInput.Close();
Console.Write(process.StandardOutput.ReadToEnd());
Why not process.Kill() ? It should help..
you can use this code to kill the process. When it is finished.
process.WaitForExit();

problems with stdout and psexec.exe from sysinternals

i have searched and read about issues with psexec.exe from sysinternals not working properly with c# and stdout. i am now trying to figure out how to just call a batch file that has the following instead of using System.Diagnostics.Process to call psexec:
test.bat contains the following line:
psexec.exe \\hostname -u user -p password ipconfig /all >c:\test.txt
test.txt will be saved on the host where i am running my c sharp app and executing psexec.
when i execute the following:
System.Diagnostics.Process psexec_run = new System.Diagnostics.Process();
psexec_run.StartInfo.FileName = "cmd.exe";
psexec_run.StartInfo.Arguments = #"/c """ + cur_dir + #"\test\test.bat""";
psexec_run.StartInfo.UseShellExecute = false;
psexec_run.Start();
psexec_run.WaitForExit();
i see the cmd window pop up and it runs something but not sure what and goes away.
if i execute the following:
System.Diagnostics.Process psexec_run = new System.Diagnostics.Process();
psexec_run.StartInfo.FileName = cur_dir + "\\test\\psexec.exe";
psexec_run.StartInfo.Arguments = #"\\hostname -u user -p password ipconfig /all";
psexec_run.StartInfo.UseShellExecute = false;
psexec_run.Start();
psexec_run.WaitForExit();
then i see the command window open and it runs psexec which takes quite a few secs and i quickly see my output i need, but i have no way of capturing the output or writing it to a file.
i guess my issue now is since psexec will not work with stdout how can i capture the output from the psexec command to write it to a file???
see the following link for the issues with psexec, the last reply on this url mentioned a way to write the process output to a file without using stdout, i'm newbie to c# i can't figure out how to write process output without use stdout :(
http://forum.sysinternals.com/psexec-fails-to-capture-stdout-when-launched-in-c_topic19333.html
based on response below i tried the following:
ProcessStartInfo psi = new ProcessStartInfo(cur_dir + "\\test\\psexec.exe", #"\\hostname -u user -p password ipconfig /all");
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
StreamReader myStreamReader = p.StandardOutput;
// Read the standard output of the spawned process.
string sOutput = myStreamReader.ReadToEnd();
i did ReadToEnd so i would make sure it got all the output, it DID NOT!! for some reason it only go the first line of ipconfig output that was it. Also the cmd window it opened up never closed for some reason. even with CreateNoWindow=true the code just hangs. so again something is wrong with psexec and stdout i think?? as i can run this code just fine using ipconfig /all command on the local host and not use psexec...
again i am looking to avoid stdout and somehow find a way to get the output from this command or unless there is something else i'm over looking? also, not to make more work for anyone, but if you d/l psexec.exe from sysinternals and test it with a command on a remote host you will see. i have spent 2 days on this one :( trying to figure out how to use psexec or find some other quick method to execute remote command on a host and get ouptput.
UPDATE:
i gave up on psexec in c# code, i saw many posts about psexec eating the output, having a child window process ,etcc
until my head hurt :) so i am trying to run a batch file and output to a file and it's not making sense...
i have a batch file test.bat with the following
psexec.exe \\\hostname -u name -p password ipconfig /all >c:\test.txt
when i run the following code:
ProcessStartInfo psi = new ProcessStartInfo(cur_dir + #"\test\test.bat");
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
p.WaitForExit();
the cmd windows comes and goes really quickly and the test.txt file is created but is 0 bytes no info in it.
so if i run the batch file in a windows cmd line with the psexec command it works perfectly fine!!???
so then to verify psexec was the issue i changed the batch file to:
ipconfig /all >c:\test.txt
i execute my code above and it works fine creates the output in the test.txt file..???!!!!
why is not working with psexec am i missing something? if it's psexec, does anyone have
any recommendations for how i can execute a command on a remote windows host and get me the
output???
I have an answer to this problem that has worked for me.
Hopefully someone else will find it useful.
I have literally just spent the last two hours tearing my hair out with this. The psexec tool runs completely fine using a normal command prompt but when attempting to redirect the streams it truncates the output and you only get half output back.
In the end how I fixed my issue was a little bit of a hack. I piped the output of the command to a text file and read it back in to return it from the function.
I also has to set UseShellExecute to true. Without this it still wouldn't work. This had the unfortunate side effect of showing the console window. To get around that I set the window style to be hidden and hey presto it works!!!
Heres my code:
string ExecutePSExec(string command)
{
string result = "";
try
{
string location = AppDomain.CurrentDomain.BaseDirectory;
// append output to file at the end of this string:
string cmdWithFileOutput = string.Format("{0} >{1}temp.log 2>&1", command,location );
// The flag /c tells "cmd" to execute what follows and exit
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmdWithFileOutput);
procStartInfo.UseShellExecute = true; // have to set shell execute to true to
procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden; // as a window will be created set the window style to be hiddem
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
// now read file back.
string filePath = string.Format("{0}temp.log", location);
result = System.IO.File.ReadAllText(filePath);
}
catch (Exception objException)
{
// Log the exception
}
return result;
}
and its usage:
string command = #"psexec.exe -l -u domain\username -p password /accepteula \\192.168.1.3 netstat -a -n";
ExecutePSExec(command);
I had exactly same problem. i was getting "Windows ip config. " as first line when i run with psexec. i tried with paexec it worked well. I used Marius's code.
Note: if you dont use first cmd / c in arguments command runs only on local computer even if you define target as \\remoteserver
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.Arguments = #"cmd/c C:\paexec.exe \\\192.168.2.5 -s -u test.local\administrator -p Password1 cmd /c ipconfig";
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
System.IO.StreamReader myStreamReader1 = p.StandardOutput;
p.WaitForExit();
string sOutput = myStreamReader1.ReadToEnd();
Are you sure your sourcecode is correct? that link is quite a bit old.. maybe its fixed!
Heres an example how to redirect the standard-output and put whole output in a string via streamreader:
ProcessStartInfo psi = new ProcessStartInfo("tftp.exe");
// preferences for tftp process
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
StreamReader myStreamReader = p.StandardOutput;
p.WaitForExit();
// Read the standard output of the spawned process.
string sOutput = myStreamReader.ReadToEnd();
i found a solution. apparently psexec is NOT going to work in c sharp. so i came up with some wmi code to connect to a remote host and it's working PERFECTLY!!! :)
i used microsoft's WMICodeCreator.exe to create wmi code for C# for the process method on a remote host, wow that tool is amazing because wmi code is little confusing to me.
psexec's output goes to StandardError and not StandardOutput. I don't know why it is that way. Following code snippet access it.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.RedirectStandardError = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
errors = process.StandardError.ReadToEnd();
process.Close();

Categories