2016-01-21 14 views
6

Uzyskiwanie wyjątek z tym kodem ... mimo iż mam uprawnień administratora na komputerze zdalnymJak uruchomić lub zatrzymać program IIS, a także usługa systemu Windows na komputerze zdalnym przy użyciu C#

class Program 
    { 
     static void Main(string[] args) 
     { 
      var sc = new System.ServiceProcess.ServiceController("W3SVC", "10.201.58.114"); 
      sc.Start(); 
      sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);    
      sc.Stop(); 
      sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); 
     } 
    } 

Exception:

nieobsługiwany wyjątek typu „System.InvalidOperationException” wystąpił w System.ServiceProcess.dll

informacje dodatkowe: nie można otworzyć usługi C ontrol Manager na komputerze '10 .201.58.114 '. Ta operacja może wymagać innych uprawnień.

+0

Czy system docelowy jest wolny od oprogramowania zabezpieczającego? Przekonasz się, że niektóre oprogramowanie zabezpieczające może mieć taki efekt. – Xefan

+1

może pomóc w uruchomieniu aplikacji "As Administrator"? również przy założeniu, że masz prawa do IP pod warunkiem, że ... – vidriduch

+0

Z wierszem polecenia używanym jako administrator: 'C: \> iisreset.exe ', Błąd pobierania jako:' Odmowa dostępu, musisz być administratorem komputera zdalnego, aby móc używać tego polecenia. Albo twoje konto zostanie dodane do lokalnej grupy administratora na komputerze zdalnym lub do globalnej grupy administratora domeny. "Należy pamiętać, że mam prawa administratora na zdalnym komputerze, ale wciąż pojawia się błąd. – venkat

Odpowiedz

0

Wygląda na to, że nie są dodawane do administratorów LOCALGROUP

Sprawdź to z

administratorów LOCALGROUP netto

na zdalnej maszynie

jeśli użytkownik jest nie na liście, uruchom

Administratorzy localgroup netto/dodaj użytkownika

+0

Moje nazwisko jest już wymienione w grupie lokalnej administratorów. Ale wciąż otrzymuję ten sam wyjątek. – venkat

1

są maszyny w tej samej domenie? Jeśli nie, to Administrator na maszynie1 nie jest równoważne Administrator na maszynie2, więc to może być twój problem.

Jedną z możliwości jest to, że trzeba udzielić dostępu dla użytkownika - na zdalnym komputerze - aby zatrzymać i uruchomić usługę tak:

SUBINACL /SERVICE \\<MACHINE>\W3SVC /GRANT=<MACHINE>\<USER>=TO 

Jest przykładem tego w komentarzach drugiego kodu blok poniżej (ponieważ potrzebowałem tego nawet przy podszywaniu się pod kod).

Jeśli to nie rozwiąże problemu, możesz spróbować podszyć się pod użytkownika zdalnego. Udało mi się to zrobić działając przy użyciu następującego kodu.

Najpierw utwórz nowy WrapperImpersonationContext.cs Klasa:

using System; 
using System.Runtime.InteropServices; 
using System.Security.Principal; 
using System.Security.Permissions; 
using System.ComponentModel; 

//Version from http://michiel.vanotegem.nl/2006/07/windowsimpersonationcontext-made-easy/ 

public class WrapperImpersonationContext 
{ 
    [DllImport("advapi32.dll", SetLastError = true)] 
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, 
     String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); 

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
    public extern static bool CloseHandle(IntPtr handle); 

    private const int LOGON32_PROVIDER_DEFAULT = 0; 
    private const int LOGON32_LOGON_INTERACTIVE = 2; 

    private string m_Domain; 
    private string m_Password; 
    private string m_Username; 
    private IntPtr m_Token; 

    private WindowsImpersonationContext m_Context = null; 


    protected bool IsInContext 
    { 
     get { return m_Context != null; } 
    } 

    public WrapperImpersonationContext(string domain, string username, string password) 
    { 
     m_Domain = domain; 
     m_Username = username; 
     m_Password = password; 
    } 

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] 
    public void Enter() 
    { 
     if (this.IsInContext) return; 
     m_Token = new IntPtr(0); 
     try 
     { 
      m_Token = IntPtr.Zero; 
      bool logonSuccessfull = LogonUser(
       m_Username, 
       m_Domain, 
       m_Password, 
       LOGON32_LOGON_INTERACTIVE, 
       LOGON32_PROVIDER_DEFAULT, 
       ref m_Token); 
      if (logonSuccessfull == false) 
      { 
       int error = Marshal.GetLastWin32Error(); 
       throw new Win32Exception(error); 
      } 
      WindowsIdentity identity = new WindowsIdentity(m_Token); 
      m_Context = identity.Impersonate(); 
     } 
     catch (Exception exception) 
     { 
      // Catch exceptions here 
     } 
    } 


    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] 
    public void Leave() 
    { 
     if (this.IsInContext == false) return; 
     m_Context.Undo(); 

     if (m_Token != IntPtr.Zero) CloseHandle(m_Token); 
     m_Context = null; 
    } 
} 

