基于python LDAP3的AD域账号注册系统

近来无聊,写写最近一个小项目:

出发点 : 新员工入职,需要申请较多的账号,比如各应用系统账号:AD域账号,邮箱账号,上网权限绑定,打印系统,共享文件夹权限绑定等,如果一个一个地注册,需要浪费大量填写重复表单的时间.

各应用系统之间的关系: 上网权限/打印系统/共享文件夹/工作组   需要建立AD域账号各系统同步后才能针对相应账号进行设置.

1. 使用Django 作为用户交互工具.

2.LDAP3 负责处理用户提交的表单数据.

Django 就不細讲了!

LDAP3連接AD域有两种方式,一种是SSL安全连接(可以增,删,改,查),一种是普通连接(只能查询)

SSL连接需要在AD域控上面安装证书服务,然后在你自己电脑上输入 http://IP/certsrv/   申请证书,后安装

证书安装好后,就可以与域控建立连接.

@login_required
def ad_user(request):
    if request.method != "POST":
        return render(request,"index.html")
    try:
        FirstName = request.POST.get('first-name')   #
        LastName = request.POST.get('last-name')    #
        LognName = request.POST.get('logn-name')    #登录名
        LognPassword = request.POST.get('logn-password')    #登录密码
        OuName = request.POST.get('OU')                        #厂区部门
        GroupsName = request.POST.get('GROUPS')                 #工作组
        EmpNo = request.POST.get("logn-empno")                  #工號
    except:
        return render(request,"index.html")

    #用戶提交表單處理---------------------------------------------------------------------
    FirstName = FirstName.replace(" ", '')  #去除字符串中的空格
    LastName = LastName.replace(" ", '') #去除字符串中的空格
    LognName = LognName.replace(" ", '') #去除字符串中的空格
    LognPassword = LognPassword.replace(" ", '') #去除字符串中的空格
    # GroupsName = GroupsName.replace(" ", '')             #去除字符串中的空格
    EmpNo = EmpNo.replace(" ", '') #去除字符串中的空格


    if FirstName and LastName and LognName and LognPassword and GroupsName:
        pass
    else:
        return render(request, "error.html", {'error_message':'提交了非法字符串,無法建立,請重試'})



    #根據OU代碼在數據庫中查找相對應的OU名
    try:
        OuNameDatabase = OuSwitch.objects.get(ou_code=OuName)
    except:
        return render(request, "error.html",{'error_message':'無法識別的組織單位!'})




    # OU處理-----------------------------------------------------------------------------------------------
    allName = FirstName+LastName
    User = 'CN=' + allName + ','
    OuPath = User + OuNameDatabase.ou_name
    DisplayName = LognName+'('+ allName  +')'          #XXX(XXX)
    UserPrincipalName = LognName + '@Company.com.cn'   #後綴
    print('組織路徑:'+OuPath)
    print('用戶組ID:'+GroupsName)
    print('工號:'+EmpNo)


    # Group工作組處理-----------------------------------------------------------------------------------------------
    GroupsName = GroupsName.split(',')  ## 將一個或多個工作組轉換成列表
    groups = []
    for group in GroupsName:
        try:
            groups.append(GroupSwitch.objects.get(id=group))   #查找用戶組OU
        except:
            pass
    if groups == []:   #如果遇到用戶提交的數據出現無法找到的情況,將檢測這組數據是否全不達標
        return render(request, "error.html",{'error_message':'無法識別的工作組!'})
    # print("查詢到的數據:"+ groups )


    #LDAP主程序---------------------------------------------------------------------------------------------------
    try:
        server = Server("ldaps://Company.com.cn:636", use_ssl=True)
        conn = Connection(server, user="Company\\user_registration", password="whoareyou2009", authentication=NTLM, auto_bind=True)
    except:
        return render(request, "error.html",{'error_message':'無法連接至域控,請稍候再試!'})


    if conn.bind():
        # -------------------------添加用戶前檢測用戶是否存在---------------------------#
        dn_look_path = 'ou=Company,dc=Company,dc=com,dc=cn'
        if conn.search(dn_look_path, '(cn={})'.format(allName)):
            conn.unbind()
            conn.closed
            return render(request, "error.html",{'error_message':'{}用戶名已存在,請更換其他名稱后再試'.format(allName)})

        if conn.search(dn_look_path, '(sAMAccountName={})'.format(LognName)):
            conn.unbind()
            conn.closed
            return render(request, "error.html",{'error_message':'{}登錄名已存在,請更換其他登錄名后再試'.format(LognName)})


        # -------------------------添加用戶---------------------------#
        msg_add = conn.add(OuPath,'inetOrgPerson',{'displayName':DisplayName, #顯示名
                                                   'givenName':LastName,        #
                                                   'sn':FirstName,              #
                                                   'sAMAccountName':LognName,   #登錄名
                                                   'userPrincipalName':UserPrincipalName,   #完整名
                                                   'Description':EmpNo,                             #工號
                                                   'scriptPath':'user'})        #用戶登錄腳本
        # -------------------------設置用戶初始密碼---------------------------#
        print(msg_add)
        if msg_add:

            msg_jh = conn.extend.microsoft.modify_password(OuPath,new_password=LognPassword, old_password=None)

        # -------------------------將用戶啟用---------------------------#
            if msg_jh:
                try:
                    changeUACattribute = {'userAccountControl': [('MODIFY_REPLACE', [512])]}
                    conn.modify(OuPath, changes=changeUACattribute)
                except:
                    return render(request, "error.html", {'error_message': '{}用戶啟用失敗!'.format(allName)})
        #-------------------------設置用戶下次需更改密碼---------------------------#
                try:
                    changeTime = {'pwdLastSet': [('MODIFY_REPLACE', [0])]}
                    conn.modify(OuPath, changes=changeTime)
                except:
                    print('設置用戶下次更改密碼失敗')
                    return render(request, "error.html", {'error_message': '{}設置用戶下次更改密碼失敗'.format(allName)})

        #-------------------------加入工作組------------------------------------#
                for group_cache in groups:
                    # groupdn = 'CN=資訊部,OU=資訊,OU=總管理處,OU=Company,DC=Company,DC=com,DC=cn', 'CN=jobs,OU=人事,OU=總管理處,OU=Company,DC=Company,DC=com,DC=cn'
                        try:
                            print(group_cache.group_name)
                            conn.extend.microsoft.add_members_to_groups(OuPath, groups='{}'.format(group_cache.group_name))
                        except:
                            # return render(request, "error.html", {'error_message': '{}創建成功,但尝试加入用戶組失敗'.format(User[3:])})
                            pass
        # -------------------------釋放與服務器的連接---------------------------#
                conn.unbind()
                conn.closed

                return render(request, "succeed.html", {'username':allName,'lognname':LognName,'lognpw':LognPassword,'oupath':OuNameDatabase,'groups':groups})
        else:
            return render(request, "error.html", {'error_message': '登錄名{},註冊失敗!'.format(LognName)})
    else:
        return render(request, "error.html", {'error_message': '與服務連接失敗,請聯繫資訊,或稍候再試'})

转载于:https://www.cnblogs.com/lifajia/p/8443722.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值