Стряпаем скрипт проверки сервера. Логика следующая - проверить хидер ответа и если ответ не получен, или не равен 200 (OK) - оповестить админа.
/usr/local/bin/upcheck
Код: Выделить всё
#!/bin/bash
# Проверяем наличие необходимых аргументов
if [ -z $1 ] || [ -z $2 ]; then
echo "Missing argument"
exit 1
fi
url=$1 # передаем проверяемый url
name=$2 # имя проверяемого сервиса
dump=/tmp/${name}.dump
get="/usr/bin/curl"
send="/usr/sbin/sendmail.exim -t " # Почту у меня шлет релей на exim. Если его нет - воспользуйтесь ssmtp
file="/usr/local/etc/${name}.msg"
tm=`date +%H:%M:%S`
dt=`date +%d.%m.%Y`
rm -f $dump
$get ${url} -D ${dump} -o /dev/null
result="`cat ${dump} | grep HTTP | awk '{print $2}'`"
if [ -z ${result} ]; then # если дамп пуст (не получен ответ от сервера)
sleep 60 # ждем минуту и повторяем проверку дабы исключить случайности
rm -f $dump
$get ${url} -D ${dump} -o /dev/null
recheck="`cat ${dump} | grep HTTP | awk '{print $2}'`"
# если повторная проверка подтверждает опасения - орем благим матом:
if [ -z ${recheck} ]; then
cat > ${file} <<EOF
To: raven@domain.tld
From: checker@domain.tld
Subject: Critical error
Network error!
Could not connect to ${name}.
${dt} - ${tm}
EOF
${send} < ${file} # Пишем на почту
/usr/local/etc/calendarSMS/sendsms Could not connect to ${name} # шлем смс
fi
elif [ ${result} != 200 ]; then # Если соединение успешно, но код http-ответа не равен 200
cat > ${file} <<EOF
To: raven@domain.tld
From: checker@domain.tld
Subject: Alert
${name} is down!
Returned status: ${result}
${dt} - ${tm}
EOF
${send} < ${file}
/usr/local/etc/calendarSMS/sendsms ${name} down - ${result}
fi
# записать все в лог
cat >> /var/log/services.log <<EOF
$dt -$tm , $name , $result
EOF
fi
/usr/local/etc/calendarSMS/sendsms
Код: Выделить всё
#!/bin/sh
PINGRESOURCE=google.com
message=""
case $# in 0)
echo " sendsms [-inet] [-?] [-sync] [сообщ]"
echo " "
echo " -inet позволяет перед отправкой проверить "
echo " доступ к интернету(google.com), "
echo " пока интернет не появится сообщение не отправится"
echo " "
echo " -? эта справка"
echo " -sync перед отправкой синхронизировать время"
echo " сообщ сообщение которое будет отправлено"
exit 3;
;;
esac
for p in $*;
do
case "$p" in -?)
echo " sendsms [-inet] [-?] [-sync] [Сообщение]"
echo " "
echo " -inet позволяет перед отправкой проверить "
echo " доступ к интернету(google.com), "
echo " пока интернет не появится сообщение не отправится"
echo " "
echo " -? эта справка"
echo " -sync перед отправкой синхронезировать время"
echo " сообщ сообщение которое будет отправлено"
exit 0
;;
-inet)
while (! ping -c 3 -w 3 -W 2 ${PINGRESOURCE} >/dev/null 2>&1) do
echo "calendarSMS: Сообщение не отправлено, подключение к интернету не обнаружено!!! "
logger "calendarSMS: Сообщение не отправлено, подключение к интернету не обнаружено!!! "
sleep 10s
done
;;
-sync)
logger "calendarSMS: Synchronizing time"
if (! ntpclient -s -h ntp.mega.kg >/dev/null 2>&1) then
echo "calendarSMS: Не установлен ntpclient время не будет синхронизировано"
logger "calendarSMS: Не установлен ntpclient время не будет синхронизировано"
else
logger "calendarSMS: Synchronizing time"
fi
;;
*)
message="$message $p"
;;
esac
done
logger "calendarSMS: стартуем отправку SMS"
log=`/usr/local/etc/calendarSMS/calendarSMS.py --title "$message"`
echo "calendarSMS: $log"
logger "calendarSMS: $log"
Код: Выделить всё
#!/usr/bin/python
#
# Copyright (C) 2012 vassio@ukr.net.
#
# -*- coding: utf-8 -*-
__author__ = 'vassio'
__version__ = '3.0'
import sys, os, re, urllib, getopt, shlex, codecs, locale,time
from ConfigParser import ConfigParser
from ConfigParser import DuplicateSectionError
from gdata.calendar.service import *
class CalendarSMS:
login=''
password=''
delay=0
maxcount=0
def __init__(self, email, password,delay,maxcount):
""".init"""
try:
self.login=email;
self.password=password;
self.delay=delay;
self.maxcount=maxcount;
except Exception,v:
print(v)
def _InsertEvent(self,calendar='', title='',
content='', where='',starttime=800,endtime=1200,
start_time=None, end_time=None, recurrence_data=None):
"""insert event"""
event = gdata.calendar.CalendarEventEntry()
event.title = atom.Title(text=title)
event.content = atom.Content(text=content)
event.where.append(gdata.calendar.Where(value_string=where))
if recurrence_data is not None:
# Set a recurring event
event.recurrence = gdata.calendar.Recurrence(text=recurrence_data)
else:
if start_time is None:
# Use current time for the start_time and have the event last 1 hour
start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + starttime))
end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z',
time.gmtime(time.time() + endtime))
event.when.append(gdata.calendar.When(start_time=start_time,
end_time=end_time))
print 'Calendar=%s'%(calendar,)
print 'CalendarURL=%s'%('https://www.google.com/calendar/feeds/'+calendar+'/private/full',)
if calendar=='':
new_event = self.cal_client.InsertEvent(event,
'/calendar/feeds/default/private/full')
else:
new_event = self.cal_client.InsertEvent(event,
'https://www.google.com/calendar/feeds/'+calendar+'/private/full')
return new_event
def _InsertSingleEvent(self, title='',
content='', where='',starttime=800,endtime=1200,
start_time=None, end_time=None):
"""Uses the _InsertEvent helper method to insert a single event which
does not have any recurrence syntax specified."""
new_event = self._InsertEvent(title, content, where,starttime,endtime, start_time, end_time,
recurrence_data=None)
print 'New single event inserted: %s' % (new_event.id.text,)
print '\tEvent edit URL: %s' % (new_event.GetEditLink().href,)
print '\tEvent HTML URL: %s' % (new_event.GetHtmlLink().href,)
return new_event
def _AddReminder(self, event, minutes=10):
"""Adds a reminder to the event."""
for a_when in event.when:
if len(a_when.reminder) > 0:
a_when.reminder[0].minutes = minutes
else:
a_when.reminder.append(gdata.calendar.Reminder(minutes=minutes))
for a_when in event.when:
if len(a_when.reminder) > 0:
a_when.reminder[0].method = 'sms'
else:
a_when.reminder.append(gdata.calendar.Reminder(method='sms'))
print 'Adding %d minute reminder to event' % (minutes,)
return self.cal_client.UpdateEvent(event.GetEditLink().href, event)
def _AddExtendedProperty(self, event,
name='http://www.example.com/schemas/2005#mycal.id', value='1234'):
"""Adds an arbitrary name/value pair to the event. """
event.extended_property.append(
gdata.calendar.ExtendedProperty(name=name, value=value))
print 'Adding extended property to event: \'%s\'=\'%s\'' % (name, value,)
return self.cal_client.UpdateEvent(event.GetEditLink().href, event)
def Run(self,calendar='',textmessage='',texttitle='',starttime=800,endtime=1200,remindertime=10):
"""Runs
"""
maxcnt=self.maxcount
cnt=0
while (cnt<maxcnt):
try:
self.cal_client = CalendarService()
self.cal_client.email = self.login
self.cal_client.password = self.password
self.cal_client.source = 'Google-Calendar_SMS-2.2'
self.cal_client.ProgrammaticLogin()
see = self._InsertSingleEvent(calendar,texttitle,'',textmessage,starttime,endtime)
see_u_reminder = self._AddReminder(see, minutes=remindertime)
break
except Exception,e:
print ('Error reminder%d:%s'%(cnt,e))
try:
self.cal_client.DeleteEvent(see.GetEditLink().href)
except Exception,e:
print ('Error Delete Event%d:%s'%(cnt,e))
cnt=cnt+1
time.sleep(self.delay)
def LoadConfig(configFile):
config = ConfigParser()
config.read(os.path.expanduser(configFile))
return config
def GetConfig(config, key, default):
try:
value = config.get('sendsms', key)
except:
value = default
return value
def SetConfig(config, key, value):
try:
config.add_section('sendsms')
config.set('sendsms', key,value)
except DuplicateSectionError:
config.set('sendsms', key,value)
config.set('sendsms', key,value)
def main():
"""Runs the CalendarSMS."""
# parse command line options
try:
opts, args = getopt.getopt(sys.argv[1:], "", ["user=", "pw=", "text=","title=","starttime=","endtime","remindertime=","config=","cal="])
except getopt.error, msg:
print (''' calendarSMS [option] command [command args]
Options:
--user [username] google username
--pw [password] password
--text [text] Event Name
--title [text] Title text
--config [configFile] config file to read
--starttime [second] Time of the beginning of event
(concerning current time)
--endtime [second] Time of the termination of event
(concerning current time)
--calendar ID Calendar <??????????????????@group.calendar.google.com>
--remindertime [minutes] Time of sending of a sms before event
''')
sys.exit(2)
user = ''
pw = ''
title=''
text=''
starttime=0
endtime=0
remindertime=0
cal=''
delay=0
maxcount=0
# Process options
for o, a in opts:
if o == "--user":
user = a
elif o == "--pw":
pw = a
elif o == "--text":
text = unicode(a, locale.getpreferredencoding())
elif o == "--title":
title = unicode(a, locale.getpreferredencoding())
elif o == "--starttime":
starttime = int(a)
elif o == "--endtime":
endtime = int(a)
elif o == "--delay":
delay = int(a)
elif o == "--attempt":
maxcount = int(a)
elif o == "--remindertime":
remindertime = int(a)
elif o == "--cal":
cal = unicode(a, locale.getpreferredencoding())
configFile = '/usr/local/etc/calendarSMS/calendarSMS.config'
for opt, arg in opts:
if (opt == "--config"): configFile = arg
cfg = LoadConfig(configFile)
if (user==''):
user = GetConfig(cfg, 'user', '')
SetConfig(cfg, 'user', user)
if (pw==''):
pw = GetConfig(cfg, 'pw', '')
SetConfig(cfg, 'pw', pw)
if (starttime==0):
starttime = int(GetConfig(cfg, 'StartTime', '180'))
SetConfig(cfg, 'StartTime', starttime)
if (endtime==0):
endtime = int(GetConfig(cfg, 'EndTime', '260'))
SetConfig(cfg, 'EndTime', endtime)
if (remindertime==0):
remindertime = int(GetConfig(cfg, 'ReminderTime', '2'))
SetConfig(cfg, 'ReminderTime', remindertime)
if (delay==0):
delay = int(GetConfig(cfg, 'delay', '2'))
SetConfig(cfg, 'delay', delay)
if (maxcount==0):
maxcount = int(GetConfig(cfg, 'attempt', '10'))
SetConfig(cfg, 'attempt', maxcount)
if (cal==''):
cal = GetConfig(cfg, 'calendar', '')
SetConfig(cfg, 'calendar', cal)
if user == '' or pw == '':
print (''' calendarSMS [option] command [command args]
Options:
--user [username] google username
--pw [password] password
--text [text] Event Name
--title [text] Title text
--config [configFile] config file to read
--starttime [second] Time of the beginning of event
(concerning current time)
--endtime [second] Time of the termination of event
(concerning current time)
--calendar ID Calendar <??????????????????@group.calendar.google.com>
--remindertime [minutes] Time of sending of a sms before event
''')
sys.exit(2)
Calendar = CalendarSMS(user, pw,delay,maxcount)
Calendar.Run(cal,text,title,starttime,endtime,remindertime)
if __name__ == '__main__':
try:
main()
except Exception,e:
print ('error sendsms ',e)
Код: Выделить всё
[sendsms]
user: email пользователя календаря
pw: пароль
starttime: 120
endtime: 180
remindertime: 1
calendar: название календаря
attempt:11
delay:5
Код: Выделить всё
*/5 * * * * /usr/local/bin/upcheck http://domain.tld/page.php resource_name