Sending Alert Mail on Shutdown and Boot up!

Hello! 

In this time, I want to run an custom application as a service on my LINUX and want to run with specific user to follow some security policies. Can customize your actionable scripts with this if  your are working on systemd related machines.

Need to be running Postfix service before the demonstration! So let me into demonstration about sending system shutdown and startup alert mail to system administrator. I intend this to let system admin know as a proof of machine power state in an incident. 

Firstly, must have actionable script or application that you want to run. demo use mail command as a service. I have two scripts. one for system up and one or system down. startupmail.sh was as follow:

#!/bin/bash
DATE=$(date '+%Y-%m-%d %H:%M:%S')
$(mail -s "$HOSTNAME - System Start" exampleuser@example.com <<< "$HOSTNAME was started at $DATE")

shutdownmail.sh was as follow:

#!/bin/bash
DATE=$(date '+%Y-%m-%d %H:%M:%S')
$(mail -s "$HOSTNAME - System Shutdown" exampleuser@example.com <<< "$HOSTNAME was shutdown at $DATE"; sleep 5)

I put that files(startup.sh and shutdown.sh) under user home directory by making new directory.

Performer is mail4sysdown_n_up.service and should be located under /etc/systemd/system/ directory. It helps to run two actionable scripts as a service. 

[Unit]
Description=Send a mail on Boot and Shutdown Task
Requires=postfix.service
After=network-online.target postfix.service

[Service]
Type=oneshot
User= #scriptUser to run the scripts !root
RemainAfterExit=true
ExecStart=/opt/startupmail.sh
ExecStop=/opt/shutdownmail.sh

[Install]
WantedBy=multi-user.target

Steps to live this service:
$sudo setfacl -m u:scirptUser:rwx /etc/systemd/system/mail4sysdown_n_up.service
$sudo chown scirptUser:scriptUser startupmail.sh shtudownmail.sh
$sudo chmod 755 startupmail.sh shtudownmail.sh

$sudo systemctl start mail4sysdown_n_up.service
$sudo systemctl enable mail4sysdown_n_up.service

uncertainty and risk: I am not sure setting ACL under /etc directory is safe. 

Have a good time!!


Comments

Popular posts from this blog

Using Zabbix Inventory Script for AWX Ansible Tower Inventory

cisco csr1000v ios upgrade or downgrade

Python3 - Basic Knowledge of using Dictionary