shell脚本——批量安装zabbix-agent5.0

举例:
给元数据都为elk的主机列表中所有主机安装并配置zabbix-agent5.0

#!/bin/bash
# 用来在运行结果之前,先输出执行的那一行命令。
set -x
# 主机列表
host_array=(
    "192.168.172.22"
    "192.168.172.23"
)
# 获取安装机器的主机名
for host_ip in ${host_array[@]}
do 
    hostname=`ssh ${host_ip} 'hostname'`
done
# 定义元数据
hostmetadata=elk

# 安装并配置zabbix-agent
function install_zabbixagent() 
{
    host_ip=${1}
    # install zabbix-agent
    echo "start install zabbix-agent in host:${host_ip}"
    echo `ssh ${host_ip} "rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm"`
    echo `ssh ${host_ip} "yum clean all"`
    echo `ssh ${host_ip} "yum repolist"`
    echo `ssh ${host_ip} "yum install -y zabbix-agent"`
    echo "yum repo is ok and zabbix-agent has installed"
    # change configure file
    echo `ssh ${host_ip} "sed '/^Server=127.0.0.1/cServer=172.16.108.137' -i /etc/zabbix/zabbix_agentd.conf"`
    echo `ssh ${host_ip} "sed '/^ServerActive=127.0.0.1/cServerActive=172.16.108.137' -i /etc/zabbix/zabbix_agentd.conf"`
    echo `ssh ${host_ip} "sed 's/Hostname=Zabbix server/Hostname=${hostname}/g' -i /etc/zabbix/zabbix_agentd.conf"`
    echo `ssh ${host_ip} "echo "EnableRemoteCommands=1" >> /etc/zabbix/zabbix_agentd.conf"`
    echo `ssh ${host_ip} "echo "UnsafeUserParameters=1" >> /etc/zabbix/zabbix_agentd.conf"`
    echo `ssh ${host_ip} "echo HostMetadata="$hostmetadata" >> /etc/zabbix/zabbix_agentd.conf"`
    # start service
    echo `ssh ${host_ip} "systemctl start zabbix-agent.service"`
    echo `ssh ${host_ip} "systemctl enable zabbix-agent.service"`
}

# 判断是否已经安装zabbix-agent
function is_install_zabbixagent() 
{
    result=`ssh ${1} "yum list installed|grep zabbix-agent"`
    # -z zero 判断result的值是否为0,为0则为真
    if [ -z "${result}" ];then
        return 0
    else
        return 1
    fi 
}

# main函数,shell数组中使用@或*可以获取数组的全部元素
function main() 
{
    for host_ip in ${host_array[@]}
    do
        # get hostname
        hostname=`ssh ${host_ip} 'hostname'`
        # 判断返回值是否安装了zabbix-agent
        is_install_zabbixagent ${host_ip}
        # 返回值为0,即没有安装,调用函数
        if [ $? -eq 0 ];then
            install_zabbixagent ${host_ip}
            sleep 20s
        else
            echo "this host ${host_ip} already installed zabbix-agent"
        fi
    done
}

main

查看机器执行完脚本后配置文件的关键信息:

sed -n '/^#/!p' /etc/zabbix/zabbix_agentd.conf | sed -n '/^$/!p' 

先做免密,免密命令:

ssh-keygen
ssh-copy-id -i /root/.ssh/id_rsa.pub 192.168.172.22 
ssh-copy-id -i /root/.ssh/id_rsa.pub 192.168.172.23
原文地址:https://www.cnblogs.com/even160941/p/15237872.html