zabbix alarm settings

Alarm can be divided into email alarm, nail alarm, wechat alarm and SMS alarm
Step one:
Create a user,

One mailbox alarm

First kind

1.1 install mailx first

[root@zabbix]# yum install mailx -y
1.1.2 edit the configuration file and add it in the last line
[root@zabbix]# vim /etc/mail.rc
set bsdcompat
set sendcharsets=iso-8859-1,utf-8
set from=mailbox
set smtp=smtp://smtp.exmail.qq.com
set smtp-auth-user=mailbox
set smtp-auth-password=Mailbox password
set smtp-auth=login
1.1.3 test whether the email is sent normally
[root@zabbix]# Echo "ZABBIX test mail" | - s "ZABBIX" email
1.1.4 writing e-mail script

[root@zabbix alertscripts]# cd /usr/lib/zabbix/alertscripts
[root@zabbix alertscripts]# vi mail.sh

#!/bin/bash
#send mail

messages=echo $3 | tr '\r\n' '\n'
subject=echo $2 | tr '\r\n' '\n'
echo "${messages}" | mail -s "${subject}" $1 >>/var/mailx.log 2>&1
1.1.5 modification authority
touch /var/mailx.log 
chown -R zabbix.zabbix /var/mailx.log 
chmod +x /usr/lib/zabbix/alertscripts/mailx.sh
chown -R zabbix.zabbix /usr/lib/zabbix/
1.1.6 test script sending email
[root@zabbix alertscripts]# echo "hello world" | mail -s "testmail" your email


Add three script parameters
{ALERT.SENDTO}
{ALERT.SUBJECT}
{ALERT.MESSAGE}

Set the alarm


The second postbox setting

1.2 install postfix

yum install postfix? Install Postfix

1.2.2 install sasldb and saslauthd

#Provide virtual account and password service of smtp 
yum install cyrus-sasl*  
#sasldb2 is included in saslauthd 
 

1.2.3 current mta view

alternatives --display mta  

1.2.4 setting mta

/usr/sbin/alternatives --set mta /usr/sbin/sendmail.postfix 

1.2.5 review mta again

alternatives --display mta  
#The last line of the output result will have a prompt similar to the following: mta is set up 
#Current `best' version is /usr/sbin/sendmail.postfix. 

1.2.6 postfix startup settings

Because sasldb2 is used to provide the smtp account and password of postfix, there is no need for saslauthd service to run
systemctl enable postfix
systemctl start postfix 

1.2.7 configure and enable smtp in postfix

The main modified configuration file is / etc/postfix/main.cf,
See the code section for configuration instructions

cat  /etc/postfix/main.cf #
 #Find the following configuration items to modify as appropriate 

###### 
myhostname =  mail.test.com. 
#Modify the host name of postfix to your domain name. This item needs to add A record and point to the host IP of postfix 
mydomain   =  test.com.  
#domain name 
myorigin   =  $mydomain  
#After the mailbox domain name of local postfix, the default value of this item is myhostname 
#The mydomain mentioned above is used here, that is to say, the postfix email suffix of the local machine is: @ jjonline.com.cn 
inet_interfaces = localhost  
#Specify the network interface that the postfix system listens to, which must be localhost or 127.0.0.1 or intranet ip 
#If you note or fill in the public ip server port 25, it will be open to the public network 
#The default value is all, which means listening to all network interfaces 
#This item specifies that after localhost, local postfix can only send mail and cannot receive mail 
inet_protocols = ipv4 
#Network protocol ipv6 is not very popular in China 
mydestination = $myhostname, localhost.$mydomain, localhost 
#Specify the domain name of the recipient when postfix receives the mail, in other words, what kind of mail your postfix system will receive. 
#In this configuration, $myhostname indicates that postfix accepts email with suffix of @ $myhostname. Comma segmentation supports multiple items 
#This default uses myhostname 
local_recipient_maps = 
#The rules for receiving mail can be hash file, which is meaningless for this configuration and can be commented directly 
mynetworks = x.x.x.x, 192.158.xxx.xxx, 127.0.0.1  
#Specify the network address of your network 

