ldap3, python 3.7, как создать учетную запись в AD

пытаюсь с помощью python автоматизировать процесс создания новых пользователей в AD. Создать новых пользователей у меня получилось. Но есть один нюанс: я не знаю, как при создании учетки задать ей пароль. Атрибуты "userPassword" и "unicodePwd" пробовал - пароль, так и остается пустой, т.е. без пароля вовсе. Ниже пример кода, функция создающая учетку:

def create_user(self):
    dn=str('CN='+self.display_name+',CN=Users,DC=domain')
    attr={'sAMAccountName':str(self.display_name),'sn':self.surname,'givenName':self.given_name,'displayName':str(self.display_name),'userPrincipalName':str(self.display_name+'@domain'),'userAccountControl':'66048'}
    self.conn.add(dn,['user','organizationalPerson','person','top'],attr)

Ответы (1 шт):

Автор решения: Violet
s = Server(ad_domain, use_ssl=True, port=636)  # Адрес домена, шифрование, порт
c = Connection(s, ad_admin, ad_password)

# Создание учётной записи в домене (Active Directory)
def create_ad(first, last, uis_login, phone, position, domain_uis, uis_password):
    c.bind()

    if not c.add('cn=' + first + ' ' + last + ', ou=Подразделение, dc=domain, dc=local', 'user',
                 {'displayName': first + ' ' + last,  # Отображаемое имя
                  'givenName': first,  # Имя
                  'sn': last,  # Фамилия
                  'userPrincipalName': uis_login + '@domain.local',  # Имя входа пользователя
                  'sAMAccountName': uis_login,  # Имя входа пользователя (пред-Windows 2000)
                  'mobile': phone,  # Телефон
                  'title': position,  # Должность
                  'mail': uis_login + '@' + domain_uis,  # E-mail
                  'info': uis_password  # Заметки
                  }):
        return 'Не удалось создать учётную запись в AD'

    # Разблокируем учётную запись
    c.extend.microsoft.unlock_account(
        user='cn=' + first + ' ' + last + ', ou=Подразделение, dc=domain, dc=local')

    # Устанавливаем пароль
    if not c.extend.microsoft.modify_password(user='cn=' + first + ' ' + last + ', ou=Подразделение, dc=domain, dc=local',
                                              new_password=uis_password, old_password=None):
        return 'Не удалось установить пароль'

    # Определяем атрибуты
    change_uac_attribute = {
        "userAccountControl": (MODIFY_REPLACE, [512])}
    # 512: Normal account
    # 514: Disable account
    # 65536: Normal account + don't expire password

    # Устанавливаем атрибуты
    if not c.modify('cn=' + first + ' ' + last + ', ou=Подразделение, dc=domain, dc=local', changes=change_uac_attribute):
        return 'Не удалось установить атрибуты'

    # Добавляем в группы
    ad_add_members_to_groups(c, 'cn=' + first + ' ' + last + ', ou=Офис, dc=domain, dc=local',
                             'cn=Группа, ou=Подразделение, dc=domain, dc=local')
    c.unbind()
    return 'Done'

Дополнительно:

# Смена пароля учётной записи в домене (Active Directory)
def adpassword(login):
    uis_password = create_password()
    place = search_ad(last=login.split(" ")[1])
    for i in place:
        place = str(i['distinguishedName'])
    place = place[place.find(",") + 1:]
    c.bind()
    a = c.extend.microsoft.modify_password(user='cn=' + login + ',' + str(place), new_password=uis_password)
    c.unbind()
    return uis_password, a


# Разблокировка учётной записи в домене (Active Directory)
def unlock_account_ad(login):
    place = search_ad(last=login.split(" ")[1])
    for i in place:
        place = str(i['distinguishedName'])
    place = place[place.find(",") + 1:]
    c.bind()
    unlock_account = c.extend.microsoft.unlock_account(user='cn=' + login + ',' + str(place))
    c.unbind()
    return unlock_account


# Блокировка учётной записи в домене (Active Directory)
def block_ad(first, last):
    c.bind()
    c.extend.microsoft.unlock_account(user='cn=' + first + ' ' + last + ', ou=Подразделение, dc=domain, dc=local')
    change_uac_attribute = {"userAccountControl": (MODIFY_REPLACE, [514])}
    if not c.modify('cn=' + first + ' ' + last + ', ou=Подразделение, dc=domain, dc=local', changes=change_uac_attribute):
        return 'Не удалось заблокировать'
    c.modify_dn('cn=' + first + ' ' + last + ', ou=Подразделение, dc=domain, dc=local', 'cn=' + first + ' ' + last,
                new_superior='ou=Dismissed, dc=mcsmtcs, dc=local')
    c.unbind()
    return 'Done'
→ Ссылка