好友
阅读权限10
听众
最后登录1970-1-1
|
破公司入职量太大,手动创建域用户已经疲惫,写了个自动化脚本,更多时间摸鱼。
两个脚本,一个创建用户,一个抓用户到数据库。
第三方库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 |
用心讨论,共获提升! |
查看全部评分
|