1、界面配置ldap验证(略)

2、mysql导入ldap帐号信息

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import pymysql
import commands
import base64
import sys
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

mysql_host='xxx.internal.xxx.com'
mysql_port=3306
mysql_user='zabbix'
mysql_passwd='zabbix'
mysql_db='zabbix'

def get_user_from_ldap ():
ldap_users=commands.getoutput("ldapsearch -x -LLL -H ldap://xxx.xxx.xxx.xxx-b dc=xx,dc=com givenName|sed '1,12'd|sed '/^$/d'|egrep -v 'ou=Group|ou=machines'").strip().splitlines()
return ldap_users

def get_value():
values = {}
lines = get_user_from_ldap()
for index,line in enumerate(lines):
if line.startswith("dn: cn="):
if (index+1)<len(lines) and lines[index+1].startswith("givenName:"):
strcount = lines[index+1].strip().split()[0].count(':')
if strcount == 2:
sourcename = lines[index+1].strip().split()[1]
name = base64.b64decode(sourcename)
else:
name = lines[index+1].strip().split()[1]
alias = lines[index].strip().split('=')[1].split(',')[0]
values[alias] = name
else:
print "The user [%s] set error on ldap server !" % line
return values

def get_id():
conn = pymysql.connect(host=mysql_host, port=mysql_port, user=mysql_user, passwd=mysql_passwd, db=mysql_db, charset='utf8')
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute("select userid from users order by userid desc limit 1")
id = cur.fetchone().values()[0]
cur.close()
conn.close()
return id

def get_mysql_data():
conn = pymysql.connect(host=mysql_host, port=mysql_port, user=mysql_user, passwd=mysql_passwd, db=mysql_db, charset='utf8')
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute("select userid from users order by userid desc limit 1")
id = cur.fetchone().values()[0]
cur.close()
cur_user = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur_user.execute("select alias from users")
user_data = cur_user.fetchall()
user_name = [name['alias'] for name in user_data]
cur_user.close()
conn.close()
return id,user_name

def insert_data():
conn = pymysql.connect(host=mysql_host, port=mysql_port, user=mysql_user, passwd=mysql_passwd, db=mysql_db, charset='utf8')
cur = conn.cursor()
n, zabbix_user = get_mysql_data()
# del_name = []
data = get_value()
ldap_name = data.keys()
for alias, name in data.items():
search = cur.execute("select * from users where alias = %s", (alias, ))
if not search:
n += 1
sql = "insert into users(userid,name,alias) values ('%s','%s','%s');" % (n,name,alias)
insert = cur.execute(sql)
if insert:
with open ('/opt/ldap.log', 'a') as log:
time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
str = "User %s Name's %s and Userid's %s Add Succeed at %s" % (alias,name,n,time)
log.write(str+'\n')
del_cur = conn.cursor()
for name in zabbix_user:
if name not in ldap_name:
if name.lower() != 'zabbix' or name.lower() != 'guest':
# del_name.append(name)
try:
del_data = del_cur.execute("delete from users where alias = %s", (name,))
if del_data:
with open ('/opt/ldap.log', 'a') as del_log:
del_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
del_str = "User %s del succeed at %s" % (name, del_time)
del_log.write(del_str+'\n')
except (Exception), error_str:
print error_str
print "when del %s failed" % name
# print del_name
conn.commit()
cur.close()
conn.close()

if __name__ == '__main__':
insert_data()

