Подтвердить что ты не робот

Используя С#, как вы можете проверить, отключена ли учетная запись компьютера в активной директории?

Как вы проверяете, отключена ли учетная запись компьютера в Active Directory с помощью С#/. NET

4b9b3361

Ответ 1

Попробуйте следующее:

class Program
{
    static void Main(string[] args)
    {
        const string ldap = "LDAP://your-ldap-server-here";

        using (DirectoryEntry conn = new DirectoryEntry(ldap))
        {
            using (DirectorySearcher searcher = new DirectorySearcher(conn))
            {
                searcher.Filter = "(|(samAccountName=userA)(samAccountName=userB))";
                searcher.PropertiesToLoad.Add("samAccountName");
                searcher.PropertiesToLoad.Add("userAccountControl");

                using (SearchResultCollection results = searcher.FindAll())
                {
                    foreach (SearchResult result in results)
                    {
                        int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
                        string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
                        bool disabled = ((userAccountControl & 2) > 0);

                        Console.WriteLine("{0} ({1:x}) :: {2}", samAccountName, userAccountControl, disabled);
                    }
                }
            }
        }

        Console.ReadLine();
    }
}

Второй бит userAccountControl будет равен 1, если учетная запись отключена.

Ответ 3

Если вы используете .NET 3.5, вы можете использовать новые методы пространства имен System.DirectoryServices.AccountManagment для более простого доступа к Active Directory. Объект UserPrincipal имеет свойство Enabled, которое дает вам то, что вы ищете.

В январском выпуске журнала MSDN 2008 года есть хороший обзор этих подпрограмм. Вы можете прочитать статью онлайн здесь: Принципы управления безопасностью каталога в .NET Framework 3.5

Ответ 4

Ответ Леандро Лопеса классный и работает... другой вариант - мы можем сделать LINQ для userAccountControl со значениями отключить и отключить эти функции.

Ответ от userAccountControl:

512 Включенная учетная запись

514 Отключенная учетная запись

544 Включено, пароль не требуется

546 Отключено, пароль не требуется

66048 Включено, пароль не истекает

66050 Отключено, пароль не истекает

66080 Включено, пароль не истекает и не требуется

66082 Отключено, пароль не истекает и не требуется

262656 Включено, требуется смарт-карта

262658 Отключено, требуется смарт-карта

262688 Включено, требуется смарт-карта, пароль не требуется

262690 Отключено, требуется смарт-карта, пароль не требуется

328192 Включено, требуется смарт-карта, пароль не истекает

328194 Отключено, требуется смарт-карта, пароль не истекает

328224 Включено, требуется смарт-карта, пароль не истекает и не требуется

328226 Отключено, требуется смарт-карта, пароль не истекает и не требуется

Ответ 5

Без проверки бит, добавив:

(UserAccountControl: 1.2.840.113556.1.4.803: = 2)

на ваш фильтр должны возвращаться только отключенные пользователи. Конечно,

(UserAccountControl: 1.2.840.113556.1.4.803: = 2)

будет гарантировать, что пользователи не будут отключены, если вы предпочитаете идти по этому маршруту.

Ответ 6

Эй, я получил его окончательно:) вот мой код надеется, что это поможет вам

const int ADS_UF_ACCOUNTDISABLE = 0x00000002;

        DirectoryEntry de = new DirectoryEntry();
        de.Path = "LDAP://companyname.com";
        DirectorySearcher objADSearcher = new DirectorySearcher(de);
        de.AuthenticationType = AuthenticationTypes.Secure;

        objADSearcher.SearchRoot = de;
        objADSearcher.Filter = "(SAMAccountName=" + TextBox1.Text + ")";
        SearchResult results = objADSearcher.FindOne();
        if (results.ToString() !="")
        {

           int flags= Convert.ToInt32(results.Properties["userAccountControl"][0].ToString());

//для справки              results.Properties [ "UserAccountControl" ] [0].ToString() равно ( "514" );.

           if (Convert.ToBoolean(flags & ADS_UF_ACCOUNTDISABLE))
           {
               Response.Write("Account Disabled");
           }

Ответ 7

Если вы используете имя samAcountName или любое другое поле Identity, проще всего использовать метод UserPrincipal.FindByIdentity. И используйте гибридный подход к Leandro López и Deepti. оба подхода очень хороши, но очень узко сфокусированы. Более подробную информацию об этом флаге можно найти на MSDN

Ответ 8

Вы можете легко декодировать свойство userAccountControl, преобразовывая результат в перечисление.

int userAccountControlValue = 544;
UserAccountControl userAccountControl = (UserAccountControl) userAccountControlValue;

// This gets a comma separated string of the flag names that apply.
string userAccountControlFlagNames = userAccountControl.ToString();

// This is how you test for an individual flag.
bool isNormalAccount = (userAccountControl & UserAccountControl.NORMAL_ACCOUNT) == UserAccountControl.NORMAL_ACCOUNT;
bool isAccountDisabled = (userAccountControl & UserAccountControl.ACCOUNTDISABLE) == UserAccountControl.ACCOUNTDISABLE;
bool isAccountLockedOut = (userAccountControl & UserAccountControl.LOCKOUT) == UserAccountControl.LOCKOUT;

Вы также можете использовать его для создания фильтра LDAP:

// To get a user that is disabled.
string ldapFilter = string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0})(userAccountControl:1.2.840.113556.1.4.803:={1:D}))", accountName, UserAccountControl.ACCOUNTDISABLE)

