Setting SMS notifications in zabbix

  • Tutorial
The issue of SMS notifications in zabbix was already covered on Habré and the problem was solved using SMS gateways. Also mentioned about Sending SMS using Delphi . I want to tell how to configure SMS notifications using a USB modem.
So, what do we have:

1) a fairly extensive IT infrastructure

2) a Zabbix 2.0.3 monitoring system (the current version at the time of writing) operating under Fedora 14 x64

3) a ZTE MF100 3G USB modem from the national Ukrainian operator Kyivstar.



4) Prepaid SIM card that came with the modem.

Also, a corporate 3G SIM was purchased for the modem, but it will not work, because it is impossible to call and send SMS from 3G cards, and this does not suit us. So, I put a small amount on the card “for experiments”, stuck the modem into USB and .

Installation of the necessary


First of all, I registered a card in My Kyivstar system . It’s convenient to look through the rest of the money on the modem’s account and order extra. services. Let me remind you that I carry out all the activities in Fedora. For other Linux, the commands may differ, but I’m thinking of finding out which of the replacements is easy for you. I also will not consider the option of installing the necessary source, although this can also be done. I limit myself to installing existing standard packages:
sudo yum install usb_modeswitch # для поддержки USB-модемов Huawei, T-Mobile, Vodafone, Option, ZTE, Novatel
sudo yum install minicom        # для терминального подключения к модему по /dev/ttyUSB*
sudo yum install smstools  # собстветвенно пакет для работы с смс. 
Now check if the modem appeared
ls -l /dev/ttyUSB*
The result should look something like this
crw-rw----. 1 root dialout 188, 0 Oct 22 12:05 /dev/ttyUSB0
crw-rw----. 1 root dialout 188, 1 Oct 22 15:56 /dev/ttyUSB1
crw-rw----. 1 root dialout 188, 2 Oct 22 12:05 /dev/ttyUSB2
The modem has created 3 virtual USB ports. In my case, ttyUSB1 and ttyUSB2 are available for AT commands. If the modem has created 5 or more virtual ports, then their number can be reduced to 3x. To do this, disable the cdrom and flash-drive modes in it. Turning off the commando is the AT + ZCDRUN = E , the inclusion of the AT + ZCDRUN the F = . If we want to disable only cd-rom, then AT + ZCDRUN = 8 . If we want to turn it back on - AT + ZCDRUN = 9. I start the terminal
minicom -D /dev/ttyUSB1
I see a greeting

Welcome to minicom 2.5
OPTIONS: I18n
Compiled on Feb 24 2011, 11:25:55.
Port /dev/ttyUSB1
Press CTRL-A Z for help on special keys
AT S7=45 S0=0 L1 V1 X4 &c1 E1 Q0
OK
turn off the CD-ROM
>AT+ZCDRUN=8
Close autorun state result(0:FAIL 1:SUCCESS):1
OK
In general, there are quite a lot of AT commands before, in the days of telephone modems, knowledge was mandatory for a self-respecting admin. Now everything has changed and you can remember the forgotten commands using Google. For example, here’s a good help article. Let's try to talk to the modem. Let's see the modem’s mode of operation
>AT+ZSNT?
+ZSNT: 1,0,0
OK
in my case - = 1,0,0 - Automatic selection of only GSM network. Since I use a regular rather than a 3G SIM card, this mode completely suits me. The following operating mode options also exist:
AT+ZSNT=0,0,0 (Авто) - по умолчанию
AT+ZSNT=0,0,1 Автоматический выбор сети: GSM+WCDMA, предпочтение GSM
AT+ZSNT=0,0,2 Автоматический выбор сети: GSM+WCDMA, предпочтение WCDMA
AT+ZSNT=1,0,0 Автоматический выбор сети: только GSM
AT+ZSNT=2,0,0 Автоматический выбор сети: только WCDMA
AT+ZSNT=0,1,0 Ручной выбор сети: GSM+WCDMA
AT+ZSNT=1,1,0 Ручной выбор сети: только GSM
AT+ZSNT=2,1,0 Ручной выбор сети: только WCDMA
Check if pin protection is set.
>AT+CPIN?
 +CPIN: SIM PIN
 OK
disable PIN
>AT+CLCK="SC",0,"1111"
enable PIN
>AT+CLCK="SC",1,"1111"
If it is turned on, then to continue working we need to enter it
>AT+CPIN=”1234″
 OK
check again
>AT+CPIN?
 +CPIN: READY
 OK
