Automating interactive command line process from C# - c#

I have an *.exe that has an interactive text command interface which I want to automate from C#.
The (1) is the C # result, and the (2) is the result of directly using *.exe.
(latter miss "connect ok!" & "download successfully!")
(1)
connect ok!
cable detect ok!
download successfully!
(2)
cable detect ok!
I don’t know how to make the result of C # the same as the (2), below is my code:
Process p = new Process();
p.StartInfo.FileName = ex.exe;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("prj_project open " + "...../bin/store//*****Water.ldf");
p.StandardInput.WriteLine("pgr_project open " + "...../bin/store/imp11/imp11.xcf");
p.StandardInput.WriteLine("pgr_program run");
p.StandardInput.WriteLine("exit");
p.WaitForExit();
var str = p.StandardOutput.ReadToEnd();
var str2 = p.StandardError.ReadToEnd();
Console.WriteLine(str);
Console.WriteLine(str2);
p.Close();
For some reason, I want to mask out some places, hope not to cause your confusion.
If you can help me solve this problem, thank you very much.
It drives me crazy...It took me almost fifteen hours to solve...

Related

Why does Kaspersky anti-virus prevent my program from capturing the output of its child process?

I have a C# program that launches a child process and captures its output in a string. This works on most Windows machines (Windows 7 and newer), but when Kaspersky anti-virus is present, Process.StandardOutput.ReadToEnd() returns null. There is no error code or exception. The child process is a trusted console application. The process takes 5 or 6 seconds to run.
The code for launching the child process is as follows:
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.FileName = "icao.exe";
psi.Arguments = im_path + "image.jpg";
Process p = new Process();
p.StartInfo = psi;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
MessageBox.Show(error);
p.WaitForExit();
int exitCode = p.ExitCode;
MessageBox.Show(exitCode+"");
Why does output end up being null when Kaspersky is present?
My guess is that Kaspersky's heuristics are seeing that your program wants to execute another exe. Because nothing is telling Kaspersky that this is ok, it flags your program as possible malware, because it wants to interface with other programs that are developed by other companies. If you are able to I would try white listing your program with Kaspersky and see if that solves your issue.

Start NodeJS Application from C# web Form Application

I have built MeteroJS application that I want to start as NodeJS application from C# code.
Here is Windows Form application that is used as control panel for starting and stopping the NodeJS application
I can start NodeJS application manually with command line: (this works!)
set MONGO_URL=mongodb://someAdmin:password#localhost:27017/some_db
set ROOT_URL=http://someservice:8080
set PORT=8080
node bundle\main.js
I want to repeat all action above from command line, this time inside C# application.
This is code that executes on Start button click:
Environment.SetEnvironmentVariable("MONGO_URL", String.Format("mongodb://{0}:{1}#localhost:27017/{2}", usernameTxt.Text, passwordTxt.Text, databaseTxt.Text), EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("ROOT_URL", String.Format("http://someservice:{0}", portTxt.Text), EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PORT", portTxt.Text, EnvironmentVariableTarget.Machine);
Process.Start("CMD.exe", #"/C node bundle\main.js");
I am not sure if this is even possible. This simply does not work and left no logs.
Could you please check what I am doing wrong and advise.
Use the following code to execute the node.js cmd
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.FileName = #"c:\node\node.exe";**//Path to node installed folder****
string argument = "\\ bundle\main.js";
p.StartInfo.Arguments = #argument;
p.Start();
This code may help you:
Process p = new Process();
p.StartInfo.WorkingDirectory= #"C:\Users\USERNAME\Documents\Visual Studio 2015\Projects\Proyecto 1.3\Proyecto 1.3\bin\Debug\server";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c node app.js";
p.Start();

Run VB Script from Windows Service

I have written a small Windows Service in C# which executes .BAT and .VBS scripts. The following code triggers the .vbs script:
string path = "C:\\Path\\To\\MyScript.vbs";
Process p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WorkingDirectory = Environment.SystemDirectory;
p.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
p.StartInfo.Arguments = "/C C:\\Windows\\System32\\cscript.exe //Nologo \"" + path + "\"";
p.StartInfo.ErrorDialog = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += OutputDataReceived;
p.ErrorDataReceived += OutputDataReceived;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
try
{
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
}
catch { // }
The code compiles and runs without any exceptions. However, there miust be something wrong since the VBS script does not execute until the end. Inside the script, I open a telnet session and enter some commands. When I run the same code and the same script in a WinForms Application, everything works perfectly fine.
I assume the problem is caused by my service, which runs as LOCAL SYSTEM.
Any ideas?
EDIT
This is my VBScript:
set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd"
WScript.Sleep 1000
WshShell.SendKeys "telnet 127.0.0.1 3000"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 2000
WshShell.SendKeys "reboot application"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 2000
For some reason, the telnet command is never executed, but the Process still ends with exitcode '0'...
Got it - SendKeys does not work when no user is logged in. The code itself works perfectly fine.

SNMPWalk Error in C# Process init

I'm creating an application at work that uses SNMPWalk to get details on specific IP addresses. Right now it's meant to use Nmap to find all printers in a specified network and then it uses SNMPWalk to get details on each printer.
The problem is that SNMPWalk is giving me the error:
"No log handling enabled - using stderr logging
-v2c: (Sub-id not found: (top) -> -v2c)"
My code is here:
Process p = new Process();
p.StartInfo.FileName = snmploc + "\\snmpwalk.exe";
p.StartInfo.ErrorDialog = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.WorkingDirectory = snmploc;
p.StartInfo.Arguments = "–mALL -v2c –cpublic " + printer.IP();
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
Console.WriteLine("Snmpwalk has been fired");
Console.WriteLine("Waiting for Snmp to terminate...");
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
p.WaitForExit();
Console.WriteLine(p.ExitCode);
printer is an object of the class Printer. It is used to contain printer details such as ip address, name, model, serial number, and open ports. snmploc is obtained from command line arguments.
The main reason that this is so complicated is that when I try using the exact same command in a command prompt it works perfectly.

Showing output of a running cmd process

I have a C# code that uses command prompt to call a python script. The script currently takes about 25 seconds to run. When run in command prompt, the python script has several outputs until finally outputting "done". My C# code runs the script, but never closes the command prompt if I use "WaitForExit". So my thought is I need some kind of logic to check to see if "done" has been outputted, but the internet has not been very helpful with methodology.
Here's what I have, it currently only outputs the first line, "Microsoft Windows [Version 6.1.7601]". Obviously, no good.
var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = #"C:\Optimization";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.WriteLine(#"ipy spot_for_labview.py");
StreamReader mySR = p.StandardOutput;
string mystr = mySR.ReadLine();
Debug.WriteLine(mystr);
p.WaitForExit(25000); //25000 is a placeholder until better method found.
p.Close();
If there's anyway to close the process after it finishes, or to get all the cmd output I'm all ears.
Any help is appreciated.
did you try this event ? Process.OutputDataReceived Event
or Process.ErrorDataReceived Event
here is the code from MSDN
Process sortProcess;
sortProcess = new Process();
sortProcess.StartInfo.FileName = "Sort.exe";
sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
...
....
...
private static void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
}

Categories

Resources