Myluzh Blog

Strive to become a dream architect.

python批量创建AD用户

发布时间: 2022-6-29 文章作者: myluzh 分类名称: Python


根目录需存在一个user.csv文件,格式如下
账号名称,姓名,组织单位(xxx/xxx/xxx)
例如:李小天,A888888,股份有限公司/股份有限公司/研究所

import logging
import os


class AD:
    def __init__(self):
        self.logging = None
        self.logtxt = None
        self.Domain = "jsg.local"
        self.DefaultPwd = "1234.com"
        self.UserTxt = "./user.csv"
        self.LogTxt = "./log.txt"
        self.log()

    def log(self):
        # encoding='utf-8')  # 中文乱码在python>3.9该有参数
        logging.basicConfig(  # filename=self.LogTxt,
            format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s',
            level=logging.ERROR)

    def addUser(self):
        UserTxt = open(self.UserTxt, 'r', encoding='UTF-8')
        lineI = 1
        for UserList in UserTxt.readlines():
            try:
                UserList = UserList.replace("\n", "")
                UserList = UserList.split(",")
                OUList = UserList[2].split("/")
                OUList.reverse()
                OU = "ou=" + ",ou=".join(OUList)
                DCList = self.Domain.split(".")
                # DCList.reverse()
                DC = "dc=" + ",dc=".join(DCList)
                addUserShell = f"dsadd user \"cn={UserList[0]},{OU},{DC.upper()}\" -samid {UserList[1]} -upn {UserList[1]}@{self.Domain.upper()} -ln {UserList[0][0]} -fn {UserList[0][1:]} -display {UserList[0]} -pwd {self.DefaultPwd} -mustchpwd no -pwdneverexpires yes -disabled no"
                # print(addUserShell)
                os.system(addUserShell)
                lineI = lineI + 1
            except Exception as e:
                logging.error(str(e) + f" {self.UserTxt} Line:{lineI} Content:" + str(UserList))
                lineI = lineI + 1
                continue


AD = AD()
AD.addUser()

标签: python 域控 ad 批量创建

发表评论