杰瑞科技汇

zabbix python mail

Of course! Sending emails from a Zabbix action using a Python script is a powerful and flexible way to customize your alert notifications. This is often preferred over Zabbix's built-in email functionality because it allows for more complex formatting, attaching multiple files, and using external SMTP services (like Gmail, SendGrid, etc.) more easily.

Here’s a complete, step-by-step guide on how to set this up.

Overview of the Process

  1. Write a Python Script: Create a Python script that can accept Zabbix macro variables and send an email.
  2. Make the Script Executable: Ensure Zabbix server (or Zabbix proxy) can run the script.
  3. Configure Zabbix:
    • Create a new Media Type in Zabbix that points to your Python script.
    • Create or modify an Action to use this new Media Type.
  4. Test: Trigger a problem to verify that the email is sent correctly.

Step 1: The Python Script (send_mail.py)

This script will be the core of our solution. It will parse the message subject and body from Zabbix's standard input (STDIN) and send an email using the smtplib library.

Place this script on your Zabbix server (or Zabbix proxy, if that's where you want notifications to originate from).

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# --- CONFIGURATION ---
# IMPORTANT: Fill in your SMTP server details here.
# It's better to use environment variables or a config file for sensitive data in production.
SMTP_SERVER = "smtp.your-mail-provider.com"
SMTP_PORT = 587
SMTP_USERNAME = "your-email@domain.com"
SMTP_PASSWORD = "your-app-specific-password" # Use an app password if using 2FA
# --- SCRIPT LOGIC (No changes needed below this line) ---
def send_email(recipient, subject, body):
    """
    Sends an email using the configured SMTP server.
    """
    # Create the email message
    msg = MIMEMultipart()
    msg['From'] = SMTP_USERNAME
    msg['To'] = recipient
    msg['Subject'] = subject
    # Attach the body as plain text
    msg.attach(MIMEText(body, 'plain'))
    try:
        # Create a secure SSL context
        context = ssl.create_default_context()
        # Connect to the SMTP server and send the email
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls(context=context) # Secure the connection
            server.login(SMTP_USERNAME, SMTP_PASSWORD)
            server.send_message(msg)
        print("Email sent successfully to", recipient)
        return True
    except Exception as e:
        print(f"Failed to send email: {e}", file=sys.stderr)
        return False
if __name__ == "__main__":
    # Zabbix passes the message to the script via standard input (STDIN)
    # The format is:
    # {ALERT.SENDTO}
    # {ALERT.SUBJECT}
    # {ALERT.MESSAGE}
    recipient = sys.stdin.readline().strip()
    subject = sys.stdin.readline().strip()
    body = sys.stdin.read() # Read the rest of the message
    if not recipient or not subject or not body:
        print("Error: Missing recipient, subject, or body.", file=sys.stderr)
        sys.exit(1)
    # Call the send_email function
    send_email(recipient, subject, body)

Crucial Notes on the Script:

  • SMTP Configuration: Replace the placeholder values with your actual SMTP server details. For Gmail, use smtp.gmail.com, port 587, and your email address. Crucially, you must use an "App Password" for Gmail if you have 2-Factor Authentication enabled. You cannot use your regular Gmail password.
  • Encoding: The script uses UTF-8 encoding, which is good for handling special characters in alert messages.
  • Error Handling: Basic error handling is included. If the email fails to send, an error message is printed to standard error (stderr), which Zabbix will log.

Step 2: Make the Script Executable

Now, you need to place the script on your Zabbix server and give it the correct permissions.

  1. Save the Script: Save the code above as send_mail.py in a directory, for example, /usr/lib/zabbix/alertscripts/. This is the default Zabbix script directory.

    sudo nano /usr/lib/zabbix/alertscripts/send_mail.py
    # Paste the Python code and save
  2. Set Permissions: The script must be executable by the zabbix user (or whatever user the Zabbix server runs as).

    sudo chown zabbix:zabbix /usr/lib/zabbix/alertscripts/send_mail.py
    sudo chmod +x /usr/lib/zabbix/alertscripts/send_mail.py
  3. Verify Zabbix Server Configuration: Ensure the Zabbix server knows where to find the scripts. Edit the zabbix_server.conf file:

    sudo nano /etc/zabbix/zabbix_server.conf

    Check and set the following parameter if it's not already set:

    AlertScriptsPath=/usr/lib/zabbix/alertscripts

    Restart the Zabbix server service for the change to take effect:

    sudo systemctl restart zabbix-server

Step 3: Configure Zabbix Media Type and Action

This is done in the Zabbix web interface.

A. Create the Media Type

  1. Go to Administration -> Media types.
  2. Click Create media type in the top right corner.
  3. Fill in the details:
    • Name: Python Email (or any descriptive name).
    • Type: Script.
    • Script name: send_mail.py (This must be the exact name of your script file).
    • Script parameters: Leave this empty. Our script reads from STDIN, which is the default behavior for Zabbix scripts.
  4. Click Add.

B. Create or Modify an Action

Now, we tell Zabbix when to use our new media type.

  1. Go to Configuration -> Actions.

  2. Click Create action (or edit an existing one like "Email").

  3. Action Tab:

    • Name: Send Python Email (or a descriptive name).
    • Default message: You can define a default message template here if you wish.
  4. Operations Tab:

    • Under Send message to, select the user group or user that should receive the alerts.

    • From the Media type dropdown, select your new Python Email media type.

    • When: Keep the default Operation is OK and Operation is PROBLEM.

    • Send only to: Ensure the correct media (e.g., Email) is selected for the users.

    • Message template: You can customize the subject and body here using Zabbix macros. For example:

      • Subject: PROBLEM: {TRIGGER.NAME} on {HOST.NAME}

      • Message:

        Trigger: {TRIGGER.NAME}
        Host: {HOST.NAME}
        IP: {HOST.IP}
        Severity: {TRIGGER.SEVERITY}
        Status: {TRIGGER.STATUS}
        Date: {DATE} {TIME}
        Problem item:
        {ITEM.NAME}: {ITEM.VALUE}
        Message:
        {TRIGGER.URL}
  5. Recovery Operations Tab (Optional but Recommended):

    • This tab defines what happens when a problem is resolved.

    • Check Send message to and select the same user group/media type.

    • Set Send only to to Recovery operations.

    • Message template:

      • Subject: RESOLVED: {TRIGGER.NAME} on {HOST.NAME}

      • Message:

        Trigger: {TRIGGER.NAME}
        Host: {HOST.NAME}
        IP: {HOST.IP}
        Severity: {TRIGGER.SEVERITY}
        Status: {TRIGGER.STATUS}
        Date: {DATE} {TIME}
        The problem has been resolved.
  6. Click Add or Update to save the action.


Step 4: Test the Configuration

The final step is to verify that everything works.

  1. Enable Notifications: Ensure the user or user group you configured in the Action has the Python Email media type enabled in their profile (Administration -> Users -> select user -> Media tab).
  2. Trigger a Problem: The easiest way is to stop a monitored service (e.g., sudo systemctl stop zabbix-agent on a monitored host) or disable a host in Zabbix.
  3. Check for Email: You should receive an email to the address specified in the user's media settings.
  4. Check Logs: If you don't receive an email, check the Zabbix server logs for errors.
    tail -f /var/log/zabbix/zabbix_server.log | grep send_mail

    This will show you the output from your Python script, including any "Email sent successfully" messages or error traces.

Advanced: HTML Emails

To send nicely formatted HTML emails, you just need to modify the Python script slightly.

  1. Change the send_email function:

    # In send_email(), change this line:
    # msg.attach(MIMEText(body, 'plain'))
    # To this:
    msg.attach(MIMEText(body, 'html')) # Changed 'plain' to 'html'
  2. Update the Zabbix Message Template: In your Action's Message template, you can now use HTML tags.

    Subject: PROBLEM: {TRIGGER.NAME} on {HOST.NAME} Message:

    <h2>Alert: {TRIGGER.NAME}</h2>
    <table border="1" cellpadding="5" cellspacing="0">
        <tr><td><b>Host:</b></td><td>{HOST.NAME}</td></tr>
        <tr><td><b>IP:</b></td><td>{HOST.IP}</td></tr>
        <tr><td><b>Severity:</b></td><td>{TRIGGER.SEVERITY}</td></tr>
        <tr><td><b>Status:</b></td><td>{TRIGGER.STATUS}</td></tr>
        <tr><td><b>Time:</b></td><td>{DATE} {TIME}</td></tr>
    </table>
    <hr>
    <h3>Problem Details:</h3>
    <p><b>Item:</b> {ITEM.NAME}</p>
    <p><b>Value:</b> <font color="red">{ITEM.VALUE}</font></p>
    <p><b>URL:</b> <a href="{TRIGGER.URL}">{TRIGGER.URL}</a></p>

Now, when an alert is triggered, you will receive a much more readable, formatted HTML email.

分享:
扫描分享到社交APP
上一篇
下一篇