python+flask+uwsgiモニタopenldap


仕事中にopenldapを監視する必要があるという問題に遭遇しました.会社用の監視ツールはprometheusなので、最初はopenldap_を使用しました.exporterがopenldapのmetricsを捕まえると、後で問題が発生し、モニタリングはopenldapを死なせ、接続の速度が接続を切断する速度よりも大きいため、接続数が増加し続け、他のldap認証を必要とするサービスが接続できないため、このexporterモニタリングの使用を断固として放棄した.openldapを監視するためにpythonスクリプトを自分で書くことにし、まずpython-ldap提供apiを検索し、PythonプログラムからLDAP目サーバにアクセスする.さあ、次はスクリプトです.
vim alert.py
import ldap
import requests
import json
l = ldap.initialize('ldap://ip:389')
binddn = "cn=Manager,dc=xxx,dc=xxx"
bindpw = "xxxxxxx"
def get_token():

  url='https://qyapi.weixin.qq.com/cgi-bin/gettoken'
  values = {'corpid' : 'xxx' ,
      'corpsecret':'xxx',
       }
  req = requests.post(url, params=values)
  data = json.loads(req.text)
  return data["access_token"]

def send_msg(messageinfo):
  url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+get_token()
  values = """{"touser" : "@all" ,
      "toparty":"1",
      "msgtype":"text",
      "agentid":"xxx",
      "text":{
        "content": "%s"
      },
      "safe":"0"
      }""" %(str(messageinfo))

  data = json.loads(values)
  req = requests.post(url, values)

try:
  l.simple_bind_s(binddn, bindpw)
  valid = True
except ldap.LDAPError, e:
  if type(e.message) == dict and e.message.has_key('desc'):
      send_msg(e.message['desc']+'ip')
  else:
      send_msg(e)
finally:
  l.unbind_s()

vim index.py
from flask import Flask
import os
app = Flask(__name__)

@app.route('/metrics')
def monitor():
    os.popen("python alert.py")
    return "this is monitor for ldap"

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=3531,debug=True)

上のipとxxxをあなたたち自身の対応する数値に置き換えます.このスクリプトはメッセージを微信にアラームするので、企業の微信を登録し、対応する値をスクリプトに記入する必要があります.
コマンドを使用してプログラムを実行します.
uwsgi  --http ip:3531 --wsgi-file index.py

または
vim myproject.ini
[uwsgi]
virtualenv=/home/ldap-monitor/myenv
callable=app
wsgi-file=index.py
http=:3531
master=true
processes=4
threads=2
pidfile=myproject.pid
max-requests=100

uwsgiプログラムをsystemctlに追加することもでき、より便利に実行できます.
# /etc/systemd/system/ldapmonitor.service
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
WorkingDirectory=/home/ldap-monitor
ExecStart=/usr/bin/uwsgi --ini /home/ldap-monitor/myproject.ini
ExecStop=/usr/bin/uwsgi --stop /home/ldap-monitor/myproject.pid
ExecReload=/usr/bin/uwsgi --reload /home/ldap-monitor/myproject.pid
[Install]
WantedBy=multi-user.target

flaskからのwebアドレスをprometheusの構成に追加し、1 mおきにアクセスすると、モニタリングプロセス全体が完了します.以上でopenldapのモニタリングが可能になり、ldapがオフになるとスクリプトの微信にアラームが鳴ります.