#Modify according to the actual situation 
smtpd_banner = test.com ESMTP Server 
#Specifies the header information returned when MUA connects to postfix through smtp 
#The original configuration is attached with the version number of postfix, which can be removed as appropriate 
#SMTP Config 
broken_sasl_auth_clients = yes 
#Specify that postfix is compatible with MUA and uses irregular smtp protocol -- mainly for the old version of outlook, which is meaningless for this configuration 
mynetworks_style = host 
relay_domains = $mydestination 


#smtp to add
#========================================================================
smtpd_client_restrictions = permit_sasl_authenticated 
#Specifies the host name or ip address of the client that can initiate an SMTP connection to postfix 
#Here, permit ﹣ sasl ﹣ authenticated means that all users who have passed sasl authentication (that is, users who have passed account and password validation when connecting to smtp) are allowed 
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination 
#The address provided by the sender when executing the RCPT TO command is restricted. Copy here 
smtpd_sasl_auth_enable = yes 
#Specifying postfix to use sasl for authentication is to enable smtp and require account and password validation 
smtpd_sasl_local_domain = $mydomain 
#Specify the local domain name for SMTP authentication. This configuration can use smtpd ﹣ SASL ﹣ local ﹣ domain = ', or simply comment out that the default is empty 
smtpd_sasl_security_options = noanonymous 
#Cancel the anonymous login of smtp. The default value of this item is nonanonymous smtp. If anonymous login is very harmful, please specify it as nonanonymous 
message_size_limit = 5242880 
#Specifies the volume size of mail sent through postfix, which is 5M here 

1.2.8 sasldb2 establish smtp user and password

 Edit the configuration of enabling smtp account password validation through sasl 
VI / etc / sasl2 / smtpd.conf VI write or edit as follows: 
pwcheck_method: saslauthd 
mech_list: plain login 

#Note: the location of this configuration file is on a 64 bit machine, and the 32-bit machine should be on / usr/lib/sasl2/smtpd.conf

1.2.9 create an smtp account

saslpasswd2 -c -u `postconf -h mydomain` test #Enter the password twice in a row 
#Represents the email account (also the account of smtp) and password for creating test@$mydomain 
#This example is to create a test@test.com account and password 
#Note that the account used for smtp login is not just the user name, but the entire email address string 
#Suppose that the smtp account set here, test@test.com, is used when testing under test 

1.2.10 view the user and password of sasldb2

sasldblistusers2 
#This command enters the user to view the user status of sasldb 
#This command will output such contents as test@test.com: userPassword after entering 
Restart postfix or reload after each smtp user is added 

Two nail alarm

cd /usr/lib/zabbix/alertscripts  #This directory stores scripts``

This script needs to be modified and tested by yourself

#!/usr/bin/python
#-*- coding: utf-8 -*-
import requests,time
import json,sys,re,os

zabbixserver_url = 'http://39.104.84.241:80/index.php'
#Specific address
auth = 'aaaaa'
#Certified parameters

def get_itemid():
    a=re.findall(r"ITEM ID: \d+",info2)
    i=str(a)
    itemid=re.findall(r"\d+",i)
    return int("".join(itemid).lstrip('[\'').rstrip('\']'))

def get_picture(itemID,pname):
    myRequests = requests.Session()
    try:
        loginHeaders = {
            "Host": '39.104.84.241:80',
            "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "user-Agent":"Mozilla/6.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.91 Safari/537.36"
        }
        # Information needed to build a login
        playLoad = {
            "name": "Admin",
            "password": 'admin',
            "autologin": "1",
            "enter": "Sign in",
        }
        myRequests.post(zabbixserver_url, headers=loginHeaders, data=playLoad)

        testUrl = "http://39.104.84.241/chart.php"
        testUrlplayLoad = {
        "itemids": itemID,
        "from": "now-2h",
	"to":"now",
        "width": "700",
        }
        testGraph =  myRequests.get(url=testUrl,params=testUrlplayLoad)
        IMAGEPATH = os.path.join('/usr/share/nginx/html/dingding_pic/', pname)
        f = open(IMAGEPATH, 'wb')
        f.write(testGraph.content)
        f.close()
        pname_url = 'http://39.104.84.241:80/dingding_pic/' + pname
        return pname_url
    except Exception as e:
        print e
        return False


