吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1353|回复: 14
收起左侧

[Python 原创] Python自动化新建AD域用户

  [复制链接]
arrymarry 发表于 2023-12-27 11:03
破公司入职量太大,手动创建域用户已经疲惫,写了个自动化脚本,更多时间摸鱼。

两个脚本,一个创建用户,一个抓用户到数据库。

第三方库pip install即可
[Python] 纯文本查看 复制代码
from pypinyin import lazy_pinyin
from ldap3 import Server, Connection, ALL, NTLM, MODIFY_REPLACE
from ad_to_mysql import *
import pymysql


def create_user(user, bumen):#传入姓名和部门,我是通过监控新入职邮件抓取得到参数进行调用
    name_list = lazy_pinyin(user)  

    if len(user) == 2:
        name = name_list[0] + name_list[1]
    elif len(user) == 3:
        name = name_list[0] + name_list[1] + name_list[2]

    user_db = pymysql.connect(host="", port=3306, user="", passwd="", db='domainUsers')#数据库地址、username、密码、数据库名
    cur = user_db.cursor()

    #新增用户时查询sAMAccountName和name是否有重复,主要看name怎么定义,我这是直接全拼
    denglu_name=cur.execute("select * from users where sAMAccountName = '{0}';".format(name))#登录名是否重名
    if denglu_name == 1:
        name = name + "2"
        
    yonghu_name = cur.execute("select * from users where name = '{0}';".format(user))#用户名是否重名
    if yonghu_name == 1:
        user = user + "_%s"%bumen
    
    user_db.close()
    user_db.cursor().close()

    # 域服务器连接配置
    server = Server('10.10.10.10', use_ssl=True, get_info=ALL)#域控地址
    conn = Connection(server, user='admin\\admin', password='admin123', auto_bind=True, authentication=NTLM)

    user_attributes = {
        'sn': user[0],
        'givenName': user[1:],
        'displayName': user,
        'sAMAccountName': name,
        'userPrincipalName': name + '@admin.com',
        'mail': name + '@admin.com',
        'mailNickname': name,
        'homeMDB': 'CN=Mailbox Database 0109296902,CN=Databases,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=admin,DC=com',
        'homeMTA': 'CN=Microsoft MTA,CN=EXCHANGE2010,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=admin,DC=com',
        'legacyExchangeDN': '/o=First Organization/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn={}'.format(name),
        'msExchHomeServerName': '/o=First Organization/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=EXCHANGE2010',
        'proxyAddresses': "SMTP:{}@admin.com".format(name),#创建exchange邮箱,测试使用exchange2010
        'msExchVersion': '44220983382016',
        'showInAddressBook': [
            'CN=默认全局地址列表,CN=All Global Address Lists,CN=Address Lists Container,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=admin,DC=com',
            'CN=所有用户,CN=All Address Lists,CN=Address Lists Container,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=admin,DC=com']              
    }#这里的信息使用ADSI查看


    user_cn = 'CN={0},OU=test,DC=admin,DC=com'.format(user)
    bumenquanxian = "CN=test,OU=Gerap,DC=admin,DC=com"#域用户权限组
    bumenyoujian = "CN=行政,OU=邮件组,DC=admin,DC=com"#邮件权限组
    
    newuser = conn.add(user_cn, attributes=user_attributes, object_class='user')
    conn.extend.microsoft.modify_password(user_cn, new_password='admin123')
    conn.modify(user_cn, {'userAccountControl': [(MODIFY_REPLACE, [512])]})  # 
    if newuser:
        print('用户:' + user + '添加成功!')
        refresh_mysqldb()#刷新数据库
        
    else:
        print('增加用户发生错误')
        
    conn.extend.microsoft.add_members_to_groups(user_cn, bumenquanxian)
    conn.extend.microsoft.add_members_to_groups(user_cn, bumenyoujian)
    


[Python] 纯文本查看 复制代码
from ldap3 import Server, Connection, ALL
import pymysql

#抓取域用户信息到数据库