Now the pin code is accepted. Let's see the signal level
>AT+CSQ
+CSQ: 21,99
OK
get the IMEI version of the module
>AT+GSN
359518034903581
OK
Let's see the type of network registration
>AT+CREG?
+CREG: 0,1
OK
0 means that there is no message about registration changes in the network1 - successfully registered in the networkWe will see information about the operator
>AT+COPS?
+COPS: 0,0,"Kyivstar",0
OK
The first 0 means automatic network selection, a long test format for the name (second 0), and the operator’s name itself - Kyivstar. Let's check whether we have installed and which SMS sending center (Service Center Address)
AT+CSCA?
+CSCA: "+380672021111",145
OK
This is the correct number for Kyivstar. Now let's try to send a message. Before sending a message, you need to set the message format. This is done with the command AT + CMGF = x . where x is the message format, 0-1.0, is the PDU mode, command code control. Message output in HEX code. The default mode is 1, - text mode. Commands are text. Message output in text form. In the first mode, messages will be issued in the form of hex codes ascii or unicode. This is a very inconvenient mode. Sending SMS is done with the command AT + CMGS = "ХХХХХХХХХХХ"where ХХХХХХХХХХХХ is the subscriber number. Sending SMS depends on the format of the message. After entering the command, it displays the ">" prompt, after which you can enter the message text. Ends with an ESC or Ctrl-Z character. We will send a message using text mode and preliminarily setting SCA:
AT+CMGF=1
OK
AT+CSCA= "+380672021111"
OK
AT+CMGS="+38067xxxxxxx"
> test message
>
+CMGS: 110
OK
SMS has successfully arrived. You can send SMS by writing it in memory:
AT+CMGW="91234567"Sending text messages is easy.
AT+CMSS=3
When working with AT commands, things do not always go smoothly. Sometimes commands are executed with errors, returning a three-digit error code. Here is a list of the main error codes:
Error code 	Meaning 
0-127 	GSM 04.11 Annex E-2 values 
128-255 	GSM 03.40 section 9.2.3.22 values 
300 	Phone failure 
301 	SMS service of phone reserved 
302 	Operation not allowed 
303 	Operation not supported 
304 	Invalid PDU mode parameter 
305 	Invalid text mode parameter 
310 	SIM not inserted 
311 	SIM PIN necessary 
312 	PH-SIM PIN necessary 
313 	SIM failure 
314 	SIM busy 
315 	SIM wrong 
320 	Memory failure 
321 	Invalid memory index 
322 	Memory full 
330 	SMSC (message service center) address unknown 
331 	No network service 
332 	Network timeout 
500 	Unknown error 
512 	Manufacturer specific

Configure smstools


Now configure SMS Tools. Edit the config /etc/smsd.comf. I bring a ready-made config with comments:
#используемые устройства, если несколько — пишем через запятую
devices = GSM1
#папки для сохранения смс
incoming=/var/spool/sms/incoming
outgoing=/var/spool/sms/outgoing
checked=/var/spool/sms/checked
sent=/var/spool/sms/sent
# лог, если не указан — пишется в syslog, если = 1, пишет в stdout
logfile = /var/log/smsd/smsd.log
#уровень логирования
loglevel = 5 #debug = 7
user = sms
#включаем "умный" лог
smart_logging = yes
#скрипт, выполяющийся перед отправкой смс для автоматической конвертации кириллических сообщений в "правильную" кодировку. о нём подробнее ниже
checkhandler = /etc/smsd/check.sh
#скрипт, выполняющийся после отправки смс и создающий лог отправленного. о нём подробнее ниже
eventhandler = /etc/smsd/trsms.sh
[GSM1]
#используемое устройство
device = /dev/ttyUSB1
#пин-код
pin = 1111
#SCA
smsc = 380672021111
You can read more about all the config parameters on the smstool official website.

Script trsms.sh


Now create the script /etc/smsd/trsms.sh, which will write a log of sent SMS. Moreover, all Cyrillic messages will fall into it in readable encoding. Do not forget to give the right to execute the script to the smstool user and to write to the /var/log/smsd/sms.log log
chown  smstools:smstools /etc/smsd/trsms.sh
chmod gu+x /etc/smsd/trsms.sh
chmod gu+w /var/log/smsd/sms.log
The script itself:
#!/bin/bash
status="$1"
file="$2"
touch /etc/smsd/ok
case "$1" in
 SENT)
      FILE=`mktemp /tmp/smsd_XXXXXX`
      head -5 $file | grep -e "^To: " -e "Alphabet: " -e "^Sent: " >> /var/log/smsd/sms.log
      if grep "Alphabet: Unicode" $file >/dev/null; then
         tail -n +6  $file | iconv -f UCS-2BE -t UTF-8  >> /var/log/smsd/sms.log
      else
        tail -n +5 $file >> /var/log/smsd/sms.log
      fi
        echo >> /var/log/smsd/sms.log
        echo "========================================" >> /var/log/smsd/sms.log
        echo >> /var/log/smsd/sms.log
        ;;
