python 把Excel 数据转换ldif格式
源码:
https://github.com/chaoren399/csv2ldif.git
源格式:
姓名,用户名,企业邮箱
赵锋,zhaofeng,zhaofeng@baimeidashu.com
张慧,zhanghui,zhanghui@baimeidashu.com
周佳,zhoushijia,zhoushijia@baimeidashu.com
陈缘,chenyuan,chenyuan@baimeidashu.com
刘赛,liusai,liusai@baimeidashu.com
莉嘉,wanglijia,wanglijia@baimeidashu.com
王双,wangshuangjian,wangshuangjian@baimeidashu.com
杨伊,yangyiqiu,yangyiqiu@baimeidashu.com
目标格式:
dn: uid=zhangsan,ou=users,dc=baimeidashu,dc=com
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
gidNumber: 0
givenName: zhangsan
sn: 1
displayName:张三
uid: zhangsan
homeDirectory: /home/zhangsan
mail: zhangsan@baimeidashu.com
cn: zhangsan
uidNumber: 27721
memberOf: cn=ldap-jira-users-groups,ou=jira,dc=baimeidashu,dc=com
有了这个文件就可以了
代码:
# 这是一个示例 Python 脚本。
# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。
import pandas as pd
import random
def generate_uid(length=5):
# 生成一个指定长度的随机数,我们这里设置长度为5
return random.randint(10000, 99999)
def print_hi(name):
# 在下面的代码行中使用断点来调试脚本。
print(f'Hi, {name}') # 按 Ctrl+F8 切换断点。
path = 'file//3-测试数据.csv'
path2 = 'file//1.ldif'
with open(path2, 'w') as file:
data = pd.read_csv(path,encoding='gbk')
for index, row in data.iterrows():
displayName = row['姓名']
givenName = row['用户名']
print (givenName)
# 生成UID
uid = generate_uid()
file.write("dn: "+'uid='+givenName+',ou=users,dc=baimeidashu,dc=com'+'\n')
file.write("objectClass: "+'posixAccount'+'\n')
file.write("objectClass: "+'top'+'\n')
file.write("objectClass: "+'inetOrgPerson'+'\n')
file.write("gidNumber:"+'0'+'\n')
file.write("givenName: "+givenName+'\n')
file.write("sn: "+'1'+'\n')
file.write("displayName: "+displayName+'\n')
file.write("uid: "+givenName+'\n')
file.write("homeDirectory: /home/"+givenName+'\n')
file.write("mail: "+givenName+'@baimeidashu.com'+'\n')
file.write("cn: "+givenName+'\n')
file.write("uidNumber: "+str(uid)+'\n')
file.write("memberOf: "+'cn=ldap-jira-users-groups,ou=jira,dc=baimeidashu,dc=com'+'\n')
file.write('-----------------------------\n')
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
print_hi('PyCharm')
# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助