C# and psexec process output redirection issues - c#

I'm trying to create a small program to run on a centralized device. This program will run
"psexec \server(s) netstat -na | findstr "LISTENING""
to collect netstat data from remote nodes (should redirect output to string), then parse the data and compare against a known list. I can run the psexec cmd above without any issues from the cmd line, but when I try to run the same command as a process within my C# program, no data is returned to be parsed. I can see that the netstat is being run (cmd window flashes with netstat results), but the process.standardoutput is not catching the stream. If I use ping or pretty much anything other than psexec as an argument, the stream is caught and the results are shown in my text box. I've also tried setting the filename to psexec.exe and specifying the arguments but I get the same results. Last but not least, if I run psexec without any arguments, I get the help kickback info returned in my textbox. This is true if I'm running psexec.exe as the filename OR if I run cmd.exe as filename with "/c psexec" specified as args.
I'm just trying to get psexec output to be caught when executing locally at this point. I'll worry about psexec to remote machines later. Any help would be MUCH appreciated.
Here's the code:
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = "cmd.exe";
pProcess.StartInfo.Arguments = "/c psexec netstat";
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.Start();
string strOutput = pProcess.StandardOutput.ReadToEnd();
pProcess.WaitForExit();
if (pProcess.HasExited)
{
textBox1.Text = strOutput;
}
else
{
textBox1.Text = "TIMEOUT FAIL";
}

I would recommend also capturing the standard error output in case anything is being reported there.
Also, you may have a disconnect between "bitness" of psexec and your application if you are running on a 64-bit OS. If this is the case, change the platform for the project to match that of psexec rather than building as Any CPU.

