Run script (.bat) from ASP.Net with elevated privileges - c#

I have a ASP.Net application from which I want to run several (BAT) scripts that require elevated privileges, because it must start and stop services, copy files, etc ...
I've tried to apply different approaches, but I can't find one that works.
This is the code from ASP.Net c#:
var securePass= new SecureString();
string password = "AdminPassword";
for (int x = 0; x < password.Length; x++)
{
pass.AppendChar(password[x]);
}
Process p = new Process();
p.StartInfo.FileName = Path.Combine(appPath, "Scripts", "ServiceTest.bat");
p.StartInfo.Arguments = "";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UserName = adminUserName;
p.StartInfo.Domain = adminDomain;
p.StartInfo.Password = securePass;
p.StartInfo.Verb = "runas";
p.Start();
p.WaitForExit();
This is the ServiceTest.bat:
NET START MSSQL$SQLEXPRESS
It not works: If I remove "p.StartInfo.CreateNoWindow" and "p.StartInfo.RedirectStandardOutput" lines, the console window shows "Access denied" error executing "NET START MSSQL$SQLEXPRESS".
I tried with Filename "cmd.exe", and "/c "+Path.Combine(appPath, "Scripts", "ServiceTest.bat") as arguments, and several ways but it not work.
Any suggestion?
Thanks for your time!

You have to use different credentials. For that use RunAs or PSExec
https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
https://techtorials.me/windows/using-runas-with-a-password/
E.g.
PsExec64.exe \\<local machine Name> -u Domain\Administrator -p <Password> "<Script Name>"

Related

Issue with C# CMD output

I am creating a C# app that changes Windows Server edition from Standard Evaluation to Standard. I am trying to get a output of the CMD command, but when the DISM command is completed, it asks you if you want to restart the computer and you need to enter "y" or "n". I tried it doing by passing "echo n | " before the command and by using process.StandardInput.Write, but none of this works. The function works perfectly with other commands that doesn´t require user input. Do you have any idea what am I doing wrong? Thanks
public static string get_cmd_output(string cmd)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C echo n | " + cmd;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string q = "";
while (!process.HasExited)
q += process.StandardOutput.ReadToEnd();
return q;
}
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula");
In the docs for DISM, one of the global parameters you can pass is /NoRestart:
/NoRestart
Suppresses reboot. If a reboot is not required, this command does
nothing. This option will keep the application from prompting for a
restart (or keep it from restarting automatically if the /Quiet option
is used).
So it should work if you do this:
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula /NoRestart");

How do I correctly start a process with administrator rights?

So I've looked at alot of different SO posts, I've been on codeproject and dreamincode aswell but I cant for the life of me find out how to CORRECTLY start a process on Windows 8.1 with admin rights.
This is my code.
I'm trying to create a silent install of FireFox but everytime I give it the filepath it still promts me with the UAC, and I thought that running as admin would work. What am I doing wrong here?
Console.WriteLine("Please enter the path to the application: ");
string path = Console.ReadLine();
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = true;
psi.Verb = "runas";
psi.Arguments = "/s /v /qn /min";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.FileName = path;
Process.Start(psi);

How can I call the "net share" command from within my program?

I am currently trying to make an application that uses the command net share from the CMD. However, when I press on the button that runs the code, it gives me the following error:
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll.
Here's the code I'm using:
Process cmd = new Process();
cmd.StartInfo.FileName = "net share";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
txt_Logs.Text = cmd.StandardOutput.ReadToEnd();
But when you put ipconfig into the FileName part and /all into the Arguments part, it works perfectly.
The issue is with the StartInfo.File, "net share" is not a valid filename.
Try this
Process cmd = new Process()'
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
If the path contain spaces, you will need to quote it.
Process cmd = new Process();
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share";
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
net is a exe in sys32.. share is an argument.. add it to your aguments..
It is because net share requires Administrative privilege to run this command.
When you try to run only Net Share it will perfectly and it doesn't require any special privilege. But when you try run the command with parameters in the command prompt it will give error stating
System error 5 has occurred.
Access is denied.
So you need to run as administrator
The possible solution might be that you could run the Visual Studio as administrator
To run the command with administrator privilege whereas if the OS is Vista or higher you can do it like below
if (System.Environment.OSVersion.Version.Major >= 6)
{
p.StartInfo.Verb = "runas";
}
As mentioned by #Mohit, this is a problem of admin rights. You can run process as administrator from C# by adding following:
cmd.StartInfo.Verb = "runas";
"net" it's a programm and "share" argument. Try this:
cmd.StartInfo.FileName = "net";
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;

how to copy a file from any directory to c drive using cmd in c#

i tried an image file to copy in c:(operating sys) drive,but it says error wid access denied,i have used as
string strCmdLine;
strCmdLine = #" /c xcopy d:\123.png C:\windows\system32";
Process.Start("CMD.exe", strCmdLine);
you probably dont have enough permissions....
try adding credentials :
Process p = new Process();
process.StartInfo.UserName = "aaaa";
process.StartInfo.Password = "xxxxx";
...
...
also , verify that :
read permissions for : d:\123.png
write permissions for : C:\windows\system32
Access Denied may be caused by several reasons, such as user permissions or file being in use. Since the command line seems to be OK, I suggest to check whether your application was run by a Windows user that has permission to write to C:\windows\system32.
you need to run CMD.exe as admin try following
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Verb = "runas";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.WriteLine(#"/c xcopy d:\123.png C:\windows\system32");
You can check This post which shows how to run program as admin.

How can I invoke app on server from ASP.NET web app?

This question could be a can of worms, but I've always wondered if it were possible to invoke an executable application from inside a web application on the web server?
I can easily set this up as a scheduled task to run and check every few minutes, but it would be nice to be able to invoke the application on demand from the a web page.
The site is an ASP.NET 2.0 website using C# and the application is an executable console app written in C#.
You need to start a new process. This is an example how to do it.
Process proc = new Process();
StringBuilder sb = new StringBuilder();
string[] aTarget = target.Split(PATH_SEPERATOR);
string errorMessage;
string outputMessage;
foreach (string parm in parameters)
{
sb.Append(parm + " ");
}
proc.StartInfo.FileName = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = sb.ToString();
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : (int)TimeSpan.FromMinutes(timeout).TotalMilliseconds //Per SLaks suggestion. Thanks!
);
errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();
outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
A link to MSDN:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(VS.71).aspx
You'll also need to check to make sure that the account the Web application is running under has the appropriate permissions to execute the program.
Process.Start
I think you could do that using the following code.
Process p= new Process();
p.StartInfo.WorkingDirectory = #"C:\whatever";
p.StartInfo.FileName = #"C:\some.exe";
p.StartInfo.CreateNoWindow = true;
p.Start();
where the Process type is from the namespace System.Diagnostics.Process

Categories