Thursday 18 April 2019

Mount checker with email capability

This is done in 3 scripts:


1st Script - the init service:

Mount the directory:

mount -t cifs //192.168.02.02/somedirectory /srv/somedirectory -o vers=3.0,credentials=/root/creds

#! /bin/sh

### BEGIN INIT INFO
# Provides:          cifchecker
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Simple script to start a program at boot
# Description:       A simple script which will start / stop a program a boot / shutdown.
### END INIT INFO

# If you want a command to always run, put it here

# Carry out specific functions when asked to by the system
case "$1" in
  start)
    echo "Starting cifchecker"
    # run application you want to start
    /usr/local/bin/sendemail.sh &
    ;;
  stop)
    echo "Stopping cifchecker"
    # kill application you want to stop
    dead=$(ps -o pgid,cmd -U root | grep -v grep | grep sendemail | awk '{print $1}')
    kill -- -$dead
    ;;
  *)
    echo "Usage: /etc/init.d/cifchecker {start|stop}"
    exit 1
    ;;
esac

exit 0

Place this in /etc/init.d/ directory and run:

chmod 755 cifchecker
update-rc.d cifchecker defaults

2nd Script: This keeps an eye on the Partition and calls email script if needed:

#!/usr/bin/env bash

while true;
do
 /bin/findmnt /srv/directoryname
 status=$(echo $?)
 sleep 1m
 if [ $status -ne 0 ]; then
  /usr/local/bin/mailer.py 'Mount partition has been lost'
  while true;
  do
   /bin/findmnt /srv/directoryname
   statusafter=$(echo $?)
   sleep 1m
   if [ $statusafter -ne 0 ]; then
    continue
   else
    /usr/local/bin/mailer.py 'Mount partition restored'
    break
   fi
  done
 else
  continue
 fi
done

3rd Script: This sends the email as per directive:

#!/usr/bin/env python3

import os, fnmatch, subprocess,datetime,time,smtplib,sys
from email.message import EmailMessage

icomm1 = sys.argv[1]
msg = EmailMessage()
msg.set_content(icomm1)
msg['Subject'] = 'cifs mount issue'
msg['From'] = 'naveed@nasheikh.com'
msg['To'] = 'adrian@nasheikh.com','tamy@nasheikh.com'
s = smtplib.SMTP('smtp.stats.govt.nz')
s.send_message(msg)
s.quit()

Good practice is to place both executable scripts in /usr/local/bin

-------------------------------------------------------------Fi----------------------------------------------------------

No comments:

Post a Comment