zabbix 同步ldap帐号脚本的更多相关文章

  1. VBS处理AD帐号密码到期提醒的脚本[zt]

    原文:https://gallery.technet.microsoft.com/scriptcenter/f7f5f7ed-14ee-4d0e-81c2-7d95ce7e08f5 '======== ...

  2. shell脚本,批量创建10个系统帐号并设置密码为随机8位字符串。

    [root@localhost wyb]# cat user10.sh #!/bin/bash #批量创建10个系统帐号wangyb01-wangyb10并设置密码(密码为随机8位字符串). > ...

  3. 如何修改SharePoint2013服务器场帐号密码

    服务器远程登录帐号密码修改密码后,如何修改sharepoint服务器场管理员账户密码,今天登录了一下N久以前的搭建sharepoint2013服务器场的一台服务器器,登录进去以后直接提示帐号密码过期需 ...

  4. wex5 实战 登陆帐号更换与用户id一致性

    一 前言 关于用户登陆,注册,页面跳转,我讲了很多,都是页面框架级别的.有人问到这个问题,索性总结一下,今天是收尾最后一篇. 以往初学时的设计是: 1 注册 2 登陆 3 进入页面. 这种很简单,没有 ...

  5. 在SQL Server中添加供应用程序使用的帐号

        在之前客户咨询案例中,很多客户应用程序连接SQL Server直接用的就是SA帐号.如果对数据库管理稍微严格一点的话,就不应该给应用程序这种权限,通常应用程序只需要进行增删改查,而很少有DDL ...

  6. 3种用组策略将域帐号加入本地管理员组的方法_jinifly_新浪博客

    次当前系统域帐号是怎么在第一次登录时,自动加入域客户端本地管理员组的?我猜不外乎就是脚本.计算机策略或虚拟机初始化的自动应答脚本,结果系统的前任同事找到了答案--GPO的用户策略(确切讲是用户首选项) ...

  7. 为github帐号添加SSH keys

    为github帐号添加SSH keys 2012-05-26 00:05 34279人阅读 评论(6) 收藏 举报 ssh文本编辑gitvim工具up 使用git clone命令从github上同步g ...

  8. 用firefox 31配合KeePass密码管理器实现web帐号密码自动填写登录

    原文:http://bbs.kafan.cn/thread-1754676-1-1.html KeePass的优势:1.这是一款完全开源的密码管理器2.很多人都使用lastpass来保存密码,而这种严 ...

  9. Chapter 2 User Authentication, Authorization, and Security(2):创建登录帐号

    原文出处:http://blog.csdn.net/dba_huangzj/article/details/38705965,专题目录:http://blog.csdn.net/dba_huangzj ...

随机推荐

  1. C++ 中的静态成员函数与静态成员变量

    于CSDN 2014-01-17 与静态数据成员一样,静态成员函数是类的一部分,而不是对象的一部分.如果要在类外调用公用的静态成员函数,要用类名和域运算符"∷".如Box∷volu ...

  2. 【转载】 C#中ArrayList集合类的使用

    在C#的集合操作过程中,我们一般常用的集合类为List集合,List集合是一种强类型的泛型集合,其实还有一个ArrayList集合类,ArrayList集合类则非泛型类的集合,并且ArrayList集 ...

  3. ios、安卓前端兼容性

    1.日期兼容性 解决方法(请看我上一篇文章)安卓.ios时间转换成时间戳的形式 2.input框聚焦,ios出现outline或者阴影,安卓显示正常 解决方法 input:focus{outline: ...

  4. 学习笔记之自然语言处理(Natural Language Processing)

    自然语言处理 - 维基百科,自由的百科全书 https://zh.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7 ...

  5. element-ui Upload 上传获取当前选择的视频时长

    <el-upload class="upload-demo" ref="vidos" :action="URL+'/api/post/file' ...

  6. xen虚拟化环境安装

    1. 操作系统安装 OEL下载地址大全: http://koumm.blog.51cto.com/703525/1283801 # uname -a Linux localhost 2.6.39-40 ...

  7. PHP实现Redis单据锁,防止并发重复写入

    一.写在前面 在整个供应链系统中,会有很多种单据(采购单.入库单.到货单.运单等等),在涉及写单据数据的接口时(增删改操作),即使前端做了相关限制,还是有可能因为网络或异常操作产生并发重复调用的情况, ...

  8. python中pymsql常用方法(1)

    python中pymysql模块常用方法以及其使用 首先我们知道pymysql 是python中操作数据库的模块 使用步骤分为如下几步: ​ 1.与数据库服务器建立链接 conn=pymysql.Co ...

  9. LaTeX的安装并使其能够编译中文

    首先,感谢博客园团队帮我找回这篇被我误删除的博客.找回方法:发送邮件至"contact@cnblogs.com",然后就可以在工作人员的帮助下找回了.下面介绍LaTeX的安装并使其 ...

  10. matplotlib--基本setting

    一.创建自定义图像 figure figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=Tr ...