尝试管理远程iis7池的System.Runtime.InteropServices.COMException

时间:2014-06-30 10:14:46

标签: c# iis-7 impersonation

我正在编写一个工具来自动将多个网站部署到远程计算机,我需要在网站发布期间管理一些IIS7池。

我写了一个函数来管理没有模拟的本地池,它运行良好,所以我这样编辑:

[DllImport("advapi32.DLL", SetLastError = true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

public static void ManagePool(string command, string appPool)
{
    IntPtr admin_token = default(IntPtr);
    WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
    WindowsIdentity wid_admin = null;
    WindowsImpersonationContext wic = null;
    try
    {
        if (LogonUser("username", "domain", "password, 9, 0, ref admin_token) != 0)
        {
            wid_admin = new WindowsIdentity(admin_token);
            wic = wid_admin.Impersonate();

            using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPool))
            {
                appPoolEntry.Invoke(command, null);
                appPoolEntry.Close();
            }
        }
    }
    catch (System.Exception se)
    {
        int ret = Marshal.GetLastWin32Error();
        log.append("Error code: " + ret.ToString());
        log.append(se.Message);
    }
    finally
    {
        if (wic != null)
        {
            wic.Undo();
        }
    }
}

但是当我尝试拨打ManagePool("Stop", "IIS://172.23.231.199/W3SVC/AppPools/My Pool")时,我收到此错误:

Unknown error (0x80005000) 
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_NativeObject()
   at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)

如何远程管理它们?有没有办法让它有效?

1 个答案:

答案 0 :(得分:0)

我决定:

IntPtr admin_token = default(IntPtr);
WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
WindowsIdentity wid_admin = null;
WindowsImpersonationContext wic = null;
try
{
    if (LogonUser("username", "domain", "password", 9, 0, ref admin_token) != 0)
    {
        wid_admin = new WindowsIdentity(admin_token);
        wic = wid_admin.Impersonate();
        ServerManager.OpenRemote("123.123.123.123").ApplicationPools["My Pool"].Start();
    }
}

感谢几乎压倒性的回复流

:P