I’m facing some issue w.r.t calling a .exe from MVC4.
I have a ActionResult method where I want to start a command prompt locally but it shouldnot run as IISPool Identity instead it should run as a user logged in, unlike we do RunAs manually.
I have to pass parameter to the command line and in turn receive the output. I have written a code but it is not returning anything. Can someone highlight where I made some mistake.
string _commandParameter = #"whoami";
try
{
var process = new Process
{
StartInfo =
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
Verb = "runas",
FileName = #"C:\Windows\System32\cmd.exe",
Domain = "dir",
UserName = userID,
Password = GetSecureString(userpassword),
Arguments = _commandParameter
}
};
process.Start();
string readToEndOutput = process.StandardOutput.ReadToEnd();
string readToEndError = process.StandardError.ReadToEnd();
process.WaitForExit();
}
catch (Exception ex)
{
log.Info("error as StackTrace Exception in Input ActionResult -" + ex.StackTrace.ToString());
log.Info("error as Message Exception in Input ActionResult -" + ex.Message.ToString());
}
public static SecureString GetSecureString(string str)
{
SecureString result = new SecureString();
try
{
if (string.IsNullOrWhiteSpace(str))
return null;
else
{
foreach (char c in str.ToCharArray())
result.AppendChar(c);
return result;
}
}
catch (Exception ex)
{
log.Info("Cannot create password-" + ex.StackTrace.ToString());
}
return result;
}
The output
Related
I am absolutely new to ASP.NET Core.
I want to send a GET-Request to my Linux server which is hosting my ASP.NET Core API to execute some bash commands and return the given output in my GET-Response.
I found a similar question: ASP.NET Core execute Linux shell command but I am not sure if the answer is really the solution for my problem neither how to use this package.
Is there a solution for this like:
[HttpGet]
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
{
bashOutput = BASHCOMMAND(whoami);
return await bashOutput;
}
Or is there may a better way to execute commands on my linux server and return the value via API? It doesn't have to be ASP.NET Core.
Try this
public static string Run(string cmd, bool sudo = false)
{
try
{
var psi = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = (sudo ? "sudo " : "") + "-c '" + cmd + "'",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
};
Process proc = new Process() { StartInfo = psi, };
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
if (string.IsNullOrWhiteSpace(result))
{
Console.WriteLine("The Command '" + psi.Arguments + "' endet with exitcode: " + proc.ExitCode);
return proc.ExitCode.ToString();
}
return result;
}
catch (Exception exc)
{
Debug.WriteLine("Native Linux comand failed: " + cmd);
Debug.WriteLine(exc.ToString());
}
return "-1";
}
I am having a .rmd file [ R mark down file], it will do data validation for some specific scenario, i wanted to execute the rmd file from console application using c#, can some one help me doing the execution.
Finally I have done the above requirement as below,posting here since it can help some one on implementation
- created a R script and invoked Rmd script from the R script
- used command line code for invoking R script from C#.
R Script Sample:
rmarkdown::render(
input = rmdfilepath,
output_file = outputfilepath,
output_format = "all", output_options = list())
c# Sample:
private static string RunRScript(string rpath, string scriptpath, string inputfilepath,
string outputfilepath)
{
try
{
var info = new ProcessStartInfo
{
FileName = rpath,
WorkingDirectory = Path.GetDirectoryName(rpath),
Arguments = scriptpath + " " + inputfilepath + " " + outputfilepath,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false
};
using (var proc = new Process { StartInfo = info })
{
proc.Start();
return proc.StandardOutput.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return string.Empty;
}
When I execute the script via code it's going in an infinite loop. But same script working in CMD
tried with CMD and It's working but not working in code. Take any VB Script as a sample and validate.
private string excecuteScript(string retValue)
{
try
{
string filetoexecute = Path.Combine(Application.StartupPath, Path.GetExtension(ScriptName).EndsWith(".vbs",StringComparison.InvariantCultureIgnoreCase) ? "AA_MyVB.vbs" : "AA_MyJS.js");
filetoexecute = string.Format("\"" + filetoexecute + "\"");
string arguments = " " + filetoexecute + " " + ScriptInputPara + " \"" + ScriptName + "\" ";
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = Path.Combine(Environment.SystemDirectory, "WScript.exe"),
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var myProcess = CommonMethods.InvokeProcess(startInfo);
StreamReader errorStream = myProcess.StandardError;
StreamReader outputStream = myProcess.StandardOutput;
string theOutput = string.Empty;
bool stopWhile = false;
while (!stopWhile)
{
stopWhile = myProcess.HasExited;
if (CmdTask.IsTaskTimedout)
{
stopWhile = true;
myProcess.Kill();
}
}
theOutput += outputStream.ReadLine();
TheError += errorStream.ReadToEnd();
if (myProcess.ExitCode != 0)
{
TheError = "Error occurred while executing script file";
}
if (IsScriptTask && !string.IsNullOrEmpty(theOutput) && !string.IsNullOrEmpty(ScriptOutputPara))
CmdTask.SetVariableValue(ScriptOutputPara, theOutput);
}
catch (Exception ex)
{
retValue = (ex.Message);
}
return retValue;
}
Actual: myProcess.HasExited returns false
Expected: myProcess.HasExited returns true
if I execute theOutput += outputStream.ReadLine(); before while loop then myProcess.HasExited returns true...
Hey i am trying to launch my Application.exe as a runas administrator but still not able to launch i have tried both verb="runas" as well as created app.manifest file but my exe not opening in administrator mode.
I am using this code :
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = GetASDeploymentExe(),
Arguments = GetASDeploymentCmdArgs(),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
Domain = "***",
UserName = username,
Password = secstr,
Verb = "runas"
}
};
proc.Start();
config.ASDeploymentToolPID = proc.Id;
string line = string.Empty;
do
{
line = proc.StandardOutput.ReadLine();
Console.WriteLine(line);
} while (!proc.HasExited);
string error = string.Empty;
while (!proc.StandardError.EndOfStream)
{
error = proc.StandardError.ReadLine();
Logger.WriteError(error);
}
}
Try this:
//Vista or higher check
if (System.Environment.OSVersion.Version.Major >= 6)
{
p.StartInfo.Verb = "runas";
}
Alternatively, go the manifest route for your application.
I know that this is question was already asked but i couldn't find any answer . I have this code i'm trying to run an app with a specific user but gives error that file could not be found even if the file is there.
static void Main(string[] args)
{
System.Diagnostics.ProcessStartInfo myProcess = new System.Diagnostics.ProcessStartInfo("cinegy.exe");
myProcess.WorkingDirectory =Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)+ "\\Cinegy\\Cinegy Workflow 8.5.8\\";
System.Security.SecureString password = new System.Security.SecureString();
string uspw = "mypass";
foreach (char c in uspw)
{
password.AppendChar(c);
}
myProcess.UserName = "myuser";
myProcess.Password = password;
myProcess.Domain = "mydomain";
myProcess.UseShellExecute = false;
try
{
System.Diagnostics.Process.Start(myProcess);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
Thanks
Error is |The system cannot find the file specified|
If you use
UseShellExecute = false
it ignores WorkingDirectory
You can either set UseShellExecute to true and have a cmd shell. Or you add the location of the process to path of the process you are running:
string path = System.Environment.GetEnvironmentVariable("path");
path += ";" + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\Cinegy\\Cinegy Workflow 8.5.8\\";
System.Environment.SetEnvironmentVariable("path", path);