// To get a user that is not disabled.
string ldapFilter = string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0})(!(userAccountControl:1.2.840.113556.1.4.803:={1:D})))", accountName, UserAccountControl.ACCOUNTDISABLE)

Также см. Active Directory: Фильтры синтаксиса LDAP для примеров часто используемых фильтров LDAP Active Directory.

Здесь вы найдете определение перечисления:

/// <summary>
/// Flags that control the behavior of the user account.
/// </summary>
[Flags()]
public enum UserAccountControl : int
{
    /// <summary>
    /// The logon script is executed. 
    ///</summary>
    SCRIPT = 0x00000001,

    /// <summary>
    /// The user account is disabled. 
    ///</summary>
    ACCOUNTDISABLE = 0x00000002,

    /// <summary>
    /// The home directory is required. 
    ///</summary>
    HOMEDIR_REQUIRED = 0x00000008,

    /// <summary>
    /// The account is currently locked out. 
    ///</summary>
    LOCKOUT = 0x00000010,

    /// <summary>
    /// No password is required. 
    ///</summary>
    PASSWD_NOTREQD = 0x00000020,

    /// <summary>
    /// The user cannot change the password. 
    ///</summary>
    /// <remarks>
    /// Note:  You cannot assign the permission settings of PASSWD_CANT_CHANGE by directly modifying the UserAccountControl attribute. 
    /// For more information and a code example that shows how to prevent a user from changing the password, see User Cannot Change Password.
    // </remarks>
    PASSWD_CANT_CHANGE = 0x00000040,

    /// <summary>
    /// The user can send an encrypted password. 
    ///</summary>
    ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0x00000080,

    /// <summary>
    /// This is an account for users whose primary account is in another domain. This account provides user access to this domain, but not 
    /// to any domain that trusts this domain. Also known as a local user account. 
    ///</summary>
    TEMP_DUPLICATE_ACCOUNT = 0x00000100,

    /// <summary>
    /// This is a default account type that represents a typical user. 
    ///</summary>
    NORMAL_ACCOUNT = 0x00000200,

    /// <summary>
    /// This is a permit to trust account for a system domain that trusts other domains. 
    ///</summary>
    INTERDOMAIN_TRUST_ACCOUNT = 0x00000800,

    /// <summary>
    /// This is a computer account for a computer that is a member of this domain. 
    ///</summary>
    WORKSTATION_TRUST_ACCOUNT = 0x00001000,

    /// <summary>
    /// This is a computer account for a system backup domain controller that is a member of this domain. 
    ///</summary>
    SERVER_TRUST_ACCOUNT = 0x00002000,

    /// <summary>
    /// Not used. 
    ///</summary>
    Unused1 = 0x00004000,

    /// <summary>
    /// Not used. 
    ///</summary>
    Unused2 = 0x00008000,

    /// <summary>
    /// The password for this account will never expire. 
    ///</summary>
    DONT_EXPIRE_PASSWD = 0x00010000,

    /// <summary>
    /// This is an MNS logon account. 
    ///</summary>
    MNS_LOGON_ACCOUNT = 0x00020000,

    /// <summary>
    /// The user must log on using a smart card. 
    ///</summary>
    SMARTCARD_REQUIRED = 0x00040000,

    /// <summary>
    /// The service account (user or computer account), under which a service runs, is trusted for Kerberos delegation. Any such service 
    /// can impersonate a client requesting the service. 
    ///</summary>
    TRUSTED_FOR_DELEGATION = 0x00080000,

    /// <summary>
    /// The security context of the user will not be delegated to a service even if the service account is set as trusted for Kerberos delegation. 
    ///</summary>
    NOT_DELEGATED = 0x00100000,

    /// <summary>
    /// Restrict this principal to use only Data Encryption Standard (DES) encryption types for keys. 
    ///</summary>
    USE_DES_KEY_ONLY = 0x00200000,

    /// <summary>
    /// This account does not require Kerberos pre-authentication for logon. 
    ///</summary>
    DONT_REQUIRE_PREAUTH = 0x00400000,

    /// <summary>
    /// The user password has expired. This flag is created by the system using data from the Pwd-Last-Set attribute and the domain policy. 
    ///</summary>
    PASSWORD_EXPIRED = 0x00800000,

    /// <summary>
    /// The account is enabled for delegation. This is a security-sensitive setting; accounts with this option enabled should be strictly 
    /// controlled. This setting enables a service running under the account to assume a client identity and authenticate as that user to 
    /// other remote servers on the network.
    ///</summary>
    TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0x01000000,

    /// <summary>
    /// 
    /// </summary>
    PARTIAL_SECRETS_ACCOUNT = 0x04000000,

    /// <summary>
    /// 
    /// </summary>
    USE_AES_KEYS = 0x08000000
}