ldap批量导入用户信息脚本
ldap部署好后,需要导入用户名、密码、邮箱、电话等
1、用户信息配置文件
ldap_adduser.txt
用户名–中文名–密码–邮箱–电话
wangwu|王五|123456|wangwu@example.com|15012345678
zhangsan|张三|123456|zhangsan@example.com|15012345678
2、导入txt数据脚本
ldap信息:
server_url = ‘10.20.42.16’
server_port = 9389
root_dn = ‘cn=admin,dc=hoperun,dc=com’
root_pw = ‘123456’
dn_ou = ‘ou=Users,dc=hoperun,dc=com’
from ldap3 import Server, Connection, ALL
from colorama import Fore, Style
# pip3 install ldap3
# LDAP info
server_url = '10.20.42.16'
server_port = 9389
root_dn = 'cn=admin,dc=hoperun,dc=com'
root_pw = '123456'
dn_ou = 'ou=Users,dc=hoperun,dc=com'
def add_user(line, ldap_dn, ldap_attributes, c, counts):
# 检查用户是否已存在
c.search(search_base=dn_ou,
search_filter=f'(cn={ldap_attributes["cn"]})',
attributes=['cn'])
if c.entries: # 如果有找到用户
print(Fore.YELLOW + f"已存在: {line} | 跳过..." + Style.RESET_ALL)
counts['skipped'] += 1
return
# 如果用户不存在,添加用户 posixAccount
c.add(dn=ldap_dn,
object_class=['inetOrgPerson','posixAccount', 'top'],
attributes=ldap_attributes)
if c.result['result'] == 0:
counts['success'] += 1
print(Fore.GREEN + f"成功: {line} | {ldap_attributes}" + Style.RESET_ALL)
else:
counts['failure'] += 1
print(Fore.RED + f"失败: {c.result} | {line}" + Style.RESET_ALL)
# 设置LDAP连接
server = Server(host=server_url, port=server_port, get_info=ALL)
c = Connection(server, user=root_dn, password=root_pw, auto_bind=True)
# 成功、失败和跳过的计数
counts = {'success': 0, 'failure': 0, 'skipped': 0}
# 打开文件并处理用户数据
with open('./ldap_adduser.txt', 'r', encoding='utf8') as f:
for line in f:
uid_numbers = []
gid_numbers = []
c.search(search_base=dn_ou, search_filter='(objectClass=posixAccount)', attributes=['uidNumber', 'gidNumber'])
for entry in c.entries:
if 'uidNumber' in entry:
uid_numbers.append(int(entry.uidNumber[0]))
if 'gidNumber' in entry:
gid_numbers.append(int(entry.gidNumber[0]))
next_uid = max(uid_numbers) + 1 if uid_numbers else 1000 # 开始值可以根据需要调整
next_gid = max(gid_numbers) + 1 if gid_numbers else 1000 # 开始值可以根据需要调整
# 使用列表解包避免多次调用
dn_cn, dn_sn, ldap_password, ldap_mail, ldap_mobile = map(str.strip, line.strip().split('|'))
dn_cn = ldap_mail.split('@')[0]
ldap_dn = f'cn={dn_cn},{dn_ou}'
home_directory = f"/home/{dn_cn}"
ldap_attributes = {
'cn': dn_cn,
'sn': dn_sn,
'uid': dn_cn,
'userpassword': ldap_password,
'mail': ldap_mail,
'mobile': ldap_mobile,
'givenName': dn_cn,
'uidNumber': next_uid, # 使用生成的 uidNumber
'gidNumber': next_gid, # 使用生成的 gidNumber
'homeDirectory': home_directory
}
add_user(f"{dn_cn} | {dn_sn} | {ldap_password} | {ldap_mail} | {ldap_mobile}", ldap_dn, ldap_attributes, c, counts)
# 最后打印成功、失败和跳过的总数
print(Fore.YELLOW + f"\n总成功数: {counts['success']} | 总失败数: {counts['failure']} | 总跳过数: {counts['skipped']}" + Style.RESET_ALL)