# 用户信息写入到数据库中
class Mariadb():
    def __init__(self, dbname='domainUsers', tablename='users'):
        self.conn_mysql = pymysql.connect(host="10.10.10.10", port=3306, user="", passwd="")#数据库地址、username、密码
        self.dbname = dbname
        self.tablename = tablename

    # 删除旧库
    def drop_db(self):
        self.conn_mysql.cursor().execute("drop database if exists {0};".format(self.dbname))
        self.conn_mysql.commit()

    # 创建新库和表
    def create_dbtable(self):
        self.conn_mysql.cursor().execute("create database if not exists {0} charset=utf8mb4;".format(self.dbname))
        self.conn_mysql.cursor().execute("use {0}".format(self.dbname))
        self.conn_mysql.cursor().execute('''create table if not exists {0} (ID int not null auto_increment primary key,
                        name char(15) not null,
                        center char(10) not null,
                        department char(20) not null,
                        sAMAccountName char(20) not null,
                        memberOf text not null,
                        distinguishedName varchar(255) not null)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
                        AUTO_INCREMENT=1;'''.format(self.tablename))
        self.conn_mysql.commit()

    # 插入数据
    def insert(self, tablename, name, center, department, logname, memberOf, dn):
        self.conn_mysql.cursor().execute("use {0}".format(self.dbname))
        self.conn_mysql.cursor().execute('''insert into {0} (name,center,department,sAMAccountName,memberOf,distinguishedName)
                        values('{1}','{2}','{3}','{4}','{5}','{6}');'''.format(self.tablename, name, center, department,
                                                                               logname, memberOf, dn))
        self.conn_mysql.commit()

    # 关闭数据库连接
    def close_conn(self):
        self.conn_mysql.close()
        self.conn_mysql.cursor().close()


# 爬取域控指定组织单位内的用户信息
department = {'行政':{'TEST':'OU=test,DC=admin,DC=COM'}
    }

def refresh_mysqldb():
    server = Server('', get_info=ALL)#域控地址
    conn = Connection(server, 'admin\\admin', 'admin123', auto_bind=True)#管理用户
    dbobject = Mariadb()
    dbobject.drop_db()
    dbobject.create_dbtable()
    try:
        for key1, value1 in department.items():
            for key, value in value1.items():
                conn.search(search_base=value, search_filter='(objectClass=user)',
                            attributes=['name', 'sAMAccountName', 'memberOf', 'distinguishedName'])
                for entry in conn.entries:
                    dbobject.insert(key, str(entry['name']), key1, key, str(entry['sAMAccountName']),
                                    str(','.join(entry['memberOf'])), str(entry['distinguishedName']))
        print("[+]刷新数据库成功!")
    except Exception as e:
        dbobject.rollback()#失败回滚
        print("[-]刷新数据库失败!")
    finally:
        dbobject.close_conn()

免费评分

参与人数 2吾爱币 +8 热心值 +2 收起 理由
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
临渊行 + 1 + 1 用心讨论,共获提升!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

Chanlong 发表于 2024-2-21 14:14
感谢楼主分享。hhh说起这个AD域控
我们公司这就比较方便,HR系统跟AD打通的。只要人事那边操作完生成了工号,就能用工具直接开账号了。
这个账号就对应了HR系统内人事给新办理人员入职对应的部门岗位。
bester 发表于 2023-12-27 13:30
我在Active Directory中有一个jdx.com.cn,展开是各个部门,比如行政部,再展开是信息组,这个组下面是各个人的姓名,所以我想问一下CN OU DC 和DC 是啥
 楼主| arrymarry 发表于 2023-12-27 13:55
bester 发表于 2023-12-27 13:30
我在Active Directory中有一个jdx.com.cn,展开是各个部门,比如行政部,再展开是信息组,这个组下面是各个人的 ...

jdx.com.cn是DC,行政部是OU,用户就是CN;CN=xxx,OU=行政部,DC=jdx,DC=com,DC=cn
latelord 发表于 2023-12-27 14:00
与题无关,但我一直想知道的是如何添加用户新选项信息,比如添加用户的QQ号,微信号等?有没有知道
bester 发表于 2023-12-27 14:01
arrymarry 发表于 2023-12-27 13:55
jdx.com.cn是DC,行政部是OU,用户就是CN;CN=xxx,OU=行政部,DC=jdx,DC=com,DC=cn

好的 谢谢你 十分感谢
 楼主| arrymarry 发表于 2023-12-27 14:07
latelord 发表于 2023-12-27 14:00
与题无关,但我一直想知道的是如何添加用户新选项信息,比如添加用户的QQ号,微信号等?有没有知道

我理解的是ADSI里面找对应属性就是
jun269 发表于 2023-12-27 14:32
楼主软件打包出来给我们用用试试呗。
q3125418 发表于 2023-12-27 14:48
jun269 发表于 2023-12-27 14:32
楼主软件打包出来给我们用用试试呗。

就服你的思路
linerya 发表于 2023-12-27 14:51
楼主软件打包出来给我们用用试试呗。
 楼主| arrymarry 发表于 2023-12-27 15:01
linerya 发表于 2023-12-27 14:51
楼主软件打包出来给我们用用试试呗。

你得自己配置啊,然后调用方法就行了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-28 03:33

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表