开发者

C# Web service: want to execute shell command as Admin (or higher priv.)

开发者 https://www.devze.com 2023-01-29 07:55 出处:网络
I have a web service which needs to execute a command on the server it\'s sitting on.Specifically, I\'m running the \"net start [certain service]\" command.The problem lies in the permissions... the w

I have a web service which needs to execute a command on the server it's sitting on. Specifically, I'm running the "net start [certain service]" command. The problem lies in the permissions... the web service is running as NETWORK SERVICE, which doesn't have the appropriate permissions to execute this command. Is there a way (possibly using Windows.Security) such that I can execute this as a higher privileged user.

** The command executes fine when ran locally, but this needs to be executed through the service (the point of the service...)

When attempting to impersonate a user, (using MSDN example, http://msdn.microsoft.com/en-us/library/chf6f开发者_开发问答bt4.aspx):

[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]

static public string Impersonate(string userName, string domainName, string password)

{

IntPtr tokenHandle = new IntPtr(0);

IntPtr dupeTokenHandle = new IntPtr(0); string output = "";

try { const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; output += "Set Token to ptrzero"; tokenHandle = IntPtr.Zero;

      output += "getting return value";
      //Call LogonUser to obtain a handle to an access token
      bool returnValue = LogonUser(userName, domainName,
                  password, LOGON32_LOGON_INTERACTIVE, 
                      LOGON32_PROVIDER_DEFAULT, ref tokenHandle);

      output += "LogonUser called";

      if (!returnValue)
      {
          int ret = Marshal.GetLastWin32Error();
          output += "\n LogonUser failed with error code: " + ret.ToString();
      }
      else
          output += "\nLogonUser succeeded!";

      //check the identity:
      output += "\n current: " + WindowsIdentity.GetCurrent().Name;

      WindowsIdentity newId = new WindowsIdentity(tokenHandle);
      WindowsImpersonationContext impersonatedUser = newId.Impersonate();

      //Check:
      output += "\n after: " + WindowsIdentity.GetCurrent().Name;
  }   
  catch (Exception ex)            
  {
  output += ex.ToString();            
  } 
  return output;      

}

I call the function to perform a shell execution, (Prior to execution I check if the current user is correct; which says the "current user" is my administrative-privileged account), but it still won't execute the same commands.


You should impersonate an admin user: Run Code as a different user (C#)

By the way, you shouldn't need to shell out to the net command. The ServiceController class can start and stop services.

0

精彩评论

暂无评论...
验证码 换一张
取 消