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

jira内容变更后,发送钉钉到群,能@艾特对应的指定人提醒。

前提依赖:openldap;python3;ldap3;Django

关于部署openLDAP请观看上一篇文章:https://blog.csdn.net/qq_35961346/article/details/115331677

关于钉钉申请群机器人:https://developers.dingtalk.com/document/app/document-upgrade-notice#/serverapi2/krgddi

ldap必需每个人维护有电话(Phone)参数

上代码:

#!/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']
        attr_dict_dic = dict(attr_dict)
        print(attr_dict_dic)
        phone = attr_dict_dic.get("telephoneNumber")[0]
        return phone

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


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


@csrf_exempt
def demo(request):
    if request.method == "POST":
        jiradata = request.body
        jirabaowen(jiradata)
        demo = request.POST.get("demo")
        return HttpResponse(demo)
    else:
        data = request.GET.get('demo')
        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 = {}
    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}

    # 发送信息到钉钉
        # project_name项目名称,我这里维护了两个项目
    project_name = jira_data.get("issue").get("fields").get("project").get("key")
    if project_name == "$jira_projectName1": 
        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())

结果上图:

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值