esac
Example log part:
========================================
To: 38067XXXXXXX
Alphabet: Unicode
Sent: 12-10-23 21:07:29
test message
========================================
To: 38093XXXXXXX
Alphabet: Unicode
Sent: 12-10-19 12:16:28
лог пишет теперь и на русском
========================================

Script check.sh


SMSTools can handle events using external programs. Our script will help to send Russian SMS in the correct encoding checking messages before sending (unicode2sms was taken as a prototype from the standard script package, which can be found in / usr / bin. Similarly, do not forget to give permission to execute script to smstool user
chown  smstools:smstools /etc/smsd/check.sh
chmod gu+x /etc/smsd/check.sh
The script itself:
#!/bin/bash
# checkhandler for SMS Tools 3
# autoconverts cyrillic messages to UCS-2BE
# add checkhandler=/path/to/ucsautoconvert into global part of smsd.conf
# written by lexy (lexy@mrlexy.ru), 2008
FILE=`mktemp /tmp/smsd_XXXXXX`
if [ ! `grep '[А-Яа-я]' $1 > /dev/null` -o `grep 'Alphabet:\s*U' $1 > /dev/null` ]
    then exit 0
fi
cat $1 | awk '{if(NF==0) {s=1} if(s==0 && NF>0 && $0!~/Alphabet:[ \t]*U/){print}}' > $FILE
echo Alphabet: Unicode >> $FILE
cat $1 | awk '{if(NF==0) {s=1} if(s==1){print}}' | iconv -t UCS-2BE >> $FILE
mv $FILE $1
chmod 664 $1
now everything is ready to launch.
>service smsd start
Starting smsd:                                             [  OK  ]
check if it started
> ps ax | grep smsd
 1345 ?        Ss     0:00 /usr/sbin/smsd
 1347 ?        S      0:00 /usr/sbin/smsd
 2322 pts/2    S+     0:00 grep --color=auto smsd
try to send a message. the subscriber number is indicated in the international format, but without the “+” sign
smssend "38067XXXXXXX" "test message"
--
Text: test message
To: 38067XXXXXXX
We look at the log.
> tail  /var/log/smsd/smsd.log
added lines
2012-10-23 21:07:08,5, GSM1: SMS sent, Message_id: 112, To: 38067XXXXXXX, sending time 7 sec.
2012-10-23 21:07:21,5, smsd: Moved file /var/spool/sms/outgoing/send_NpoTqX to /var/spool/sms/checked
check the sent SMS:
>cat /var/spool/sms/sent/send_NpoTqX
To: 38067XXXXXXX
Alphabet: Unicode
Modem: GSM1
Sent: 12-10-23 21:07:29
IMSI: 255030837719869
test message

Zabbix setup


We’ll write a script that Zabbix will execute to send sms. In Zabbix, such scripts lie in the directory defined in the AlertScriptsPath variable .
cat /usr/local/etc/zabbix_server.conf | grep AlertScriptsPath
### Option: AlertScriptsPath
 AlertScriptsPath=/home/zabbix/bin/
I call the script itself sms_send.sh and it consists of almost one line:
#!/bin/bash
to=$1
subject="$2"
body="$3"
smssend $to  "$subject"
Further configuration is done through the web interface. First, go to Administration -> Notification Methods (Administration Media types->) and create a new notification method (Media types). The name of the script should be the same as the name of the script file in the AlertScriptsPath directory.

Next in the user settings (Administration -> Users or Administration -> Users) add the method of notifications (Media):

After that, in the settings for Actions (Actions) it will be possible to use this Media :



Tariffs


The standard price of one SMS = 0.5 UAH. That with a large number of SMS can result in a pretty penny. What does the operator offer to reduce costs?

Option One - Prepaid

There are two options:
  1. “Package 30 SMS” with a monthly fee of 4 UAH per week. It turns out that the price of 1 SMS = 13.33 kopecks.
  2. “60 SMS package” with a monthly fee of 6 UAH per week. It turns out that the price of 1 sms = 10 kopecks.
The price is good. But there are also disadvantages:
  • In both cases, unused SMS “burn out” at the end of the week.
  • You need to regularly log in to My Kyivstar and re-order the service, otherwise you can remain without notice at the most important moment.


option two - contract
There are three options:
  1. “SMS package -50%” with a monthly fee of 3 UAH per month. The package includes 500 sms at a discount. It turns out that the price of 1 SMS = 25 kopecks.
  2. «Пакет SMS -70%» с абон.платой в 7 грн в месяц. В пакет входит 500 смс со скидкой. Получается, что цена 1 смс =15 коп.
  3. «Пакет 1000 SMS» с абон.платой в 120 грн в месяц. В пакет входит 1000 бесплатных смс. Получается, что цена 1 смс =12 коп.
It turns out more expensive than in pre-packs, but then you do not need to activate it weekly. Once did - and forgot.
By the way, prices are competitive. For example, the internet service smscentre.kiev.ua for our organization offered a price of 15 kopecks. for one SMS with the number of SMS per month 1-25000 without a subscriber. boards and with free activation of the package. But when using a modem, we get one indisputable advantage - independence from the Internet. After all, it’s not mass SMS that interests you, but notifications from Zabbix. And when using the Internet SMS distribution services, I risk NOT receiving an important SMS in the case of, for example, a prolonged blackout in the office or an accident at the provider. Which package to choose is up to you.
You can learn more about SMS packages at: for the contractand for prepaid

PlaySMS Setup


Installing this application is optional. The application is necessary for the mass mailing of SMS messages that are stored in the mysql database. The packages httpd, mysql, php, php-pear, php-mysql, php-cli, phpmyadmin are needed to work. But I already installed all these packages for Zabbix to work. Create a new user and directory for PlaySMS. Download the latest version of PlaySMS and create a database in mysql:
adduser playsms
mkdir -p /var/www/playsms
mkdir -p /var/spool/playsms
mkdir -p /var/log/playsms
chown -R apache /var/www/playsms
chown -R apache /var/spool/playsms
chown -R apache /var/log/playsms
chmod -a -G smstools playsms
wget http://downloads.sourceforge.net/project/playsms/playsms/Version%200.9.7.1/playsms-0.9.7.1.tar.gz
tar -zxvf playsms-0.9.7.1.tar.gz -C /usr/local/src
cd /usr/local/src/playsms-0.9.7.1/web/
cp -rR * /var/www/playsms
cp playsmsd* sendsmsd* /usr/local/bin/  
chown -R apache /var/www/playsms
mysqladmin -u root -p create playsms
We import into the created database:
mysql -u root -p playsms < /usr/local/src/playsms-0.9.7.1/db/playsms.sql
Copy the config, after editing the password in it, the password for connecting to the database (and login, if you do not have root)
cp /var/www/playsms/config-dist.php /var/www/playsms/config.php
 vi /var/www/playsms/config.php
$core_config['db']['pass'] = 'ваш пароль';          // database password
Set up the program to start automatically:
cd /usr/local/src/playsms-0.9.7.1/bin
 cp playsmsd playsmsd.php playsmsd_start /usr/local/bin/
 cp playsms /etc/default/
In /etc/rc.d/rc.local, add the line - / usr / local / bin / playsmsd_start. The PlaySMS control panel is available at htpp: //ip.address.your.server/playsms. Login admin \ admin.
Check that the correct path is specified in / etc / default / playsms
PLAYSMS_PATH=/var/www/html/playsms  


useful links


Links that will prompt you to further improve the idea of ​​sending SMS:
An article with a script-gateway E-mail-> SMS
A detailed manual on AT commands and sending SMS
Description of various AT commands
SMS forwarding using SMSTools
Description of SMS message file headers

UPD: to view the balance on the account and the number of promotional SMS, you must install the gsm-ussd package. The format of the command and the result are as follows:
>gsm-ussd -m /dev/ttyUSB2 '*115#'
Bonusy 55.0 SMS na nomery po Ukraini (dijsni do 2012-11-06 23:59:59). Zamovlennia Paketu SMS za tel. 477*030*
>gsm-ussd -m /dev/ttyUSB2 '*111#'
Na rahunku: 17.14 grn. Nomer die do 24-10-2013. Bonusy: 0 grn (dijsni do 14-10-2022); 104810496 bytes

Also popular now: