AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 1161995
Accepted
ocroquette
ocroquette
Asked: 2024-07-04 14:23:28 +0800 CST2024-07-04 14:23:28 +0800 CST 2024-07-04 14:23:28 +0800 CST

No Active Directory, como sincronizar automaticamente os membros de um grupo com base nos atributos dos usuários?

  • 772

No Active Directory local, gostaria de manter listas de distribuição e grupos de segurança com base nos atributos dos usuários, por exemplo, o gerente, o departamento, a cidade.

windows
  • 1 1 respostas
  • 82 Views

1 respostas

  • Voted
  1. Best Answer
    ocroquette
    2024-07-04T14:23:28+08:002024-07-04T14:23:28+08:00

    Infelizmente, o Windows não oferece esse recurso imediatamente, mas é relativamente fácil de implementar como um script Powershell, que pode ser executado como uma tarefa agendada.

    Aqui está o arquivo que contém a função correspondente. É chamado AD2DL como em "Active Directory To Distribution List", mas também funciona com grupos de segurança.

    AD2DL.ps1
    
    # https://serverfault.com/questions/1161995/in-active-directory-how-to-synchronize-the-members-of-a-group-automatically-bas/1161996
    
    function Sync-AD2DL {
        param (
            # Example AdGroupName: "MyGroup"
            [string]$AdGroupName,
            # Example filters:
            #   "*"
            #   "Department -eq 'IT'"
            #   "Department -like 'IT'"
            #   "Manager -eq 'someone' -or SamAccountName -eq 'someone'"
            #   "City -eq 'Berlin' -and SamAccountName -ne 'exception'"
            # See below for all properties
            [string]$Filter,
            # Example OrganisationalUnits: @("OU=Users,dc=domain,dc=tld")
            [string[]]$OrganisationalUnits
       )
    
        $expectedMembers = @()
    
        foreach($ou in $OrganisationalUnits)
        {
            $matchingUsers = Get-ADUser -SearchBase $ou -Filter $filter
    
            # Filter out accounts that are disabled:
            $matchingUsers = $matchingUsers | Where { $_.Enabled }
    
            $expectedMembers += $matchingUsers
        }
    
        # Write-Host "expectedMembers=" $currentMembers
    
        $expectedNames = $expectedMembers | select -ExpandProperty DistinguishedName
    
        $currentMembers = Get-ADGroupMember -Identity $AdGroupName
        $currentNames = $currentMembers | select -ExpandProperty DistinguishedName
        $oldLength = $currentMembers.Length
    
        # Write-Host "currentMembers=" $currentMembers
    
        $usersToAdd = $expectedMembers | Where-Object { $currentNames -notcontains $_.DistinguishedName }
    
        foreach($user in $usersToAdd)
        {
            Write-Host "Adding " $user " to " $AdGroupName
            Add-ADGroupMember -Identity $AdGroupName -Members $user.samaccountname -ErrorAction SilentlyContinue
        }
    
        $usersToRemove = $currentMembers | Where-Object { $expectedNames -notcontains $_.DistinguishedName }
    
        foreach($user in $usersToRemove)
        {
            Write-Host "Removing " $user " from " $AdGroupName
            Remove-ADGroupMember -Identity $AdGroupName -Members $user.samaccountname -Confirm:$false
        }
    
        $newLength = (Get-ADGroupMember -Identity $AdGroupName).Length
        Write-Host $AdGroupName " Added:" $usersToAdd.Length "  Removed:" $usersToRemove.Length "New size:" $newLength
    }
    
    
    # All user properties, for reference, retrieved with "Get-Member":
    #
    # AccountExpirationDate                 Property              System.DateTime AccountExpirationDate {get;set;}
    # accountExpires                        Property              System.Int64 accountExpires {get;set;}
    # AccountLockoutTime                    Property              System.DateTime AccountLockoutTime {get;set;}
    # AccountNotDelegated                   Property              System.Boolean AccountNotDelegated {get;set;}
    # AllowReversiblePasswordEncryption     Property              System.Boolean AllowReversiblePasswordEncryption {get;set;}
    # AuthenticationPolicy                  Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection AuthenticationPolicy {get;set;}
    # AuthenticationPolicySilo              Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection AuthenticationPolicySilo {get;set;}
    # BadLogonCount                         Property              System.Int32 BadLogonCount {get;}
    # badPasswordTime                       Property              System.Int64 badPasswordTime {get;set;}
    # badPwdCount                           Property              System.Int32 badPwdCount {get;set;}
    # c                                     Property              System.String c {get;set;}
    # CannotChangePassword                  Property              System.Boolean CannotChangePassword {get;set;}
    # CanonicalName                         Property              System.String CanonicalName {get;}
    # Certificates                          Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Certificates {get;set;}
    # City                                  Property              System.String City {get;set;}
    # CN                                    Property              System.String CN {get;}
    # co                                    Property              System.String co {get;set;}
    # codePage                              Property              System.Int32 codePage {get;set;}
    # Company                               Property              System.String Company {get;set;}
    # CompoundIdentitySupported             Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection CompoundIdentitySupported {get;set;}
    # Country                               Property              System.String Country {get;set;}
    # countryCode                           Property              System.Int32 countryCode {get;set;}
    # Created                               Property              System.DateTime Created {get;}
    # createTimeStamp                       Property              System.DateTime createTimeStamp {get;}
    # Deleted                               Property              System.Boolean Deleted {get;}
    # Department                            Property              System.String Department {get;set;}
    # Description                           Property              System.String Description {get;set;}
    # DisplayName                           Property              System.String DisplayName {get;set;}
    # DistinguishedName                     Property              System.String DistinguishedName {get;set;}
    # Division                              Property              System.String Division {get;set;}
    # DoesNotRequirePreAuth                 Property              System.Boolean DoesNotRequirePreAuth {get;set;}
    # dSCorePropagationData                 Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection dSCorePropagationData {get;}
    # EmailAddress                          Property              System.String EmailAddress {get;set;}
    # EmployeeID                            Property              System.String EmployeeID {get;set;}
    # EmployeeNumber                        Property              System.String EmployeeNumber {get;set;}
    # Enabled                               Property              System.Boolean Enabled {get;set;}
    # Fax                                   Property              System.String Fax {get;set;}
    # GivenName                             Property              System.String GivenName {get;set;}
    # HomeDirectory                         Property              System.String HomeDirectory {get;set;}
    # HomedirRequired                       Property              System.Boolean HomedirRequired {get;set;}
    # HomeDrive                             Property              System.String HomeDrive {get;set;}
    # homeMDB                               Property              System.String homeMDB {get;set;}
    # HomePage                              Property              System.String HomePage {get;set;}
    # HomePhone                             Property              System.String HomePhone {get;set;}
    # Initials                              Property              System.String Initials {get;set;}
    # instanceType                          Property              System.Int32 instanceType {get;}
    # isDeleted                             Property              System.Boolean isDeleted {get;}
    # KerberosEncryptionType                Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection KerberosEncryptionType {get;set;}
    # l                                     Property              System.String l {get;set;}
    # LastBadPasswordAttempt                Property              System.DateTime LastBadPasswordAttempt {get;}
    # LastKnownParent                       Property              System.String LastKnownParent {get;}
    # lastLogoff                            Property              System.Int64 lastLogoff {get;set;}
    # lastLogon                             Property              System.Int64 lastLogon {get;set;}
    # LastLogonDate                         Property              System.DateTime LastLogonDate {get;}
    # lastLogonTimestamp                    Property              System.Int64 lastLogonTimestamp {get;set;}
    # legacyExchangeDN                      Property              System.String legacyExchangeDN {get;set;}
    # LockedOut                             Property              System.Boolean LockedOut {get;set;}
    # lockoutTime                           Property              System.Int64 lockoutTime {get;set;}
    # logonCount                            Property              System.Int32 logonCount {get;set;}
    # LogonWorkstations                     Property              System.String LogonWorkstations {get;set;}
    # mail                                  Property              System.String mail {get;set;}
    # mailNickname                          Property              System.String mailNickname {get;set;}
    # Manager                               Property              System.String Manager {get;set;}
    # mDBUseDefaults                        Property              System.Boolean mDBUseDefaults {get;set;}
    # MemberOf                              Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection MemberOf {get;}
    # MNSLogonAccount                       Property              System.Boolean MNSLogonAccount {get;set;}
    # MobilePhone                           Property              System.String MobilePhone {get;set;}
    # Modified                              Property              System.DateTime Modified {get;}
    # modifyTimeStamp                       Property              System.DateTime modifyTimeStamp {get;}
    # mS-DS-ConsistencyGuid                 Property              System.Byte[] mS-DS-ConsistencyGuid {get;set;}
    # msDS-SupportedEncryptionTypes         Property              System.Int32 msDS-SupportedEncryptionTypes {get;set;}
    # msDS-User-Account-Control-Computed    Property              System.Int32 msDS-User-Account-Control-Computed {get;}
    # msExchArchiveQuota                    Property              System.Int64 msExchArchiveQuota {get;set;}
    # msExchArchiveWarnQuota                Property              System.Int64 msExchArchiveWarnQuota {get;set;}
    # msExchCalendarLoggingQuota            Property              System.Int32 msExchCalendarLoggingQuota {get;set;}
    # msExchDumpsterQuota                   Property              System.Int32 msExchDumpsterQuota {get;set;}
    # msExchDumpsterWarningQuota            Property              System.Int32 msExchDumpsterWarningQuota {get;set;}
    # msExchELCMailboxFlags                 Property              System.Int32 msExchELCMailboxFlags {get;set;}
    # msExchHomeServerName                  Property              System.String msExchHomeServerName {get;set;}
    # msExchMailboxGuid                     Property              System.Byte[] msExchMailboxGuid {get;set;}
    # msExchMailboxSecurityDescriptor       Property              System.DirectoryServices.ActiveDirectorySecurity msExchMailboxSecurityDescriptor {get;set;}
    # msExchMobileMailboxFlags              Property              System.Int32 msExchMobileMailboxFlags {get;set;}
    # msExchPoliciesIncluded                Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection msExchPoliciesIncluded {get;set;}
    # msExchRBACPolicyLink                  Property              System.String msExchRBACPolicyLink {get;set;}
    # msExchRecipientDisplayType            Property              System.Int32 msExchRecipientDisplayType {get;set;}
    # msExchRecipientTypeDetails            Property              System.Int64 msExchRecipientTypeDetails {get;set;}
    # msExchTextMessagingState              Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection msExchTextMessagingState {get;set;}
    # msExchUMDtmfMap                       Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection msExchUMDtmfMap {get;set;}
    # msExchUserAccountControl              Property              System.Int32 msExchUserAccountControl {get;set;}
    # msExchUserCulture                     Property              System.String msExchUserCulture {get;set;}
    # msExchVersion                         Property              System.Int64 msExchVersion {get;set;}
    # msExchWhenMailboxCreated              Property              System.DateTime msExchWhenMailboxCreated {get;set;}
    # Name                                  Property              System.String Name {get;}
    # nTSecurityDescriptor                  Property              System.DirectoryServices.ActiveDirectorySecurity nTSecurityDescriptor {get;set;}
    # ObjectCategory                        Property              System.String ObjectCategory {get;}
    # ObjectClass                           Property              System.String ObjectClass {get;set;}
    # ObjectGUID                            Property              System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e0...
    # objectSid                             Property              System.Security.Principal.SecurityIdentifier objectSid {get;}
    # Office                                Property              System.String Office {get;set;}
    # OfficePhone                           Property              System.String OfficePhone {get;set;}
    # Organization                          Property              System.String Organization {get;set;}
    # OtherName                             Property              System.String OtherName {get;set;}
    # PasswordExpired                       Property              System.Boolean PasswordExpired {get;set;}
    # PasswordLastSet                       Property              System.DateTime PasswordLastSet {get;set;}
    # PasswordNeverExpires                  Property              System.Boolean PasswordNeverExpires {get;set;}
    # PasswordNotRequired                   Property              System.Boolean PasswordNotRequired {get;set;}
    # POBox                                 Property              System.String POBox {get;set;}
    # PostalCode                            Property              System.String PostalCode {get;set;}
    # PrimaryGroup                          Property              System.String PrimaryGroup {get;}
    # primaryGroupID                        Property              System.Int32 primaryGroupID {get;set;}
    # PrincipalsAllowedToDelegateToAccount  Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection PrincipalsAllowedToDelegateToAccount {get;...
    # ProfilePath                           Property              System.String ProfilePath {get;set;}
    # ProtectedFromAccidentalDeletion       Property              System.Boolean ProtectedFromAccidentalDeletion {get;set;}
    # proxyAddresses                        Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection proxyAddresses {get;set;}
    # pwdLastSet                            Property              System.Int64 pwdLastSet {get;set;}
    # SamAccountName                        Property              System.String SamAccountName {get;set;}
    # sAMAccountType                        Property              System.Int32 sAMAccountType {get;set;}
    # ScriptPath                            Property              System.String ScriptPath {get;set;}
    # sDRightsEffective                     Property              System.Int32 sDRightsEffective {get;}
    # ServicePrincipalNames                 Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection ServicePrincipalNames {get;set;}
    # showInAddressBook                     Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection showInAddressBook {get;set;}
    # SID                                   Property              System.Security.Principal.SecurityIdentifier SID {get;set;}
    # SIDHistory                            Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection SIDHistory {get;}
    # SmartcardLogonRequired                Property              System.Boolean SmartcardLogonRequired {get;set;}
    # sn                                    Property              System.String sn {get;set;}
    # st                                    Property              System.String st {get;set;}
    # State                                 Property              System.String State {get;set;}
    # StreetAddress                         Property              System.String StreetAddress {get;set;}
    # Surname                               Property              System.String Surname {get;set;}
    # telephoneNumber                       Property              System.String telephoneNumber {get;set;}
    # Title                                 Property              System.String Title {get;set;}
    # TrustedForDelegation                  Property              System.Boolean TrustedForDelegation {get;set;}
    # TrustedToAuthForDelegation            Property              System.Boolean TrustedToAuthForDelegation {get;set;}
    # UseDESKeyOnly                         Property              System.Boolean UseDESKeyOnly {get;set;}
    # userAccountControl                    Property              System.Int32 userAccountControl {get;set;}
    # userCertificate                       Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection userCertificate {get;set;}
    # UserPrincipalName                     Property              System.String UserPrincipalName {get;set;}
    # uSNChanged                            Property              System.Int64 uSNChanged {get;}
    # uSNCreated                            Property              System.Int64 uSNCreated {get;}
    # whenChanged                           Property              System.DateTime whenChanged {get;}
    # whenCreated                           Property              System.DateTime whenCreated {get;}
    # wWWHomePage                           Property              System.String wWWHomePage {get;set;}
    
    

    Aqui está o roteiro principal. Há uma linha para cada grupo sincronizar. Coloque-o no mesmo diretório do script acima.

    AD2DL-Sync-All.ps1
    
    
    . $PSScriptRoot\AD2DL.ps1
    
    $OrganisationalUnits = @(
        "OU=Users,dc=domain,dc=tld"
    )
    
    
    Sync-AD2DL -OrganisationalUnits $OrganisationalUnits  -AdGroupName 'All-Senior-Staff-Members' -filter "Title -eq 'Senior staff member'"
    

    Aqui está um script de ajuda BAT que você pode chamar como tarefa agendada, por exemplo, duas vezes por dia. Coloque-o no mesmo diretório:

    AD2DL-Sync-All.bat
    
    @echo off
    set ownpath=%~dp0
    cd %ownpath%
    powershell.exe -command "& '.\AD2DL-Sync-All.ps1'"
    
    • 3

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve