由于需要知道公司资产中的相关服务器是否在zabbix的监控中,有些是不需要监控的,有些是资产更新之后zabbix没有监控的,要是一个个的去对比,比较麻烦,闲来无事,写了一个脚本,对比资产中的机器是否需要zabbix监控,然后发邮件给相关的负责人,及时的更新zabbix监控主机。主要原理是用MySQLdb模块查出zabbix中的主机和资产数据库中的主机列表,然后用列表的集合比较set来找出两个列表中不同的值,然后查看确定是在那个列表中,以不同的信息标识发邮件给负责人。
-
-
-
- import os,sys,MySQLdb,smtplib,datetime,time
- from email.mime.text import MIMEText
-
- def send_mail(content):
-
-
- mailto_list=["xxxxx@139.com"]
-
-
- mail_host="mail.xxx.cn"
- mail_user="zabbix"
- mail_pass="xxx"
- mail_postfix="xxxx.cn"
-
- ''
-
-
-
-
-
- me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
- msg = MIMEText(content,_charset='utf8')
- msg['Subject'] = u"zabbix主机检查-%s" % datetime.date.today()
- msg['From'] = me
- msg['To'] = ";".join(mailto_list)
- try:
- s = smtplib.SMTP()
- s.connect(mail_host)
- s.login(mail_user,mail_pass)
- s.sendmail(me, mailto_list, msg.as_string())
- s.close()
- except Exception, e:
- sys.exit()
-
- def conn_mysql(ip,user,passwd,sql):
- try:
- conn = MySQLdb.connect(host = ip,user = user,passwd = passwd,connect_timeout=20)
- cursor = conn.cursor()
- cursor.execute(sql)
- alldata = cursor.fetchall()
- cursor.close()
- conn.close()
- return alldata
- except:
- return 0
-
- def center_host():
- ip = '192.168.1.11'
- user = 'root'
- passwd = 'xxxxx'
- sql="SELECT ip FROM zichan.hosts WHERE STATUS=0"
- center_hostlist = conn_mysql(ip,user,passwd,sql)
- center = []
- for center_host in center_hostlist:
- center.append(center_host[0])
- center.sort()
- return center
-
- def zabbix_host():
- ip = '192.168.1.2'
- user = 'root'
- passwd = '1q2w3e4r'
- sql="SELECT HOST FROM zabbix.hosts WHERE STATUS=0"
- zabbix_hostlist = conn_mysql(ip,user,passwd,sql)
- zabbix = []
- for zabbix_host in zabbix_hostlist:
- zabbix.append(zabbix_host[0])
- zabbix.sort()
- return zabbix
-
- def main():
- center_hostlist = center_host()
- zabbix_hostlist = zabbix_host()
-
-
- difference = list(set(center_hostlist) ^ set(zabbix_hostlist))
- content = "\n"
- if len(difference) != 0:
- for host in difference:
- if host in center_hostlist:
- content = content + "%s_not_In_zabbix" % host + "\n"
- elif host in zabbix_hostlist:
- content = content + "%s_not_Out_zabbix" % host + "\n"
- else:
- sys.exit()
- send_mail(content)
-
- if __name__ == "__main__":
- main()
本文转自 lover00751CTO博客,原文链接:http://blog.51cto.com/wangwei007/1126428,如需转载请自行联系原作者