ansible和python的zabbix_api批量添加rsync服务的监控

一、正常的处理流程:

1.添加zabbix用户对rsync程序的sudo权限,且不需要输入密码
# visudo即在/etc/sudoers配置文件最后添加如下内容

Defaults:zabbix !requiretty
zabbix ALL=NOPASSWD: ALL
zabbix ALL=NOPASSWD: /bin/bash /usr/local/rsync/bin/rsync


2.编写自动拉起服务的脚本,判断rsync程序是否存在,如果不存在就启动rsync
# vim /usr/local/zabbix_agents_3.2.0/scripts/start_rsy.sh
#!/bin/bash
count_num=`ps -ef|grep 'rsync'|grep -v grep|wc -l`
echo $count_num
if [ $count_num -eq 0 ];then
/etc/init.d/rsync start
fi

# 添加程序的可执行权限
[root@web02:~]# chmod +x /usr/local/zabbix_agents_3.2.0/scripts/start_rsy.sh

3.打开zabbix agent的远程命令
sed -i 's|# EnableRemoteCommands=0|EnableRemoteCommands=1|g' /usr/local/zabbix_agents_3.2.0/conf/zabbix_agentd.conf

# 重启zabbix客户端
[root@web02:~]# /etc/init.d/zabbix_agentd restart

二、使用ansible批量处理添加rsync的监控
ansible批量添加监控需要做大量的准备工作,相对比较繁琐,如果需要监控的主机就几台手动几分钟就添加好了,当集群大到一定规模手动处理就显得很笨拙了
使用ansible进行添加,后面即使新增单台服务器也可以这么操作,可以避免我们手动操作遗漏步骤

# 添加需要处理的主机信息
# vim /etc/ansible/hosts
chinasoft_cbs_backend_web2    ansible_host=172.30.0.243    ansible_port=2018    ansible_user=root    ansible_ssh_pass=pass
chinasoft_apiser_web03    ansible_host=172.30.0.27    ansible_port=2018    ansible_user=root    ansible_ssh_pass=pass
chinasoft_platform_web01    ansible_host=172.30.0.19    ansible_port=2018    ansible_user=root    ansible_ssh_pass=pass
chinasoft_platform_web02    ansible_host=172.30.0.17    ansible_port=2018    ansible_user=root    ansible_ssh_pass=pass
chinasoft_platform_web03    ansible_host=172.30.0.20    ansible_port=2018    ansible_user=root    ansible_ssh_pass=pass
chinasoft_platform_web04    ansible_host=172.30.0.18    ansible_port=2018    ansible_user=root    ansible_ssh_pass=pass

1.添加sudoer的权限
# 添加zabbix的sudo权限,/etc/sudoers结尾添加这三行
Defaults:zabbix !requiretty
zabbix ALL=NOPASSWD: ALL
zabbix ALL=NOPASSWD: /bin/bash /usr/local/rsync/bin/rsync

# 所有sudo执行rsync的权限
ansible all -m blockinfile -a 'path=/etc/sudoers block="Defaults:zabbix !requiretty\nzabbix ALL=NOPASSWD: ALL\nzabbix ALL=NOPASSWD: /bin/bash /usr/local/rsync/bin/rsync\n" insertbefore=EOF'

2.拷贝脚本到远程主机

ansible all -m copy -a "src=/usr/local/zabbix_agents_3.2.0/scripts/start_rsy.sh dest=/usr/local/zabbix_agents_3.2.0/scripts/ mode=0755"

3.开启远程命令
ansible chinasoft_cbs_out_db3 -m shell -a "sed -i 's|# EnableRemoteCommands=0|EnableRemoteCommands=1|g' /usr/local/zabbix_agents_3.2.0/conf/zabbix_agentd.conf"


4.zabbix-server在web上添加action动作

具体执行:
# 使用一台机器用ansible添加脚本、sudo权限进行测试,如果手动关闭rsync能否触发自动启动rsync的脚本说明没问题,就可以批量进行处理了

# 添加sudo权限
ansible chinasoft_cbs_out_db3 -m blockinfile -a 'path=/etc/sudoers block="Defaults:zabbix !requiretty\nzabbix ALL=NOPASSWD: ALL\nzabbix ALL=NOPASSWD: /bin/bash /usr/local/rsync/bin/rsync\n" insertbefore=EOF'

# 添加脚本
ansible chinasoft_cbs_out_db3 -m copy -a "src=/usr/local/zabbix_agents_3.2.0/scripts/start_rsy.sh dest=/usr/local/zabbix_agents_3.2.0/scripts/ mode=0755"

# 开启远程命令
ansible chinasoft_cbs_out_db3 -m shell -a "sed -i 's|# EnableRemoteCommands=0|EnableRemoteCommands=1|g' /usr/local/zabbix_agents_3.2.0/conf/zabbix_agentd.conf"

# 验证远程命令
ansible all -m shell -a "grep EnableRemoteCommands /usr/local/zabbix_agents_3.2.0/conf/zabbix_agentd.conf"

# 重启zabbix-agent
ansible chinasoft_cbs_out_db3 -m shell -a "executable=/bin/bash /etc/init.d/zabbix_agentd restart"


批量处理:

# 确认是否有rsync服务
ansible all -m shell -a "ps -ef|grep 'rsync --daemon'"