Następnie powinieneś być w stanie wykonać następujące czynności. Zauważ, że będziesz musiał zmienić nazwę komputera, nazwę użytkownika i hasło, aby dopasować konfigurację. Warto też zwrócić uwagę na komentarze jak tam ważne informacje ustawień zabezpieczeń, które odkryłem po drodze:

//Code for Program.cs demonstrating the identity impersonation for a ServiceController. 

using System; 
using System.Security.Principal; 
using System.ServiceProcess; 

namespace RemoteConnectionTest 
{ 
    class MainClass 
    { 
     public static void Main (string[] args) 
     { 

      try { 

       //Based on the code from http://michiel.vanotegem.nl/2006/07/windowsimpersonationcontext-made-easy/ 

       Console.WriteLine("Current user: " + WindowsIdentity.GetCurrent().Name); 
       //Also worked with the IP address of GARNET (which was the machine name). 
       WrapperImpersonationContext context = new WrapperImpersonationContext("GARNET", "TestAdmin1", "password123"); 
       context.Enter(); 
       // Execute code under other uses context 
       Console.WriteLine("Current user: " + WindowsIdentity.GetCurrent().Name); 

       // Code to execute. 

       //Try running the following command on the remote server first to ensure 
       //the user has the appropriate access (obviously substitute the 
       //username and machine name). 
       // runas /user:TestAdmin "sc \\GARNET stop W3SVC" 

       //Also, make sure the user on the remote server has access for 
       //services granted as described here: http://stackoverflow.com/a/5084563/201648 
       //Otherwise you may see an error along the lines of: 
       //Cannot open W3SVC service on computer '<SERVER>'. ---> System.ComponentModel.Win32Exception: Access is denied 
       //For my configuration I had to run the command: 
       // SUBINACL /SERVICE \\GARNET\W3SVC /GRANT=GARNET\TestAdmin=TO 
       //It's entirely possible that running this command will allow your existing code to work without using impersonation. 

       //You may need to install SUBINACL https://www.microsoft.com/en-au/download/details.aspx?id=23510 
       //By default SUBINACL will install to C:\Program Files (x86)\Windows Resource Kits\Tools 
       //so CD to that directory and then run the SUBINACL command above. 

       //Also worked with the IP address of GARNET (which was the machine name). 
       var sc = new ServiceController("W3SVC", "GARNET"); 
       sc.Start(); 

       sc.WaitForStatus(ServiceControllerStatus.Running);    
       sc.Stop(); 
       sc.WaitForStatus(ServiceControllerStatus.Stopped); 

       //END - code to execute. 
       context.Leave(); 
       Console.WriteLine("Your code ran successfully. Current user: " + WindowsIdentity.GetCurrent().Name); 

      } catch (Exception ex) { 
       Console.WriteLine("An exception occured - details as follows: {0}", ex.Message); 
       Console.WriteLine("The full stack trace is: {0}", ex); 
      } 

      Console.WriteLine ("Press any key to exit..."); 
      Console.ReadLine(); 

     } 
    } 

} 

upewnić się, że urządzenie zdalne może być oceniana przy użyciu dostarczonych poświadczeń, zanim spróbujesz to zrobić w kodzie np łącząc się jako ten użytkownik poprzez zdalny pulpit.

+0

** Błąd **: "Nie można znaleźć nazwy typu lub przestrzeni nazw" RemoteAccessHelper "(czy brakuje instrukcji użycia lub odniesienia do zespołu?)' – venkat

+0

Czy spojrzałeś na kod w tutorialu http: // dotnet- assembly.blogspot.com.au/2012/11/c-accessing-remote-file-by-using.html –

+0

Aby wyjaśnić 1) określ komputer/nazwę domeny zdalnego komputera 2) spróbuj połączyć się z pilotem maszynę z komputera, na której twój kod będzie działał przy użyciu tej nazwy komputera/domeny oraz nazwy użytkownika i hasła poza kodem, np za pomocą zdalnego pulpitu 3), jeśli ci się uda, spróbuj podróbki C# na podstawie kodu w tym samouczku. Czy wiesz, czy jesteś w domenie, czy nie? Jeśli oba urządzenia znajdują się w tej samej domenie, może to być inny problem. –

Powiązane problemy