python + ldap +jira 发送 钉钉@艾特人

#!/usr/bin/env python

from ldap3 import Server, Connection, SUBTREE, ALL
from ldap3 import Server, Connection, Reader, ObjectDef
# from settings
import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import requests

# 取出telephoneNumber
ldap_host = "ldap://localhsot"
ldap_port = 389
ldap_admin_user = "cn=Manager,dc=test,dc=com"
ldap_admin_password = "admin@123"
ldap_base_search = "dc=test,dc=com"


def ldap_auth(username, password):
    s = Server(host=ldap_host, port=ldap_port, use_ssl=False, get_info='ALL')
    # 这个首先看看你的admin能不能正常connect
    ldapz_admin_connection = Connection(s, user=ldap_admin_user, password=ldap_admin_password, auto_bind='NONE',
                                        version=3,
                                        authentication='SIMPLE', client_strategy='SYNC', auto_referrals=True,
                                        check_names=True,
                                        read_only=False, lazy=False,
                                        raise_exceptions=False)
    # 连上以后必须bind(登录)才能有值
    ldapz_admin_connection.bind()

    # 这个是为了查询你输入的用户名的入口搜索地址
    res = ldapz_admin_connection.search(search_base=ldap_base_search,
                                        search_filter='(uid={})'.format(username),
                                        search_scope=SUBTREE,
                                        attributes=['cn', 'uid', 'telephoneNumber', 'displayName'])  # 这里可能由你自己选择

    if res:
        entry = ldapz_admin_connection.response[0]
        dn = entry['dn']
        attr_dict = entry['attributes']
        # print(type(attr_dict), attr_dict)
        # phone = eval(c
        # print(type(attr_dict))
        # print(phone)
        attr_dict_dic = dict(attr_dict)
        print(attr_dict_dic)
        phone = attr_dict_dic.get("telephoneNumber")[0]
        # print(phone)
        return phone

        try:
            # 这个connect是通过你的用户名和密码还有上面搜到的入口搜索来查询的
            conn2 = Connection(s, user=dn, password=password, check_names=True, lazy=False, raise_exceptions=False)
            conn2.bind()
            # print(conn2.result["description"])
            # 正确-success 不正确-invalidCredentials
            if conn2.result["description"] == "success":
                print("yes")
            else:
                print("no")
        except Exception as e:
            # print("no1")
            #  print(e)
            pass


ldap_auth("yourname", "") #ldap内实际存在的用户,需创建


@csrf_exempt
def demo(request):
    if request.method == "POST":
        # print(request.body)
        jiradata = request.body
        jirabaowen(jiradata)
        demo = request.POST.get("demo")
        # print(demo)
        return HttpResponse(demo)
    else:
        # print(request.GET)
        data = request.GET.get('demo')
        # print(data)
        return HttpResponse("hello world!")

# 拼接字符信息
def jirabaowen(jira_data):
    jira_data = json.loads(jira_data)
    creator = jira_data.get("user").get("displayName" ,'displayName is null')
    task = jira_data.get("issue").get("fields").get("issuetype").get("name", 'name is null')
    issue_key = jira_data.get("issue").get("key", 'key is null')
    changefrom = jira_data.get("changelog").get("items")[-1].get("fromString", 'fromString is null')
    changeto = jira_data.get("changelog").get("items")[-1].get("toString", 'toString is null')
    issue_name = jira_data.get("issue").get("fields").get("summary", "summary is null")
    number = jira_data.get("issue").get("key", 'issue_key is null')

    # 获取用户名称调用ldap获取用户手机号
    ldapname = jira_data.get("issue").get("fields").get("assignee").get("name")
    phone = ldap_auth(ldapname, "")
    # print(phone)
    user_phone = phone

    # ding_data = '{"msgtype": "markdown","markdown": {"title": "jira提醒","text": "#### jira提醒:@{7} >创建人:{0} 变更{1} {2} 状态:{3} to {4} > [{5}](http://jira.test.com/browse/{6}) > "},"at": {"atMobiles": ["{7}"],"isAtAll": false}}'.format(creator, task, issue_key, changefrom, changeto, issue_name, number, user_phone)

    ding_data = {}
    ding_data['msgtype'] = 'markdown'

    markdown = {}
    markdown['title'] = "jira提醒"
    markdown[
        'text'] = "#### jira提醒:@{7} \n 创建人:{0} 变更{1} {2} \n 状态:{3} to {4} [{5}](http://jira.test.com/browse/{6}) ".format(
        creator, task, issue_key, changefrom, changeto, issue_name, number, user_phone)

    ding_data['markdown'] = markdown
    ding_data['at'] = {"atMobiles": [user_phone], "isAtAll": False}

    # 发送信息到钉钉
        # jira项目名称
    project_name = jira_data.get("issue").get("fields").get("project").get("key")
    if project_name == "$jira_projectName1": # jira内项目名称
        dingurl = 'https://oapi.dingtalk.com/robot/send?access_token=bb0b4f1e5182997e32c29f884db4ac7b7adae3a0387869f4035940c'
    elif project_name == "$jira_projectName2":
        dingurl = 'https://oapi.dingtalk.com/robot/send?access_token=9b75ba7e4f72448807968b70f2d7fba87106644732c8c0c6714a998b'
    headers = {"Content-Type": "application/json"}
    rsq = requests.post(url=dingurl, data=json.dumps(ding_data), headers=headers)

    print(rsq.json())


上一篇:python + ldap +jira 发送 钉钉@艾特人


下一篇:Jenkins接入LDAP