def send_msg(pname_url):
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": info1,
            "text": info3+"[Failed to save the image in the external chain,Source station may have anti-theft chain mechanism,It is recommended to save the pictures and upload them directly(img-2O-aaa)(%s)]\n"%(pname_url)
	    	
        },
        "at":{
            "atMobiles": reminders,
            "isAtAll": False,
        },
        }
    r = requests.post(webhook_url,data=json.dumps(data),headers=headers)
def info_text():
    new_text = ""
    x = info2.split('\n')
    for i in x:
	if re.search('ITEM ID',str(i)):
	    pass
        else:
	    new_text += "- "+str(i)+('\n')
    return new_text

if __name__ == '__main__':
    os.system("echo hello >> /tmp/syslog.md")   
    pname = str(int(time.time()))+'.png'
    info1 = str(sys.argv[2])
    info2 = str(sys.argv[3])
    info3 = info_text()
    with open('/tmp/syslog.md','a') as f:
	f.write(info1)
	f.write(info2)
	#f.writelines(sys.argv[1])
	#f.writelines(sys.argv[2])
        f.close()
    reminders = []
    webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=232284dd1b239f3e05c'
    itemid = get_itemid()
    print itemid	
    pname_url=get_picture(itemid,pname)
    print pname_url
    send_msg(pname_url)```

![Insert picture description here](https://img-blog.csdnimg.cn/20200311190226195.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpYW93dW5vbmdoZW4=,size_16,color_FFFFFF,t_70)

Three wechat alarms

Script

[root@kd-zabbix alertscripts]# cat weixin.py 
#!/usr/bin/python
#_*_coding:utf-8 _*_
 
  
import urllib,urllib2
import json
import sys
import simplejson
 
reload(sys)
sys.setdefaultencoding('utf-8')
 
 
def gettoken(corpid,corpsecret):
    gettoken_url = 'https://weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
    print  gettoken_url
    try:
        token_file = urllib2.urlopen(gettoken_url)
    except urllib2.HTTPError as e:
        print e.code
        print e.read().decode("utf8")
        sys.exit()
    token_data = token_file.read().decode('utf-8')
    token_json = json.loads(token_data)
    token_json.keys()
    token = token_json['access_token']
    return token


def senddata(access_token,user,subject,content):
  
    send_url = 'https://weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    send_values = {
        "touser":"@all",
        "toparty":"2",
        "msgtype":"text",
        "agentid":"107",
        "text":{
            "content":subject + '\n' + content
           },
        "safe":"0"
        }
#    send_data = json.dumps(send_values, ensure_ascii=False)
    send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
    send_request = urllib2.Request(send_url, send_data)
    response = json.loads(urllib2.urlopen(send_request).read())
    print str(response)
  
  
if __name__ == '__main__':
    user = str(sys.argv[1])
    subject = str(sys.argv[2])
    content = str(sys.argv[3])
     
    corpid =  'Aww3'
    corpsecret = 'AaI6YaWMM4'
    accesstoken = gettoken(corpid,corpsecret)
    senddata(accesstoken,user,subject,content)

4. Set alarm action

When an event occurs, we can perform corresponding actions according to the event. According to the event source, it can be divided into trigger actions, automatic discovery actions, automatic registration actions, internal event actions. The automatic discovery actions were mentioned in the previous automatic discovery. Here is an introduction to trigger actions. When a trigger event reaches the necessary conditions for executing actions, it will execute corresponding actions Action

4.1 actions

4.2 operation

4.3 recovery operation


When finished, add the action.

66 original articles published, praised and visited 2059
Private letter follow

Tags: Zabbix JSON network yum

Posted on Wed, 11 Mar 2020 08:52:36 -0400 by renesis