1

我一直在尝试解决这个问题,不幸的是仍然没有成功。我可以远程访问服务器并拥有服务器的权限。我们在同一个域上,但不幸的是,当我的程序试图控制服务器服务时,我得到了这个错误。RPC 服务器不可用。

    public static void Main()
    {
        using (new Impersonation("domain", "Server", "Password"))
        {
            Control myControl = new Control("ServiceName", "Server");
            // do whatever you want

            myControl.StopService();
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

这是模拟代码。我在 StackOverFlow 的另一个表单上找到了这段代码,但仍然有问题。

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonation : IDisposable
{
    private readonly SafeTokenHandle _handle;
    private readonly WindowsImpersonationContext _context;

    const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

    public Impersonation(string domain, string username, string password)
    {
        var ok = LogonUser(username, domain, password,
                       LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle);
        if (!ok)
        {
            var errorCode = Marshal.GetLastWin32Error();
            throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
        }

        this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
    }

    public void Dispose()
    {
        this._context.Dispose();
        this._handle.Dispose();
    }

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true) { }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

这是控制类的代码。

    public Control(string serviceName, string computerName)
    {
        service = new ServiceController("serviceName", "ServerName");
    }

    public bool StopService()
    {

        try
        {
            if (service.Status == ServiceControllerStatus.Running)
            {
                service.Stop();
                return true;
            }

            MessageBox.Show(string.Format("{0} --> already stopped", service.DisplayName));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), @"Error Stopping Service");
        }

        return false;
    }
4

0 回答 0