ansible all -m blockinfile -a 'path=/etc/sudoers block="Defaults:zabbix !requiretty\nzabbix ALL=NOPASSWD: ALL\nzabbix ALL=NOPASSWD: /bin/bash /usr/local/rsync/bin/rsync\n" insertbefore=EOF'

ansible all -m copy -a "src=/usr/local/zabbix_agents_3.2.0/scripts/start_rsy.sh dest=/usr/local/zabbix_agents_3.2.0/scripts/ mode=0755"

# ansible all -m shell -a "ls /usr/local/zabbix_agents_3.2.0/scripts/start_rsy.sh"

ansible all -m shell -a "sed -i 's|# EnableRemoteCommands=0|EnableRemoteCommands=1|g' /usr/local/zabbix_agents_3.2.0/conf/zabbix_agentd.conf"

ansible all -m shell -a "grep EnableRemoteCommands /usr/local/zabbix_agents_3.2.0/conf/zabbix_agentd.conf"

# 重启zabbix-agent
ansible all -m shell -a "executable=/bin/bash /etc/init.d/zabbix_agentd restart"


三、使用zabbix_api批量为主机添加监控rsync程序的模板

使用zabbix_api批量添加模板的脚本:
template_massadd.py

#!/usr/bin/python
#-*- coding:utf8 -*-
import json,sys,argparse
from zabbix_api import ZabbixAPI
server = "http://10.11.0.212/api_jsonrpc.php"
username = "Admin"
password = "zabbix"
zapi = ZabbixAPI(server=server, path="", log_level=0)
zapi.login(username, password)

'''
1. 安装zabbix插件 D:\python\zabbix>pip install zabbix-api
2. 使用 zabbix_getallhosts.py 脚本获取主机名,将需要的主机名筛选出来

使用方法:
cmd下:
python template_massadd.py --host="chinasoft_cbs_frontend_web01,chinasoft_cbs_frontend_web02,chinasoft_cbs_backend_web1,chinasoft_cbs_backend_web2,chinasoft_cbs_backend_web3,chinasoft_cbs_backend_web4,web01,web02,chinasoft_store_web01,chinasoft_store_web02,chinasoft_apiser_web01,chinasoft_apiser_web02,chinasoft_payment_web01,chinasoft_payment_web02,chinasoft_platform_web01,chinasoft_platform_web02,chinasoft_platform_web03,chinasoft_platform_web04,chinasoft_apicms_backend_web01,chinasoft_apicms_backend_web02,eus-timed-task01,eus-store-pay01,eus-apiserver-web03,eus-apiserver-web04" --"templates"="Template process rsync"
'''

# 获取参数
def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-H", "--host", help="host name")
    parser.add_argument("-t", "--templates", help="template name")
    # 解析所传入的参数
    args = parser.parse_args()
    if not args.host:
        args.host = raw_input('host: ')
    if not args.templates:
        args.templates = raw_input('templates: ')
    return args

def get_host_id(host):
    get_host_id = zapi.host.get(
        {
            "output": "hostid",
            "filter": {
                "host":host.split(",")
            }
        }
    )
    host_id = []
    host_id.append([I['hostid'] for I in get_host_id])
    return host_id[0]

def get_templates_id(templates):
    templates_id = zapi.template.get(
        {
            "output": "templateid",
            "filter": {
                "host":templates.split(",")
            }
        }
    )
    return templates_id
    
def template_massadd(template_id,host_id):
    template_add = zapi.template.massadd(
        {
            "templates": template_id,
            "hosts": host_id
            }
    )
    return "host add template success"
    

# 程序入口
if __name__ == "__main__":
    args = get_args()
    print 'args:%s' % args
    host_id = get_host_id(args.host)
    print 'host_id = %s' % host_id
    template_id = get_templates_id(args.templates)
    print 'template_id: %s' % template_id
    if len(host_id) == len(args.host.split(',')):
        if len(template_id) == len(args.templates.split(',')):
            print template_massadd(template_id,host_id)
        else:
            print "template not exist"
    else:
        print "host not exist"


# 用法:

# python template_massadd.py --host="chinasoft_apiser_web01,chinasoft_payment_web01" --"templates"="Template process rsync"
# host add template success

###########################
批量获取主机名的脚本

#!/usr/bin/evn python
# coding=utf-8
  
import requests
import json
  
ZABIX_ROOT = "http://10.11.0.212"
url = ZABIX_ROOT + '/api_jsonrpc.php'
  
# user.login
payload = {
     "jsonrpc" : "2.0",
     "method" : "user.login",
     "params": {
     'user': 'Admin',
     'password':'zabbix',
     },
     "auth" : None,
     "id" : 0,
    }
headers = {'content-type': 'application/json',}

req = requests.post(url, json=payload, headers=headers)
auth = req.json()
  
# host.get
#主机显示名        'name'],
# hosts是zabbix.conf文件中配置的主机名
payload = {
        "jsonrpc" : "2.0",
        "method" : "host.get",
        "params": {
        'output': [
        'hostid',
        'host'],
        },
        "auth" : auth['result'],
        "id" : 2,
    }
res2 = requests.post(url, data=json.dumps(payload), headers=headers)
res2 = res2.json()

#        f.write(host['name'] + '\n')
for host in res2['result']:
    with open('host.txt', 'a+') as f:

        f.write(host['host'] + '\n')

 

posted @ 2018-08-25 08:19  reblue520  阅读(551)  评论(0编辑  收藏  举报