I am using PsExec to remotely fire a program. I can fire the actual program (not displayed here) or cmd.exe remotely with no problems whatsoever from the command line. When I try to fire it from ASP and C#, it will not trigger the command prompt, even though I am using the same exact string. Here is the string I am using that works every time, and the code that doesn't. Help please!
Working String: C:\psexec \\10.0.0.25 -u Administrator -p password -d -i cmd.exe
Non-working code:
ProcessStartInfo psi = new ProcessStartInfo(#"C:\PsExec.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
Arguments = #"\\10.0.0.25 -u Administrator -p password -d -i cmd.exe"
};
process.StartInfo = psi;
var success = process.Start();
One option, assuming you have control over the machine, is to setup the psexec command as a Task Scheduler job, then execute the task scheduler job from your ASP app. You can configure the task scheduler to run as an administrator, and when you fire off the job it will run under that credentials. You won't get any output that way though, so if that's an issue there may not be a good choice.
See How to run existing windows 7 task using command prompt for an example of running the task..
It's been a while since I was a system administrator, but if I recall correctly psexec has to be run from an administrative command prompt. Maybe the account your app is running under doesn't have rights to reach across the network and do stuff to a remote machine?
Put this in your Page_Load temporarily:
Response.Write(Environment.UserName);
and run it again, it should show you the name you're looking for at the top of your app.
Well, I am right now doing some automation and have figured out a few things. Please see below code maybe it will help you out
public static void PSExec_Method()
{
try
{
string userName = #"ABC";
string password = "ABC";
string remoteMachine = "ABC";
//How to restart AppPool
//string operation = "stop";
//string apppoolname = "APPPOOL";
//string command = #"%SYSTEMROOT%\System32\inetsrv\appcmd " + operation + " apppool /apppool.name:\"" + apppoolname + "\"";
string command = #"powershell -noninteractive Get-Content C:\tmp\tmp.csv -Head 5";
//string command = #"ipconfig";
string PSPath = #"C:\PSTools\PsExec.exe";
string fullcommand = PSPath + " -u " + userName + " -p " + password + " \\\\" + remoteMachine + " -h cmd.exe /c " + command;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = fullcommand;
process.Start();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.WriteLine(process.StandardError.ReadToEnd());
process.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Related
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");
I am trying to run the following code which opens command prompt and then passes the parameters which opens chrome and navigates to www.google.com
The browser needs to open from Command Prompt.
I know you have to use /c when you pass arguments.
I have tried the following:
string arguments = "/c " + "\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe \"" + " www.google.com";
string arguments = "/c " + "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe " + "www.google.com";
Any ideas why the browser is not opening and not passing the parameters?
Code
public void ExecuteCmd()
{
int exitCode;
string arguments ="/c " + #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe " + "www.google.com";
// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
// Enter the executable to run, including the complete path
start.FileName = #"C:\Windows\system32\cmd.exe";
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
// Retrieve the app's exit code
exitCode = proc.ExitCode;
}
}
Here is what it looks like if I do it manually. It opens Chrome and passes the parameter.
Use this:
string arguments = #"/c """"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" http://www.google.de"""
That is, on the command prompt this would be equal to:
C:\>cmd /c ""C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.de"
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;
Use case: I am checking certain credentials on a remote system by running commands via PsExec (i.e. for this example, I am trying to retrieve the KB articles currently installed on the remote system).
I have the following to retrieve command output:
public string GetCmDOutput(string cmd)
ProcessStartInfo startInfo = new ProcessStartInfo("control", cmd)
{
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
string output = string.Empty;
Process process = Process.Start(startInfo);
process.OutputDataReceived += (sender, e) => output = string.Concat(output, e.Data);
process.BeginOutputReadLine();
process.Start();
process.WaitForExit();
Delay.Milliseconds(1500) //API-specific delay
return output;
}
Whenever I use GetCmdOutput() to run a command locally it works like a charm, but if I try to run a command with PsExec, my output is empty.
For instance, I ran the following:
string cmd = #"\psexec.exe \\remoteComputerName -u username -p password -c cmd /c wmic qfe";
GetCmdOutput(cmd);
Report.Info(cmd); //API-specific reporting
And an empty string was returned.
After playing around with this for a couple of hours, I feel I may need a second set of eyes. What might be causing this issue?
I have run into this same problem. My solution was to run cmd and have it call psexec. I have psexec's output saved to a temp file for further manipulation. My code is returning a List.
public List<string> ExecutePSExec(string hostname)
{
List<string> recordNames = new List<string>();
string command = #"\\path\to\psexec.exe /accepteula \\" + hostname + ". exe-to-run-remotely";
try
{
string location = AppDomain.CurrentDirectory.BaseDirectory;
string cmdWithFileOutput = string.Format("{0} >{1}temp.log", command, location);
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
// Read file contents, manipulate data and then delete temp file here
}
catch (Exception e)
{
Console.WriteLine("Failure to run psexec: {0}", e.Message);
}
return recordNames;
}
NOTE: I ran into another problem and found out that running psexec this way requires the remote hostname (not IP Address) in the command to end in a period \\" + hostname + ".
This code assumes you can run psexec on the remote machine as your current user.
I need to run a legacy app that is run from a cmd window using the Process class.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe –r " + Parameters.FullPath;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception e)
{
string sMsg = "Error copying the files to " + Parameters.FullPath + ".";
HandleErrorMsg(e, sMsg);
return;
}
The process My2Com.exe should run in the background, however, I consistantly get the message that a file, used when run from the cmd line with different flags, is missing. If I run the command as indicated in a cmd window, C:\MySys\My2Com.exe –r FullyQualPath, it works as expected. I have tried several different ways to set up the Process class without success.
Any suggestions would be appreciated.
Thank you.
Try this one -
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe –r\" " + Parameters.FullPath;
will this work if you do the following
startInfo.Arguments = #"/C "C:\MySys\My2Com.exe /r" " + Parameters.FullPath +"\"";
keep in mind that if there are spaces in the filepath you need to wrap around """ for example if the filepath were like this #"""C:\Wolf Lair\WorkDeskTemp\"
notice the # and the """
you need to append the ending quotes to the string +"\""; after Parameters.FullPath;
You know why is it not working because
You haven't completed quotes
Try this:-
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe\" –r \"" + Parameters.FullPath+"\"";
startInfo.Arguments = #"/C ""C:\MySys\My2Com.exe –r """ + Parameters.FullPath + "\"";
Also, see Sending commands to cmd prompt in C#. I'd recommended using some of the code from my answer there so that you can intercept the standard output and standard error to see what you're getting.