How to send a view as CSV every month via EMail

Hi sometimes it is necessary to regularly send a view as a report for further processing here is a script how I solved this:

user@monitoring:~# touch api-csv-mail.py #create file

user@monitoring:~# nano api-csv-mail.py # and put in code

# !/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# License: GNU General Public License v2
#
# Author: Bernd Holzhauer
#
# Description: Download CSV file from Server and send it via EMail
#
# V0.1 init release
#
import requests
import smtplib
import csv
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Download CSV file from API
url='http://your-url-to-view&_username=apiuser&_secret=YourAutomationSecret&output_format=csv_export&view_name=WhatYouLikeToExport'
response = requests.get(url)
csv_data = response.content.decode('utf-8')

# Create email message
msg = MIMEMultipart()
msg['From'] = 'bee@monitoring.com'
msg['To'] = 'report@to.com'
msg['Subject'] = 'View as CSV file from Monitoring'

# Attach CSV file to email message
attachment = MIMEText(csv_data)
attachment.add_header('Content-Disposition', 'attachment', filename='data.csv')
msg.attach(attachment)

# Send email
server = smtplib.SMTP('xxx.xxx.xxx.xxx', 25)  # Replace with your email server
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()

user@monitoring:~# chmod +x YourScript.py # make it executable

user@monitoring:~# crontab -e

To schedule a cron job to run on the first Monday of every month, you can use the following cron expression:

0 0 1-7 * 1 python3 /path/to/yourscript.py

nice Link to handle cron:

cron under linux

the easy way to get the URL of your view:

image

  • open the view
  • click on export
  • right click on “Export CSV”
    result looks like:
https://monitoring.com/yoursite/check_mk/view.py?output_format=csv_export&view_name=allhosts

and add your Automation User & PW to the URL like this:

https://monitoring.com/yoursite/check_mk/view.py?&_username=apiuser&_secret=apisecret&output_format=csv_export&view_name=allhosts

enjoy a happy manager !!!

maybe someone has time and mood or wants to give the trainee a task and builds the whole script as notification MKP and makes it so user friendly :wink:

4 Likes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed. Contact an admin if you think this should be re-opened.