脚本可以根据实际用途修改,这里我是根据我需要提供的用途修改了信息。
#定义待会要用到的变量
re_sh="sh"
re_sz="sz"
re_bj="bj"
re_sz_ip="10.2"
re_sh_ip="10.4"
re_bj_ip="10.5"
syslog_ip="10.3.9.3"
#centos os check
os_file=/etc/redhat-release
C_os="CentOS"
#定义函数变量此处仅为提供函数的写法,函数的内容是通过eof来把文本写入配置文件
function cat_esrepo
{
rm -f /etc/yum.repos.d/elastic.repo
cat >> /etc/yum.repos.d/elastic.repo << EOF
[elastic-7.x]
name=Elastic repository for 7.x packages
baseurl=https://artifacts.elastic.co/packages/7.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md
EOF
}
#检测日志文件是否存在
if [ -f "/var/log/syslog" -o -f "/var/log/messages" ];then
echo "/var/log/syslog or /var/log/messages exist"
else
echo "/var/log/syslog or /var/log/messages no exist"
exit 1
fi
#测试日志接收端是否可通讯,无法通讯就退出脚本
ping -c 1 $syslog_ip &>/dev/null
if [ $? -eq 0 ];then
echo "syslog server cas ping"
else
echo "syslog server ping loss"
exit 1
fi
#判断系统,从而确定执行如何安装
if [ -f "$os_file" ];then
if [[ `cat /etc/redhat-release` =~ $C_os ]];then
sudo rpm --import https://packages.elastic.co/GPG-KEY-elasticsearch
#touch /etc/yum.repos.d/elastic.repo
cat_esrepo
sudo yum install filebeat -y
sudo yum install net-tools -y
fi
else
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch |sudo apt-key add -
apt-get install apt-transport-https
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" > /etc/apt/sources.list.d/elastic-7.x.list
sudo apt-get update && sudo apt-get install -y filebeat
apt install net-tools -y
fi
#准备filebeat的配置文件
mv /etc/filebeat/filebeat.yml /etc/filebeat/filebeat.yml.bak
cat >> /etc/filebeat/filebeat.yml <<EOF
filebeat:
inputs:
- type: log
paths:
- /var/log/syslog
- /var/log/messages
fields:
region: <REGION>
fields_under_root: true
ignore_older: 6h
close_timeout: 5m
name: <SERVER_IP>
shipper:
name: <SERVER_IP>
processors:
- add_tags:
tags: [linux_event]
output:
logstash:
hosts: ["10.3.9.3:5044", # Logstash_1
"10.3.9.4:5044" # Logstash_2
]
loadbalance: true
worker: 8
backoff.init: 1800s
backoff.max: 1800s
EOF
#获取本地ip地址,取第一个ip并替换到配置文件
local_ip=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"|grep 10.|head -1`
# echo "${local_ip}"
sed -i "s/<SERVER_IP>/$local_ip/g" /etc/filebeat/filebeat.yml
#根据ip判断区域如北京,把区域写入到配置文件。
if [[ $local_ip =~ $re_sz_ip ]];then
sed -i "s/<REGION>/$re_sz/g" /etc/filebeat/filebeat.yml
elif [[ $local_ip =~ $re_sh_ip ]];then
sed -i "s/<REGION>/$re_sh/g" /etc/filebeat/filebeat.yml
elif [[ $local_ip =~ $re_bj_ip ]];then
sed -i "s/<REGION>/$re_bj/g" /etc/filebeat/filebeat.yml
elif [[ $local_ip =~ $re_sz_ip1 ]];then
sed -i "s/<REGION>/$re_sz/g" /etc/filebeat/filebeat.yml
fi
#启动服务并激活开机启动
sudo systemctl start filebeat
sudo systemctl enable filebeat
sudo systemctl restart filebeat