Monday, April 7, 2014

Bash: disk space alert

There are millions scripts and utilities for that.. Here is my input:
[root@gsm-gateway ~]# cat /usr/local/sbin/diskspace_alert

#!/bin/bash

ALERT=0
MAX_VALUE=$1
for i in `df -h | tr -s ' '| cut -d' ' -f5 | grep -oP "\d{1,3}?(?=%)"`
do
        [ "$i" -ge "$MAX_VALUE" ] && ALERT=$((ALERT+1)) && DF_OUTPUT=$(df -h)
done

[ "$ALERT" -gt 0 ] && /usr/local/sbin/php_mailer "The disk space is nearly full" "$DF_OUTPUT"


Replace /usr/local/sbin/php_mailer to your favorite Linux mailer

add to cron:

* */1 * * * /usr/local/sbin/diskspace_alert 80

where 80 - is the max percentage value

Wednesday, April 2, 2014

Sending emails via gmail with php

This script developed to send notifications (as well html and attachment)  to server admin through gmail account:

#!/usr/bin/php
<?php

/*

Please make sure, you have installed following pear modules:

pear install Mail
pear install Net_SMTP
pear install Mail_mime
pear install Mail_mimeDecode


IMPORTANT: Works only with utf-8 charset!!!

*/

$mailru_user = "YOUR_USER@gmail.com";
$mailru_passwd = "YOUR_PASS";
$to = '<TO_SERVER_ADMIN@gmail.com>';

require_once "Mail.php";
require_once('Mail/mime.php');

if(empty($argv[1]))exit("USAGE: $argv[0] 'Hello, how are you?' 'some text' '<h1>some html text</h1>' '/tmp/attachment.txt'");



function mail_via_gmail($subject,$text,$html,$file){
    global $mailru_user;
    $from = '<'.$mailru_user.'>';
    global $mailru_passwd;
    global $to;
    $crlf = "\r\n";
    if( empty($to) ){
        echo 'Please specify $to parameter';
        exit();
    }

    if( empty( $subject ) ) $subject = '';
    if( empty( $text ) ) $text = '';
    if( empty( $html ) ) $html = '';
    if( empty( $file ) ) $file = '';

    $headers = array(
        'From' => $from,
        'To' => $to,
        'Subject' => $subject,
        'Content-Type'  => 'text/html; charset=UTF-8'
    );


    $mime_params = array(
        'text_encoding' => '7bit',
        'text_charset'  => 'UTF-8',
        'html_charset'  => 'UTF-8',
        'head_charset'  => 'UTF-8'
    );

    $mime = new Mail_mime($crlf);

    $mime->setTXTBody($text);
    $mime->setHTMLBody($html);
    $mime->addAttachment($file,'application/octet-stream');

    $body = $mime->get($mime_params);
    $headers = $mime->headers($headers);

    $smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => $mailru_user,
        'password' => $mailru_passwd
    ));

    $mail = $smtp->send($to, $headers, $body);

    if (PEAR::isError($mail)) {
        echo('<p>' . $mail->getMessage() . '</p>');
    } else {
        echo("Message successfully sent!\n");
    }
}

@mail_via_gmail($argv[1],$argv[2],$argv[3],$argv[4]);

?>