How to shutdown machine from ASP.NET - c#

I have a machine running Windows Home Server v1 (WHS is based on Windows Server 2003 and is runningh IIS6) and on here I have a restful webservice running which I build in C# VS2008 (dotnet 3.5). From within the webservice I want to be able to;
1 Check that certain windows services are running;
2 Start certain windows services
3 Stop certain windows services
4 Reboot the machine
5 Shutdown the machine
For 1-3 then I am using impersonation to elevate the ASPNET user to the local administrator (it is only me running this on a local secure network) and then "ServiceController" to control the services. This works perfectly.
For for 4 & 5 I am having issues and can't get it to work.
If I use System.Diagnostics.Process to call the "shutdown.exe" command with the parameters "/s /f" then the process executes without any errors but does not do anything! No shutdown, no exception nothing and I can't work out why. I have tried setting the local admin username & password but it does not help, and the impersonate user call does not help.
My code
string shut_args = "/s /f /t 10";
Process process1 = new Process();
process1.StartInfo.FileName = "shutdown.exe";
process1.StartInfo.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System);
SecureString password = new SecureString();
foreach (char c in "mypassword")
password.AppendChar(c);
process1.StartInfo.Password = password;
process1.StartInfo.Domain = "homeserver";
process1.StartInfo.UserName = "Administrator";
process1.StartInfo.Arguments = shut_args;
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
impersonateValidUser();
process1.Start();
So instead I tried to use WMI (code taken from another post on here) but here I get an "Privilege not held" error when trying to call InvokeMethod
Mycode
ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass ("Win32_OperatingSystem"); mcWin32.Get();
mcWin32.Scope.Options.Impersonation = ImpersonationLevel.Impersonate;
mcWin32.Scope.Options.Authentication = AuthenticationLevel.Connect;
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
// Flag 1 means we want to shut down the system. Use "2" to reboot.
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
}
I have also been through all of my security settings for the ASPNET and NETWORK_SERVICE user and they have rights to shutdown the server, the WMI security settings are also set-up for these users. But I just can't figure out what is wrong.
Any ideas?
Cheers

Have you tried to run a simple batch file instead of starting up the shutdown process in ASP.NET ?
The whole process is described here: remote shutdown/restart using ASP.NET

Old question, but I wanted to do this myself, and just figured out the answer. So try this:
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "shutdown";
startInfo.Arguments = "/s /t 5";
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();

Related

How can I start a foreground process in C#?

An example, when I'm debugging with Visual Studio, Google Chrome opens normally.
When I install the Windows service on the machine, Google Chrome opens, but in the background.
The background issue is that Google Chrome is running in a hidden way on the system.
My Windows Service running as Local System account.
string batPath = "C:\\Teste\\start.bat";
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = batPath;
processInfo.WorkingDirectory = Path.GetDirectoryName(batPath);
processInfo.ErrorDialog = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
Process proc = Process.Start(processInfo);

C# - Starting process under different user than the IIS application pool user

public static string StartProcess(string cmd, string args, string workingDirectory, string username, string password)
{
// launch system process
ProcessStartInfo startInfo = new ProcessStartInfo(cmd, args);
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.UserName = username;
startInfo.Password = ConvertStringToSecureString(password);
// get working directory from executable path
if (String.IsNullOrEmpty(workingDirectory))
{
startInfo.WorkingDirectory = Path.GetDirectoryName(cmd);
}
else
{
startInfo.WorkingDirectory = workingDirectory;
}
var results = new StringBuilder();
using (var process = Process.Start(startInfo))
{
process.StandardInput.Flush();
process.StandardInput.Close();
var reader = process.StandardOutput;
string lineOut;
while ((lineOut = reader.ReadLine()) != null)
{
results.AppendLine(lineOut);
}
while (!process.HasExited) System.Threading.Thread.Sleep(1000);
}
return results.ToString();
}
I am trying to launch a process from within my IIS application using a different username / password than the one that the IIS application pool is operating under.
The IIS app pool is running under a full admin user, and when the process starts, it completes, the result is return, no issues. When I specify a username / password, the process starts, then immediately closes.
I also have
Application popup: conhost.exe - Application Error : The application was unable to start correctly (0xc0000142). Click OK to close the application.
in my event logs. If I take the above code and put into its own exe file and run it via the desktop using the same admin user IIS is running under, the process starts (using the username / password for the other user) and completes without issues.
It appears to just be limited to IIS. Am I missing something?
For me chaging the user/process id of the application pool of my site worked.
Go to IIS Manager -> app pools -> select your pool -> advanced settings
-> under process model you can set your identity for example to your local admin account.

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.

cscript crashes when starting a process from ASP.NET Application

I´m having a problem with my ASP application. I´m getting an error from the cscript when I run a process on the server.
When I debug locally the page just works fine and the process is executed correctly, but when I deploy the application to the IIS and run it from another machine explorer it crashes when the process starts.
I imagine it was a matter of the user, so I added this line to the web.config, to ensure that.
<identity impersonate="true" userName="domain\user" password="password" />
Then, I added the user that I wanted the process to start with but the page keeps crashing. The error that I get in the server side each time the process is launch (when a button is pressed) is:
cscript.exe - Application Error
The application failed to initialize properly (0xc0000142). Click on OK to terminate the application
The code that launches the process is:
public static void actualizarPersona(csPersona persona)
{
string nombreArchivo = "card.js";
File.WriteAllText(nombreArchivo, persona.setFileActualizarPersona(persona), Encoding.GetEncoding(1252));
Process proc = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.FileName = "cscript.exe";
startInfo.Arguments = nombreArchivo;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UserName = "Administrator";
SecureString password = new SecureString();
string contraseña = "myPassword";
foreach (char c in contraseña)
{
password.AppendChar(c);
}
startInfo.Password = password;
proc.StartInfo = startInfo;
proc.Start();
proc.WaitForExit();
proc.Close();
proc.Dispose();
}
Does anyone have any idea of what may be happening?. I´ve been stuck here for a while today.
Thanks you.
You may need to load the user's profile
startInfo.LoadUserProfile = true
Edit
Try creating a new app pool with a a new admin account. If that works remove the user from the admin group and create a new group with the necessary permissions for the app.
(see trying to run a process from an asp.net application)

I want PDF file print into network print

I want PDF file print into network print
Following code where used, it work fine in local host (development area) but not worked in IIS serve host
Can given to any rights issue? How to solve the issue ?
private void SendToPrinter()
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = #"c:\output.pdf";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
System.Threading.Thread.Sleep(3000);
if (false == p.CloseMainWindow())
p.Kill();
}
It might be an authorization/security problem.
IIS (the server) runs in a context which doesn't have access to the shared printer.
Your local host has it cause it's running in your user's context.

Categories