Came across a few things to be changed but your recommendation of capturing standard error output was dead on and a good start. Turns out some info was being sent to the error output (even though really wasn't error, just run status 0 from psexec) so I knew at that point psexec wasn't just eating ALL the output. Once I started trying to pass remote hosts as args, I started getting user/pass error data back. Also needed to catch standard input if I wanted to supply credentials for proc run. Threw in some str literals and credentials for the remote exec, works perfectly. Thanks for the help. Here is the updated code--
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.Domain = "domain";
pProcess.StartInfo.UserName = "user with priv";
pProcess.StartInfo.Password = new System.Security.SecureString();
char [] pass = textBox3.Text.ToArray();
for (int x = 0; x < pass.Length; ++x)
{
pProcess.StartInfo.Password.AppendChar(pass[x]);
}
pProcess.StartInfo.FileName = #"psexec.exe";
pProcess.StartInfo.Arguments = #"\\remoteHost netstat -ano";
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardInput = true;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.RedirectStandardError = true;
pProcess.Start();
pProcess.WaitForExit(30000);
if (!pProcess.HasExited)
{
pProcess.Kill();
}
string strOutput = pProcess.StandardOutput.ReadToEnd();
string errOutput = pProcess.StandardError.ReadToEnd();
textBox1.Text = strOutput;
textBox2.Text = errOutput;

Related

execute Sqlite3 command line tool from code

I'm trying to run the sqlite.exe tool as a process in my c# code in order to read a sql from a file.
If I run the sqLite3 tool in powershell then it works fine (sqlite3.exe "mydatabase.db" ".read mySql.sql")
But when I run the sqlite3 tool from my c# code as a process, then nothing happens to mydatabase.db. It's still 0b when sqlite3 terminates.
I get no error message, the output from the sqlite3.exe is an empty string and the exit code is 1 (verified in the exit event). Does anyone have a clue why the database.db why the records in the .sql file is not added to the .db file?.
using (Process pProcess = new Process())
{
pProcess.StartInfo.FileName = sqlLite3ExePath;
pProcess.StartInfo.Arguments = $"\"{sqLitePath2}\" \".read {sqlPath}\"";;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;//System.Diagnostics.ProcessWindowStyle.Hidden;
pProcess.StartInfo.CreateNoWindow = false;//true; //not diplay a windows
pProcess.EnableRaisingEvents = true;
pProcess.Exited += PProcess_Exited;
pProcess.Start();
string output = pProcess.StandardOutput.ReadToEnd(); //The output result
pProcess.WaitForExit();
Debug.WriteLine(output);
}
As CaiusJard said in the comments, an error was passed in the error stream. Adding the following lines told me that my path was wrong.
pProcess.StartInfo.RedirectStandardError = true;
string error = pProcess.StandardError.ReadToEnd(); //The output result
The path divider "\" was removed since the path was parsed twice. Once setting the argument, and once when it was read by the tool. Replacing "\" with "/" in my paths did the trick

.NET console output and PSExec

I'm running PSExec Microsoft tool with Process class executing a remote command with its own output like this:
Process p = new Process();
string args = #"\\remotemachine -u someuser -p somepass wmic product get name";
ProcessStartInfo ps = new ProcessStartInfo();
ps.Arguments = args;
ps.FileName = psExecFileName;
ps.UseShellExecute = false;
ps.CreateNoWindow = true;
ps.RedirectStandardOutput = true;
ps.RedirectStandardError = true;
p.StartInfo = ps;
p.Start();
StreamReader output = p.StandardOutput;
string output = output.ReadToEnd();
where wmic product get name is WMI tool running remotely with its own output listing all installed applications on the remote machine.
So, in the output I don't see the output of wmic, at the same time when I'm running PSExec in the command line locally, I can fully see the output of both PSExec and started remotely WMIC.
The question is, how can I capture all the output on the local machine? Should I run it in a separate console and try to attach to the console to capture all the output?
More generally, if put plainly, why is the output in the process StandardOutput and in the console when running PSExec directly not the same?
ReadToEnd will wait till the process exit. e.g. a Console.ReadLine() in the psExecFile could block your reading. But you can get the already written stream,
StreamReader output = p.StandardOutput;
string line;
while ((line = output.ReadLine()) != null)
{
Console.WriteLine(line);
}
In the console, data written to both StandardOutput and StandardError is displayed in the console.
Within your program you need to look at each individually...try adding something like this at the end:
string error = p.StandardError.ReadToEnd();

MySQL database backup using C#

I am trying to take back up of a mysql database.
the code i am created is
ProcessStartInfo proc = new ProcessStartInfo();
string cmd = string.Format(#"-u{0} -p{1} -E -R -h{2} {3}", UserName, PWD, hostname, dbname);
proc.FileName = "Path to mysqldump.exe";
proc.RedirectStandardInput = false;
proc.RedirectStandardOutput = true;
proc.Arguments = cmd;
proc.UseShellExecute = false;
Process p = Process.Start(proc);
string res;
res = p.StandardOutput.ReadToEnd();
file.WriteLine(res);
p.WaitForExit();
file.Close();
The problem is it working correctly when the database size is small but i am getting Out Of Memory Exception when i am trying to take back up of large database (Approximately 800 MB ).
Instead of reading the standard output in C# why don't you write it directly to file through the command line?
I typically take my mysqldumps using the following command. It works in both Windows and Linux.
mysqldump -u{user} -p{password} --routines --triggers --result-file={dest_filename} {dbname}
-OR-
mysqldump -u{user} -p{password} --routines --triggers {dbname} > {dest_filename}
The Out of memory exception you encountered would probably have been caused when trying to read the entire output of mysqldump to memory in C# on the following line (typically happens when a string exceeds beyond a certain size).
res = p.StandardOutput.ReadToEnd();
Looks like very big string ate the memory.
Try to use OutputDataReceived event to write data in output file.
Here are two links with examples -
Process.OutputDataReceived Event
Process.BeginOutputReadLine Method

how to send command and receive data in command prompt in C# GUI application

I am new to C# so please sorry if i make no sense in my question. In my application which is C# DLL need to open command prompt, give a plink command for Linux system to get a system related string and set that string as environment variable. I am able to do this when i create C# console application, using plink command to get the string on command prompt and use to set it environment variable using process class in C# to open plink as separate console process. But, in C# DLL i have to open cmd.exe 1st and then give this command which i don't know how can i achieve? I tried through opening cmd.exe as process and then trying to redirect input and output to process and give command and get string reply, but no luck. Please let me know any other way to solve this.
Thanks for answers,
Ashutosh
Thanks for your quick replys. It was my mistake in writing code sequence. Now few changes and the code is working like charm. Here is code,
string strOutput;
//Starting Information for process like its path, use system shell i.e. control process by system etc.
ProcessStartInfo psi = new ProcessStartInfo(#"C:\WINDOWS\system32\cmd.exe");
// its states that system shell will not be used to control the process instead program will handle the process
psi.UseShellExecute = false;
psi.ErrorDialog = false;
// Do not show command prompt window separately
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
//redirect all standard inout to program
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
//create the process with above infor and start it
Process plinkProcess = new Process();
plinkProcess.StartInfo = psi;
plinkProcess.Start();
//link the streams to standard inout of process
StreamWriter inputWriter = plinkProcess.StandardInput;
StreamReader outputReader = plinkProcess.StandardOutput;
StreamReader errorReader = plinkProcess.StandardError;
//send command to cmd prompt and wait for command to execute with thread sleep
inputWriter.WriteLine("C:\\PLINK -ssh root#susehost -pw opensuselinux echo $SHELL\r\n");
Thread.Sleep(2000);
// flush the input stream before sending exit command to end process for any unwanted characters
inputWriter.Flush();
inputWriter.WriteLine("exit\r\n");
// read till end the stream into string
strOutput = outputReader.ReadToEnd();
//remove the part of string which is not needed
int val = strOutput.IndexOf("-type\r\n");
strOutput = strOutput.Substring(val + 7);
val = strOutput.IndexOf("\r\n");
strOutput = strOutput.Substring(0, val);
MessageBox.Show(strOutput);
I explained the code so far..., thanks a lot

ASP.NET running an EXE File

I´m trying to run an old .NET application from an ASP.NET website. After reading the web and Stackoverflow (for similar problem) I come to the following code.
The Problem is that I get always an error code (I am using administrator account
just to testing purposes). If I run the exe manually it works ok.
private void Execute(string sPath)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.UserName = "administrador";
string pass = ".............";
System.Security.SecureString secret = new System.Security.SecureString();
foreach (char c in pass) secret.AppendChar(c);
proc.StartInfo.Password = secret;
proc.StartInfo.WorkingDirectory = ConfigurationManager.AppSettings["WORKINGDIRECTORY"].ToString();
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = sPath;
proc.Start();
proc.WaitForExit();
string result = proc.StandardOutput.ReadToEnd();
Response.Write(result + " - " + proc.ExitCode);
proc.Close();
}
}
The exitcode I get is: -1066598274
Result variable is empty.
No exception is thrown
I am using Windows 2008 with IIS 7.0
Thanks in advance,
Ezequiel
Don't do this. This is just plain dirty and should not be done from ASP.NET
Write a windows service
Store the request in a queue
The service should poll the queue and process. If needed run the exe. It is suggested that the service stays in a different server.
Don't do this. This is very bad and not scalable and bad for the web server
Don't
Don't
Don't
protected void btnSubmit_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
litMessage.Visible = true;
System.Diagnostics.Process oProcess = null;
try
{
string strRootRelativePathName = "~/Application.exe";
string strPathName =
Server.MapPath(strRootRelativePathName);
if (System.IO.File.Exists(strPathName) == false)
{
litMessage.Text = "Error: File Not Found!";
}
else
{
oProcess =
new System.Diagnostics.Process();
oProcess.StartInfo.Arguments = "args";
oProcess.StartInfo.FileName = strPathName;
oProcess.Start();
oProcess.WaitForExit();
System.Threading.Thread.Sleep(20000);
litMessage.Text = "Application Executed Successfully...";
}
}
catch (System.Exception ex)
{
litMessage.Text =
string.Format("Error: {0}", ex.Message);
}
finally
{
if (oProcess != null)
{
oProcess.Close();
oProcess.Dispose();
oProcess = null;
}
}
}
}
If you use
proc.StartInfo.RedirectStandardOutput = true;
then you have to read the stream as the process executes, instead of before the call to
proc.WaitForExit();
Same goes for the standard error stream. See the MSDN docs for more detail.
You need to reorder the output reading at the end.
It expects you to read before the waitforexit() call, so you should have:
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Response.Write(result + " - " + proc.ExitCode);
proc.WaitForExit();
proc.Close();
If the application you're trying to run is really a .NET application as you say, you may not need to run it in a separate process at all. Instead, you can take advantage of the fact that .NET executables are also assemblies. I don't think Visual Studio will let you reference assemblies that end in .exe, but the command-line compiler will.
I would try using the command-line compiler to create a wrapper assembly that simply references the executable assembly, and directly calls its Main() method, passing in a string array of any command-line parameters you would normally specify. The exit code, if any, will be an integer return value from the Main method. Then you can simply call your wrapper assembly from your ASP.NET app.
Depending on what the executable does, and how much it interacts with the console, this approach may not work at all. But if it does work for your case, it should perform much better than spinning up a separate process.
What i do is to have the executable called by a ms sql job.
The executable would be run as SQL server agent service account.
Create a new sql server job
Give it a name in the job property's general page
In the steps page, create a new step of type Operating system (CmdExec)
Speeify the command and click ok to save the job parameters
The new job can be called using EXEC msdb.dbo.sp_start_job #jobname, where #jobname is
the variable carrying the name of the job you want to start.
Note that when this job starts, the UI of the exe will be hidden and will not be displayed; but you can find it in your task manager.
I have employed this method in several applications especially time consuming operations that cannot be done on the web page.
You may need to set the proc.StartInfo.LoadUserProfile property to true so the administrator's user profile stuff is loaded into the registry (AFAIK this does not happen by default).
Also, it might be educational to run a 'hello world' program to see if the problem is with actaully creating the process or if the process itself is having problems running in the context it's given.
Finally, as a step in trying to narrow down where the problem might be, you might want to run the ASP.NET process itself with admin or system credentials to see if something in the permissions of the account the ASP.NET instance is running under is part of the problem (but please do this only for troubleshooting).
Use below code:
ProcessStartInfo info = new ProcessStartInfo("D:\\My\\notepad.exe");
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
//info.UserName = dialog.User;
info.UserName = "xyz";
string pass = "xyz";
System.Security.SecureString secret = new System.Security.SecureString();
foreach (char c in pass)
secret.AppendChar(c);
info.Password = secret;
using (Process install = Process.Start(info))
{
string output = install.StandardOutput.ReadToEnd();
install.WaitForExit();
// Do something with you output data
Console.WriteLine(output);
}

Categories