LDAP脚本批量导出用户

背景:工作原因,搭建了LDAP服务,然后用户数过多,因为懒所以就通过python代码生成ldap脚本进行批量导入用户

 

1、整理用户名单,格式如下:

 

 

 注:上述格式影响代码中的excel读取代码

 

 2、python3脚本

# coding: utf-8
import base64
import xlrd


class ExcelData():
# 初始化方法
def __init__(self, data_path, sheet_name):
#定义一个属性接收文件路径
self.data_path = data_path
# 定义一个属性接收工作表名称
self.sheet_name = sheet_name
# 使用xlrd模块打开excel表读取数据
self.data = xlrd.open_workbook(self.data_path)
# 根据工作表的名称获取工作表中的内容(方式①)
self.table = self.data.sheet_by_name(self.sheet_name)
# 根据工作表的索引获取工作表的内容(方式②)
# self.table = self.data.sheet_by_name(0)
# 获取第一行所有内容,如果括号中1就是第二行,这点跟列表索引类似
self.keys = self.table.row_values(0)
# 获取工作表的有效行数
self.rowNum = self.table.nrows
# 获取工作表的有效列数
self.colNum = self.table.ncols

# 定义一个读取excel表的方法
def readExcel(self):
# 定义一个空列表
#atas = []
sheet_data = {}
for i in range(1, self.rowNum):
# 定义一个空字典

cell_name = self.table.cell_value(i, 3)
cell_id = self.table.cell_value(i, 4)
sheet_data[cell_name] = cell_id
return sheet_data

def writeTxt(txt_fp,datas):
with open(txt_fp,'a') as f:
i=10001
for cname, uname in datas.items():
print('%s is %s' % (cname, uname))
i=i+1
f.write( "\n"+"dn: cn="+str(uname)+",ou=People,dc=kamfu,dc=com" + "\n"
+ "cn:" + str(uname) + "\n"
+ "gidnumber: 10001" + "\n"
+ "homedirectory: /home/" + str(uname) + "\n"
+ "loginshell: /bin/bash" + "\n"
+ "mail: " + str(uname) + "@test.com.cn" + "\n" #公司邮箱
+ "objectclass: posixAccount" + "\n"
+ "objectclass: inetOrgPerson" + "\n"
+ "objectclass: organizationalPerson" + "\n"
+ "objectclass: person" + "\n"
+ "sn:: " + str(base64.b64encode(cname.encode("utf-8")), "utf-8") + "\n" #base64转码
+ "uid: " + str(uname) + "\n"
+ "uidnumber: " + str(i) + "\n"
+ "userpassword: {SSHA}9IRZYWEAIALUSIrPOudkyzfmATpleXFr" + "\n") #密码Kamfu666

#f.close()


if __name__ == '__main__':
data_path = "D:\LDAP用户名单.xlsx"
sheetname = "汇总"
get_data = ExcelData(data_path, sheetname)
datas = get_data.readExcel()
writeTxt("D:\LDAP_users.txt", datas)

3、运行代码生成的ldap脚本:

 

 4、复制脚本到ldap的web端进行导入

 

 



posted @ 2020-06-19 16:50  ouhy  阅读(2207)  评论(0编辑  收藏  举报