How to run command line with admin right in C# [duplicate] - c#

This question already has answers here:
Elevating process privilege programmatically?
(6 answers)
Execute several elevated commands in shell (or similar)
(1 answer)
How to run multiple lines in cmd as administrator using C#?
(2 answers)
How do I make a console app always run as an administrator?
(3 answers)
Closed 5 years ago.
I have referenced some other topics and it comes up the following coding, yet it doesn't work. I allow it creates command window and use "/k" argument keeping the window opened so that I can trace its output.
However, I can see the warning from the window that the command needs admin rights to execute. How can I execute it in admin rights?
public void ClearArpCache () {
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/user:Administrator \" cmd /k arp -d \""); // same as "netsh interface ip delete arpcache"
processStartInfo.RedirectStandardOutput = true;
//processStartInfo.CreateNoWindow = true;
//processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.UseShellExecute = false;
processStartInfo.StandardOutputEncoding = Encoding.Default;
processStartInfo.Verb = "runas";
Process.Start (processStartInfo);
UnityEngine.Debug.Log ("ARP table cache cleared.");
}
EDITED:
Try changing from "cmd.exe" to "runas.exe"
public void ClearArpCache () {
ProcessStartInfo processStartInfo = new ProcessStartInfo("runas.exe", "/user:Administrator \" cmd /k arp -d \""); // same as "netsh interface ip delete arpcache"
processStartInfo.RedirectStandardOutput = true;
//processStartInfo.CreateNoWindow = true;
//processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.UseShellExecute = false;
processStartInfo.StandardOutputEncoding = Encoding.Default;
Process.Start (processStartInfo);
UnityEngine.Debug.Log ("ARP table cache cleared.");
}

Just clarified why it failed using "runas". In order to use "runas" in Verb, UseShellExecute must be firstly turned true.
When executing following function, it will pop a window asking for admin rights, just click 'Yes' to begin the execution. Though it is beyond the scope, if possible I want to skip the pop-up window as well.
public void ClearArpCache () {
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/k arp -d"); // same as "netsh interface ip delete arpcache"
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.UseShellExecute = true;
processStartInfo.Verb = "runas";
Process.Start (processStartInfo);
UnityEngine.Debug.Log ("ARP table cache cleared.");
}

Related

Run command process as Admin

I have a Windows Forms Application with the app.manifest set to:
level="requireAdministrator" uiAccess="false".
Now I need to run a console application (Diskspd.exe) from my application and return the standard output. It almost works, though the part that requires runAs Admin of DiskSpd fails.
Here is the part of the code that call the process (Example of txtDatPath.Text is "C:\temp\IO.dat"):
if (File.Exists(txtDatPath.Text))
{
File.Delete(txtDatPath.Text);
}
string qPath = string.Format("\"{0}\"", txtDatPath.Text);
if (rdoOLTP.Checked)
{
DScmd = "-b8K –d180 -h -L –o32 –t3 -r –w75 -c5G " + qPath;
}
else
{
DScmd = "–b60K –d60 -h -L –o32 –t1 -s –w100 –c1G " + qPath;
}
//now set up the cmd
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Verb = "runas";
p.StartInfo.Arguments = DScmd;
p.StartInfo.FileName = "diskspd.exe";
p.Start();
// To avoid deadlocks, always read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
I need the process itself to run as Admin to succeed. The command behaves the same way if I run regular command then try CMD and run as admin it completes.
StartInfo.UseShellExecute needs to be set to false for the RedirectStandardOutput to work.
Well - after all of this - in adding debugging, the issue is the p.StartInfo.Arguments = DScmd;
The Argument is being interpreted as separate entries.
The solution/problem: DISKSPD requires ASCII and the string is UNICODE.
Changed the hyphens to convert.ToChar(45)
So I am going to close this case (thx all!) and open new one.

C# Start Program with ADMIN rights from other program [duplicate]

This question already has answers here:
Elevating privileges doesn't work with UseShellExecute=false
(3 answers)
Closed 1 year ago.
I´ve written a notify program, which communicats with an windows service on WebSocket. This notify program does not have admin rights but with click on button starts an other program which starts and stops the service. This program should run with admin rights, it worked very fine for some time but somehow not any more.
Thats my code snippet:
using (var process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = $".\\ServiceControl.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Arguments = $"-s {ServiceName} -start";
process.StartInfo.Verb = "runas";
process.Start();
}
The exception is the following:
System.ComponentModel.Win32Exception: "Der angeforderte Vorgang erfordert erhöhte Rechte"
Back then it showed a window where I could accept admin rights but does not any more.
Try adding this line
process.StartInfo.UseShellExecute = true;
on
using (var process = new Process())
{
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = $".\\ServiceControl.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Arguments = $"-s {ServiceName} -start";
process.StartInfo.Verb = "runas";
process.Start();
}

Stopping Windows Service from C# code doesn't work

