zabbix sync AD users
#!
/usr/bin/env python#coding:utf-8
import ldap,ldif3,sys,re
importMySQLdb
ldap_host="ldap://xx.xx.xx.xx"
ldap_user="xx@xx.xx"#abc@domain.com
ldap_pass="xxxx"
basedn ="OU=group,DC=domain,DC=com"
db_host="10.1.180.166"
db_port=3306
db_user="zabbix"
db_pass="zabbixpwd"
db_Name="zabbix"
#insert user to zabbix
#insert into users (userid,alias,passwd,autologin,type) (select max(userid)+1 as userid,'test','5fce1b3e34b520afeffb37ce08c7cd66',1,3 from users);
#select users
#select alias from zabbix.users where alias not regexp 'AR|Admin|guest' ;
def __mysql_operation(sql):
try:
conn =MySQLdb.connect(host=db_host,user=db_user,passwd=db_pass,port=db_port,db=db_Name)
cur = conn.cursor()
count = cur.execute(sql)
if count ==0:
zbx_result =0
else:
zbx_result = cur.fetchall()
conn.commit()
cur.close()
conn.close()
#print zbx_result
return zbx_result
exceptMySQLdb.Error,e:
print"Mysql Error:",e
def __ldap_query():
conn = ldap.initialize(ldap_host)
# set domain protocol version
conn.protocol_version =3
conn.set_option(ldap.OPT_REFERRALS,0)
# bind domain user
conn.simple_bind_s(ldap_user,ldap_pass)
ldif_writer = ldif3.LDIFWriter(sys.stdout)
retrieveAttributes =None
results = conn.search_s(basedn,ldap.SCOPE_SUBTREE,"(cn=*)",retrieveAttributes)
# for dn,entry in results:
# ldif_writer.unparse(dn,entry)
cn_list =[]
for result in results:
result_dn = result[0]
result_attrs = result[1]
if"member"in result_attrs:
for member in result_attrs["member"]:
re_result = re.search(r'\w+\s\w+',member)
if re_result:
cn_list.append(re_result.group().replace(' ','').lower())
#print member
user_list = sorted(set(cn_list))
return user_list
def main():
select_sql ='''select alias from users where alias not regexp 'AR|Admin|guest' ;'''
select_result = __mysql_operation(select_sql)
ldap_result = __ldap_query()
zabbix_user_list =[]
for s_row in select_result:
zabbix_user_list.append(s_row[0])
#print zabbix_user_list
# add domain user to zabbix
for l_row in ldap_result:
if l_row in zabbix_user_list:
print"The %s user alrady exist ! "%(l_row)
else:
insert_sql ='''insert into users (userid,alias,passwd,autologin,autologout,type) (select max(userid)+1 as userid,'%s','5fce1b3e34b520afeffb37ce08c7cd66',1,0,1 from users);'''%(l_row)
__mysql_operation(insert_sql)
print"Add %s user successed !"%(l_row)
# if zabbix user not exist for domain , delete this user.
for s_row in zabbix_user_list:
if s_row notin ldap_result:
delete_sql ='''delete from users where alias = "%s" ;'''%(s_row)
__mysql_operation(delete_sql)
print"Delete invalid %s user succeesed !"%(s_row)
else:
print"Not have invalid users !"
if __name__ =='__main__':
main()
首先:在windows AD创建一个zabbix用户, 最好和zabbix默认账号一致
然后配置ldap
执行脚本后,将AD所有用户都同步过来了,定期执行脚本,会自动添加删除用户, 同步AD
Growing old is mandatory, growing up is optional .