My code has to stop a service. I'm using the code below:
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.UseShellExecute = true;
processInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + #"\System32\cmd.exe";
processInfo.Arguments = "sc stop SERVICENAME";
processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
processInfo.Verb = "runas"; //The process should start with elevated permissions
Process process = new Process() { EnableRaisingEvents = true, StartInfo = processInfo };
process.Start();
process.WaitForExit();
I then check the service state from a CMD window (manually, not in my program) with the following command: sc SERVICENAME query. But the state is still RUNNING.
When I stop it opening cmd as Administrator and executing the same commands (sc stop SERVICENAME), it just works.
Any thoughts about why it doesn't work from my code?
With C# and .NET, it is better if you use the ServiceController class like this:
ServiceController controller = new ServiceController("SERVICENAME");
controller.Stop();
Executing cmd.exe with sc stop SERVICENAME as arguments won't do anything. It will only start the command prompt.
To fix your problem, simply execute sc.exe directly, passing stop SERVICENAME as the arguments.
// ...
processInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "sc.exe");
processInfo.Arguments = "stop SERVICENAME";
// ...

Run Unix commands using PuTTY in C# [duplicate]

This question already has answers here:
Automating running command on Linux from Windows using PuTTY
(9 answers)
Closed 8 years ago.
I am trying to run Unix commands in PuTTY using C#. I have the below code. But the code is not working. I am not able to open PuTTY.
static void Main(string[] args)
{
Process cmd = new Process();
cmd.StartInfo.FileName = #"C:\Windows\System32\cmd";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
cmd.StartInfo.Arguments = "C:\Users\win7\Desktop\putty.exe -ssh mahi#192.168.37.129 22 -pw mahi";
}
First, in general, you better use native .NET SSH library, like SSH.NET, instead of running external application.
See How to run commands on SSH server in C#?
The putty.exe is a GUI application. It's intended to interactive use, not for automation. There's no point trying to redirect its standard output, as it's not using it.
For automation, use another tool from PuTTY package, the plink.exe.
It's a console application, so you can redirect its standard output/input.
There's no point trying to execute an application indirectly via the cmd.exe. Execute it directly.
You need to redirect standard input too, to be able to feed commands to the Plink.
You have to provide arguments before calling the .Start().
You may want to redirect error output too (the RedirectStandardError). Though note that you will need to read output and error output in parallel, what complicates the code.
static void Main(string[] args)
{
Process cmd = new Process();
cmd.StartInfo.FileName = #"C:\Program Files (x86)\PuTTY\plink.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.Arguments = "-ssh mahi#192.168.37.129 22 -pw mahi";
cmd.Start();
cmd.StandardInput.WriteLine("./myscript.sh");
cmd.StandardInput.WriteLine("exit");
string output = cmd.StandardOutput.ReadToEnd();
}
This should work:
static void Main(string[] args)
{
ProcessStartInfo cmd = new ProcessStartInfo();
cmd.FileName = #"C:\Users\win7\Desktop\putty.exe";
cmd.UseShellExecute = false;
cmd.RedirectStandardInput = false;
cmd.RedirectStandardOutput = true;
cmd.Arguments = "-ssh mahi#192.168.37.129 22 -pw mahi";
using (Process process = Process.Start(cmd))
{
process.WaitForExit();
}
}

Executing System.Diagnostics.Process cmd.exe only opens command prompt, doesn't execute arguments

Where am I going wrong with this? It's like the arguments are not even getting executed, it just opens the command prompt, and that's it. The "results" (StandardOutput) is exactly what shows up when you just open a new command prompt....says Microsoft Windows [Version 6.1.7600] Copyright...blah then the path where the command prompt is starting from.
Anyway, here's the code that I have:
private static void ExecuteProcess(string processFile, string processArguments)
{
ProcessStartInfo psi = new ProcessStartInfo(processFile, processArguments);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
//psi.CreateNoWindow = true;
Process p = new Process();
p.StartInfo = psi;
try
{
Cursor.Current = Cursors.WaitCursor;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Cursor.Current = Cursors.Default;
if (p.ExitCode == 0)
MessageBox.Show(output, "Results");
else
throw new Exception(p.StandardError.ReadToEnd());
}
catch (Exception ex)
{
Cursor.Current = Cursors.Default;
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
p.Dispose();
}
}
processFile is equal to "cmd.exe"
processArguments is equal to:
csvde -s {servername} -f {filename} -d OU=MyOU,DC=dmz,DC=lan -r "(objectClass=organizationalUnit)" -n
Any help as to why the "arguments" aren't getting executed would be great!
Edit:
One thing I've found so far, Chris's suggestion about the permissions is true, I needed to set:
psi.Verb = "runas";
But when executing the process it didn't look like there was a username associated with the process, so I added this line as well:
psi.UserName = Environment.UserName;
Now I'm getting "the stub received bad data"...
From the docs:
Cmd
Starts a new instance of the command interpreter, Cmd.exe. Used
without parameters, cmd displays Windows XP version and copyright
information.
Syntax cmd [[{/c|/k}] [/s] [/q] [/d] [{/a|/u}] [/t:fg]
[/e:{on|off}] [/f:{on|off}] [/v:{on|off}] string] Top of page
Parameters
/c : Carries out the command specified by string and then
stops.
So you need to:
Pass the full path to the EXE or
Set the working directory to the directory containing the exe
then
Make processFile == "[]csvde.exe", and remove it from processArguments, or
Prepent "/c \"" and append "\"" to processArguments.
I finally got back to working on this and figured out how to get this to work.
I had to specifically set the Username, Password, and Domain of the Process.ProcessStartInfo in order for the process to execute.

Categories

Resources