Quantcast
Channel: Syed Jahanzaib – Personal Blog to Share Knowledge !
Viewing all 408 articles
Browse latest View live

Backup your Backup on CLOUD !

$
0
0

cloudbackup

If you are using command base server operating system with text support only, example ‘Ubuntu Server Edition‘, && if its hosting important application like radius billing, then its best practice to have several layers of backup. One good strategy for multi layer backup should be as following.

  1. Local Backup
  2. USB Backup
  3. CLOUD backup either on remote FTP / Google Drive / Dropbox.
  4. Offline Backup

AND ABOVE ALL, DON’T FORGET, CLUSTER/REPLICATION IS YOUR FRIEND , IT HELPS WHEN YOU ARE IN REAL TROUBLE !  ;) ~ trust me, I am telling your from my personnel experiences   z@!b

https://aacable.wordpress.com/2015/06/26/radius-redundancy-by-using-mysql-master-master-replication/

In this example I am using DROPBOX which is very convenient cloud base backup solution (Free up-to 5 GB, suitable for small size network) and can be installed on your windows / Linux / android as well. So I have Dropbox tool on my windows as well as Linux too. So I just add/remove files at one end, the changes replicate to other end automatically.


TWO STEPS INSTALLATION


1- Create your account at Dropbox, its free

First login to https://www.dropbox.com and register your account.


2- Howto install DROPBOX on UBUNTU

Quick Notes:

32-bit:

cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86" | tar xzf -

64-bit:

cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86_64" | tar xzf -

Now download the DROPBOX control script

mkdir /temp
cd /temp
wget https://www.dropbox.com/download?dl=packages/dropbox.py
mv download\?dl\=packages%2Fdropbox.py dropbox.py

Now start Dropbox by

/temp/dropbox.py start

It may show you a URL, copy it, and paste in your browser, your Dropbox account will be activated instantly.


  • Now test if Dropbox is started
/temp/dropbox.py status

It should be showing something like

dropbox-status

Now you can upload your files in

/root/Dropbox

Try to make any test file in this folder, and after few moments, check on Dropbox by login to http://www.dropbox.com

results

 

This is very useful if you want to automate your backup process and have multi layer backup system. You can schedule any cron script that can keep checking for Dropbox status and so on.

Regard's
Syed Jahanzaib !

 

 

 


Filed under: Linux Related

Radius Manager

$
0
0

After upgrade radius manager, you may see following error when you click on Home / Settings

Unknown column 'pm_sagepay' in 'field list'

123

It is caused by in-correct table name pm_netcash where as RM searches for `pm_ sagepay`. Issue following command to solve it.

Login to mysql, and change db to radius.

mysql -uroot -pSQLPASS
use radius;
ALTER TABLE `rm_settings`  CHANGE `pm_netcash` `pm_sagepay` TINYINT( 1 ) NOT NULL ;"

Make sure to change mysql password. This will alter the in.correct table name to correct one and then you will be able to access the menu correctly.

Regard’s
Syed Jahanzaib

 


Filed under: Radius Manager

Sending ‘Password Change’ Alert to users via SMS/Email through KANNEL SMS GATEWAY in Radius Manager

$
0
0

1234

Screenshot_2016-05-11-14-44-07


Following is a quick dirty method on how you can generate SMS / EMAIL alert when admin changes any user password [as requested by an OP]. and I think its a good idea so that users must be informed about there account password security.

In this guide I have used Radius Manager 4.1.5 along with KANNEL on same machine. Serial Modem is being used along with local mobile SIM for sending SMS.

You need to perform few steps. Proceed with caution, as alerting mysql DB incorrectly can result in partial or total database wipe out or can led to corruption of DB. Make sure you take full DB backup before proceeding. Better to test it on Virtual lab.

you need to make two .sql file

1- triggers.sql
[It will make a new trigger that will be executed when rm_users table will be modified. It will match new password field with the old.field and add then log the changed with username and other details in below table.

2-rm_userpasschangehistory.sql
[It will create new DB which will store password change datetime, username, first last name and mobile]


1- TRIGGERS.SQL

Ok lets first make triggers.sql file, open text editor and paste the data.

mkdir /temp
nano /temp/triggers.sql

Paste the following data in this file.

-- MySQL dump 10.13 Distrib 5.5.46, for debian-linux-gnu (i686)
-- Host: localhost Database: radius
-- ------------------------------------------------------
-- Server version 5.5.46-0ubuntu0.12.04.2-log

DELIMITER ;;

FOR EACH ROW BEGIN
IF NEW.password <> OLD.password THEN
INSERT INTO rm_userpasschangehistory (datetime, username, firstname, lastname, mobile) VALUES (NOW(), new.username, new.firstname, new.lastname, new.mobile);
END IF;
END */;;
DELIMITER ;

-- Dumping routines for database 'radius'
--

Save and exit.


2- rm_userpasschangehistory

Now let’s make rm_userpasschangehistory.sql , open text editor and paste the data.

mkdir /temp
nano /temp/rm_userpasschangehistory.sql

Paste the following data in this file.

-- Table structure for table rm_userpasschangehistory`
--

DROP TABLE IF EXISTS rm_userpasschangehistory`;
CREATE TABLE `rm_userpasschangehistory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`datetime` datetime NOT NULL,
`username` varchar(64) NOT NULL,
`firstname` varchar(64) NOT NULL,
`lastname` varchar(64) NOT NULL,
`mobile` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
ALTER TABLE `rm_users` ADD `ModifiedTime` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
--
-- Dumping data for table rm_userpasschangehistory

Save and exit.


IMPORTING .sql files intro RADIUS DB.

Now we can import above created .sql files into radius DB. Use below commands

mysql -uroot -pSQLPASS radius < triggers.sql

mysql -uroot -pSQLPASS radius < rm_userpasschangehistory.sql

TEST DRIVER ….

Ok now try to change any user password from radius admin panel. Once updated, check the new table cahnges by following command (I used time interval to fetch accounts changed in last 5 minutes, you can modify it as per your requirements

.. and you may see result as below …


mysql -uroot -pSQLPASS --skip-column-names -e "use radius; select * from rm_userpasschangehistory WHERE datetime >= NOW() - INTERVAL 5 MINUTE;"
+---+---------------------+------+------+-----------+-------------+
| 5 | 2016-05-11 13:46:55 | zaib | syed | jahanzaib | 03333021909 |
+---+---------------------+------+------+-----------+-------------+

~ ALHAMDOLILLAH ~


SCRIPT to fetch data via SCHEDULED CRON  job to send SMS/EMAIL.

You can use following script in cron scheduler.


#!/bin/sh
# passchange.sh
# Bash script which will run after every 5 minutes and will fetch info from mysqltable
# and will send SMS/Email alert for password change event.
# Created by SYED JAHANZAIB
# aacable@hotmail.com
# https://aacable.wordpress.com

SLQPASS="MYSQL_ROOT_PASSWORD"
TMPUSRINFO=/tmp/userpass.txt
mysql -uroot -p$SQLPASS --skip-column-names -e "use radius; select * from rm_userpasschangehistory WHERE datetime >= NOW() - INTERVAL 5 MINUTE;" >> $TMPUSRINFO

# KANNEL DETAILS
KHOST="127.0.0.1:13013"
KID="kannel"
KPASS="KANNEL_PASSWORD"

# Apply Count Loop Formula while deleting first line which have junk text
num=0
cat $TMPUSRINFO | while read users
do
num=$[$num+1]
username=`echo $users | awk '{print $4}'`
firstname=`echo $users | awk '{print $5}'`
lastname=`echo $users | awk '{print $6}'`
mobile=`echo $users | awk '{print $7}'`
date=`echo $users | awk '{print $2,$3}'`
# Print Info on screen
echo "Dear $firstname $lastname,
Password for your internet account ID=$username been successfully changed on $date.
Regard's

XYZ ISP SERVICES (PVT) LTD"

# Store Info for sending SMS in /tmp folder where we will call kannel to send customized SMS
echo "Dear $firstname $lastname,
Password for your internet account ID=$username been successfully changed on $date.

Regard's
XYZ ISP SERVICES (PVT) LTD" > /tmp/$username.passchange.sms

curl "http://$KHOST/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$mobile" -G --data-urlencode text@/tmp/$username.passchange.sms
# If you send lot of SMS via local mobile SIM, then make sure you give enough delay so that your SIM may not get blocked by BULK SMS monitor by TELCOM authority like PTA.
#sleep 15

done

# once done, we should delete the .sms files to clear the garbage

rm -fr /tmp/*.sms

sms done


CRON CODE for 5 minute schedule.

crontab -e

# Run renewal check script Script after every 5 minutes
*/5 * * * * /temp/passchange.sh

Possibilities are endless…..

Regard’s
Syed Jahanzaib


Filed under: Radius Manager

An Example of Sending SMS Alert for Daily Quota Users

$
0
0

 

Screenshot_2016-05-19-17-04-06

alert1

 

Scenario:

We have daily quota users as described here.

https://aacable.wordpress.com/2012/11/20/mikrotik-radius-manager-quota-base-service/

OP want to send alert when daily quota users crosses 70% of there allowed daily traffic quota. Since RM sends alert for  TOTAL traffic only , not for daily, therefore I made following workaround.

The purpose of this script is to send SMS/Email alert to user who have consumed 70% of there daily allowed download/upload quota [value must be set in combined unit]. Once the user will use 70% of his allowed traffic, an SMS alert will be sent using local KANNEL SMS gateway and it will update flag in rm_users table which will prevent repetitive sms. only one sms alert will be sent in one day. once the date will be changed, the script will update the flags to 0, so that it will send sms alert again once the quota crosses the line again.

It may be scheduled to run after every 10 minutes or whatever the suitable interval according to your billing load.

Disclaimer:

Following is an LAB test version. It will generate many queries and may put burden on heavily production server. So make sure if you are using it, trim it and remove junk data before deploying in production.

Plus I know that its not an elegant way to perform this task. If it could be done via php/rm itself that would be best, but since RM is a protected system and we cannot modify it, therefore i was forced to take the ‘dirty workaround’ route to achieve the task. in production i will trim it to make sure it put minimum payload on the server. It took almost 3 days to make it work.

Copyright:

No part of this post is copied from any where. Its all made by myself. You are free to use/modify/share it as you like.

~ Syed Jahanzaib ~


#!/bin/bash
#set -x
TODAY=$(date +"%Y-%m-%d")
TODAYTIME=$(date +"%Y-%m-%d %T")
SQLUSER="root"
SQLPASS="zaib1234"
TMPUSERINFO="/tmp/username.txt"
QUOTAPERCLIMIT="70"
COMPANY="SYED JAHANZAIB"

# Kannel SMS Gateway Details
KHOST="your_kannel_host"
KID="kannel"
KPASS="kannel_password"

> /tmp/username.txt
> /tmp/tempuser.txt

# Create QMAIL table if not exists
QMAILCHECK=`mysql -u$SQLUSER -p$SQLPASS -e " SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'radius' AND TABLE_NAME = 'rm_users' AND COLUMN_NAME = 'qmail';"`
if [ ! -z "$QMAILCHECK" ];
then
echo "Step-1 Check QMAIL Column in rm_users ...
QMAIL Column Found OK, proceeding further ..."
else
echo "QMAIL Column does NOT exists in rm_users table. it is required to prevent repeating email being sent to users, creating one NOW ..."
mysql -u$SQLUSER -p$SQLPASS "use radius; ALTER TABLE rm_users ADD qmail TINYINT(1) NOT NULL;"
mysql -u$SQLUSER -p$SQLPASS -e "use radius; ALTER TABLE rm_users ADD qmailtime DATETIME NOT NULL;"
fi

# Qurty Active Users list and store in it file
mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SQL_CALC_FOUND_ROWS username, firstname, lastname, address, city, zip, country, state, phone, mobile,
email, company, taxid, srvid, downlimit, uplimit, comblimit, expiration, uptimelimit, credits, comment,
enableuser, staticipcpe, staticipcm, ipmodecpe, ipmodecm, srvname, limitdl, limitul, limitcomb, limitexpiration,
limituptime, createdon, verifycode, verified, selfreg, acctype, maccm, LEFT(lastlogoff, 10)
, IF (limitdl = 1, downlimit - COALESCE((SELECT SUM(acctoutputoctets) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(dlbytes), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0),

IF (limitul = 1, uplimit - COALESCE((SELECT SUM(acctinputoctets) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(ulbytes), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0),

IF (limitcomb =1, comblimit - COALESCE((SELECT SUM(acctinputoctets + acctoutputoctets) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(ulbytes + dlbytes), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0),

IF (limituptime = 1, uptimelimit - COALESCE((SELECT SUM(acctsessiontime) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(acctsessiontime), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0)

FROM
(
SELECT username, firstname, lastname, address, city, zip, country, state, phone, mobile, email, company,
taxid, rm_users.srvid, rm_users.downlimit, rm_users.uplimit, rm_users.comblimit, rm_users.expiration,
rm_users.uptimelimit, credits, comment, enableuser, staticipcpe, staticipcm, ipmodecpe, ipmodecm, srvname, limitdl,
limitul, limitcomb, limitexpiration, limituptime, createdon, verifycode, verified, selfreg, acctype, maccm,
mac, groupid, contractid, contractvalid, rm_users.owner, srvtype, lastlogoff
FROM rm_users
JOIN rm_services USING (srvid)

ORDER BY username ASC
) AS tmp
WHERE 1
AND (tmp.acctype = '0' OR tmp.acctype = '2' OR tmp.acctype = '6' )
AND tmp.enableuser = 1 AND
(limitdl = 0 OR IF (limitdl =1, downlimit -
(SELECT COALESCE(SUM(acctoutputoctets), 0)
FROM radacct WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(dlbytes), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) > 0)
AND
(limitul = 0 OR IF (limitul =1, uplimit -
(SELECT COALESCE(SUM(acctinputoctets), 0)
FROM radacct WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(ulbytes ), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) > 0)
AND
(limitcomb = 0 OR IF (limitcomb =1, comblimit -
(SELECT COALESCE(SUM(acctinputoctets + acctoutputoctets), 0)
FROM radacct WHERE radacct.username = tmp.username) +
(SELECT COALESCE(SUM(ulbytes + dlbytes), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) > 0)
AND
(limituptime = 0 OR IF (limituptime=1, uptimelimit -
(SELECT COALESCE(SUM(acctsessiontime), 0)
FROM radacct WHERE radacct.username = tmp.username) - (SELECT COALESCE(SUM(acctsessiontime), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) > 0)
AND
(limitexpiration = 0 OR IF (limitexpiration=1, UNIX_TIMESTAMP(expiration) - UNIX_TIMESTAMP(NOW()), 1) > 0);" | awk '{print $1}' |awk 'NR > 1 { print }' > /tmp/tempuser.txt

# REMOVE user which donot have any COMBLIMIT
num=0
cat /tmp/tempuser.txt | while read users
do
num=$[$num+1]
USERID=`echo $users | awk '{print $1}'`
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$USERID';" |awk 'FNR == 2 {print $1}'`
COMBLIMITCHECK=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT limitcomb FROM rm_services WHERE srvid = '$SRVID';" |awk 'FNR == 2 {print $1}'`
if [[ $COMBLIMITCHECK -eq "1" ]]; then
echo "" > /dev/null
#echo "$USERID have Quota limit = 1 , moving to correct file"
echo "$USERID" >> /tmp/username.txt
else
echo "" > /dev/null
#sed -i 's/\<$USERID\>//g' /tmp/username.txt
fi

done

# Check if username.txt is empty , maybe no user is applicable to show or email have already been sent to them. so they will not appear,
# Echo this info for admin info purposes.
if [ -s /tmp/username.txt ]; then
echo "" > /dev/null
else
echo "Maybe no user is applicable to show or email have already been sent to them. so they will not appear"
fi

# Apply Loop formula throught the rest of script / zaib
num=0
cat /tmp/username.txt | while read users
do
num=$[$num+1]
USERID=`echo $users | awk '{print $1}'`

# Check if time is in between 00:00 till 00:10 , if YES, then maek qmail flag set to 0 so that email can be sent again. Clever😉 . ZAIB
#CURHM=`date +%H:%M`
#start="00:00"
#end="00:10"
#if [[ "$CURHM" > "$start" && "$CURHM" < "$end" ]]; then
#echo "Time matches to reset FLAGS on qmail flag set to zero ...."
#mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET qmail = 0 WHERE username = '$USERID';"
#mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET qmailtime = '0000-00-00 00:00:00' WHERE username = '$USERID';"
#fi

TODAY=$(date +"%Y-%m-%d")
TODAYTIME=$(date +"%Y-%m-%d %T")
TOMORROW=`date --date='tomorrow' +%Y-%m-%d`

# CHECK IF DATE IS CHANGED then CLEAR THE QMAIL FLAGS, otherwise ignore and continue
LASTDEXEC=`cat /etc/lastupdate.txt`
if [ "$TODAY" != "$LASTDEXEC" ]; then
echo "ALERT: Date changed. clearing the flags .... "
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET qmail = 0 WHERE username = '$USERID';"
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET qmailtime = '0000-00-00 00:00:00' WHERE username = '$USERID';"
fi

#ZZZZZAIB
QMAILTIME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT qmailtime FROM rm_users WHERE username = '$USERID';" |awk 'FNR == 2 {print $1,$2}'`
#echo "$USERID vs $QMAILTIME vs $TODAY"
#if [[ $QMAILTIME -eq $TODAY ]]; then
#echo "SMS have already sent to $USERID for $TODAY !"
#else
#echo "" > /dev/null
#fi

SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$USERID';" |awk 'FNR == 2 {print $1}'`
SRVNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

NEXTSRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT dailynextsrvid FROM radius.rm_services WHERE srvid = '$SRVID';" |awk 'FNR == 2 {print $1}'`
NEXTSRVIDNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$NEXTSRVID';" |awk 'FNR == 2'`

COMBQUOTA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT combquota FROM radius.rm_services WHERE srvid = '$SRVID';" |awk 'FNR == 2 {print $1}'`
QMAIL=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT qmail FROM radius.rm_users WHERE rm_users.username = '$USERID';" |awk 'FNR == 2 {print $1}'`
EXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE rm_users.username = '$USERID';" |awk 'FNR == 2 {print $1}'`

# Query Today Download Dynamically
TODAYDL=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SQL_CALC_FOUND_ROWS
date,
SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0),
SUM(allbytesul) - COALESCE(SUM(specbytesul), 0),
SUM(alltime) - COALESCE(SUM(spectime), 0)
FROM (
SELECT LEFT(radacct.acctstarttime, 7) AS date,
acctoutputoctets AS allbytesdl, SUM(dlbytes) AS specbytesdl,
acctinputoctets AS allbytesul, SUM(ulbytes) AS specbytesul,
radacct.acctsessiontime AS alltime, SUM(rm_radacct.acctsessiontime) AS spectime
FROM radacct
LEFT JOIN rm_radacct ON rm_radacct.radacctid = radacct.radacctid
WHERE LEFT(radacct.acctstarttime, 4) LIKE '$1%' AND radacct.username LIKE '$USERID' AND radacct.acctstarttime > '$TODAY' AND radacct.acctstarttime < '$TOMORROW' AND
FramedIPAddress LIKE '%' AND CallingStationId LIKE '%'
GROUP BY radacct.radacctid
) AS tmp GROUP BY date LIMIT 0, 50;" |sed '1d' | awk '{ print $2 + $3 }'`

# If user Download is Empty or Zero, set fake value of 111 so that percentage formula maynot make issues
if [ ! -z "$TODAYDL" ];
then
#TODAYDL="1000"
echo ""
else
echo ""
#No quota is used TODAY so using FAKE zero value so percentage value will not give errors."
TODAYDL="111"
fi

# If downloaded data percentage is above then 70% then do action

PERCENTUSED=$((100*$TODAYDL/$COMBQUOTA))

#if [[ $PERCENTUSED -gt 70 ]]
if [ "$PERCENTUSED" -gt $QUOTAPERCLIMIT ]
then

echo "
-----------------------------------------------
ID = $USERID
QUOTA ALERT = $PERCENTUSED %
SRVID = $SRVID
NAME = $SRVNAME
NEXT DAILY SERVICE = $NEXTSRVIDNAME
TODAY DONWLOAD BYTES = $TODAYDL
QUOTA LIMIT IN BYTES = $COMBQUOTA"
echo "QUOTA ALLOWED = $(($COMBQUOTA / 1024 / 1024))" MB
DLINMB=`echo "$TODAYDL/1024/1024" | bc`
echo "Today Downloaded = $DLINMB MB"

else
# Otherwise just ECHO, do nothing
echo "
-----------------------------------------------
ID = $USERID
QUOTA = OK, NOT USED / $PERCENTUSED %
NAME = $SRVNAME
Next Daily Service = $NEXTSRVIDNAME"
if [ "$TODAYDL" -eq 111 ];
then
echo "TODAYDL is empty so using fake value"
fi
#TODAYDL="1000"
#echo "NEW VALUE is $TODAYDL"
#else
#TODAYDL="1000"
#fi
echo "TODAY DONWLOADED BYTES = $TODAYDL
QUOTA LIMIT IN BYTES = $COMBQUOTA"
echo "QUOTA ALLOWED = $(($COMBQUOTA / 1024 / 1024))" MB
#echo "$TODAYDL/1024/1024" | bc
fi

# check if near quota users have already sent email, if fetched value is 1, then do nothing
# else send email and update QMAIL flag in rm_users table
########## SENDING EMAIL
if [[ $PERCENTUSED -gt $QUOTAPERCLIMIT && $QMAIL -eq 1 ]]; then
echo "INFO: $USERID have consumed 70% or above quota and SMS have alreay been sent on $QMAILTIME
-----------------------------------------------"
fi

if [[ $PERCENTUSED -gt $QUOTAPERCLIMIT && $QMAIL -eq 0 ]]
then
echo "Sending SMS Alert info to $USERID for Quota Alert ..."

# Setting Variables for sending email and fetch other data
DAILYLIMITINMB=`echo "$COMBQUOTA/1024/1024" | bc`
MOBILE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT mobile FROM radius.rm_users WHERE rm_users.username = '$USERID';" |awk 'FNR == 2 {print $1}'`
FIRSTNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname FROM radius.rm_users WHERE rm_users.username = '$USERID';" |awk 'FNR == 2 {print $1}'`
LASTNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT lastname FROM radius.rm_users WHERE rm_users.username = '$USERID';" |awk 'FNR == 2 {print $1}'`

# Echo for Screen Print
echo "Dear $FIRSTNAME $LASTNAME,
Your internet account ID $USERID have consumed $QUOTAPERCLIMIT% of daily allowed quota that is $DAILYLIMITINMB MB. After this your speed will be reduced to $NEXTSRVIDNAME for current date.
After current date change, You will be reverted back to $SRVNAME.
Your account expiration date is $EXPIRY.

Regard's
$COMPANY"

# Echo to save data inf ile which will be used later by KANNEL to send properly formatted message.

echo "Dear $FIRSTNAME $LASTNAME,
Your internet account ID $USERID have consumed $QUOTAPERCLIMIT% of daily allowed quota that is $DAILYLIMITINMB MB. After this your speed will be reduced to $NEXTSRVIDNAME for current date.
After current date change, You will be reverted back to $SRVNAME.
Your account expiration date is $EXPIRY.

Regard's
$COMPANY" > /tmp/$USERID.sms

# Finally SENDING SMS using KANNEL SMS GATEWAY, you can use other functions as well : D ~

curl "http://$KHOST:13013/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$MOBILE" -G --data-urlencode text@/tmp/$USERID.sms

# Update mysql QMAIL flag so that system should not repeat sending emails
# Make sure you run another script that should change the QMAIL flag to 0 after data cahnges
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET qmail = 1 WHERE username = '$USERID';"
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET qmailtime = '$TODAYTIME' WHERE username = '$USERID';"
fi
done

# In the end UPDATE the last executed time that will be check on next script execution

echo "$TODAY" > /etc/lastupdate.txt

tables


 


Filed under: Linux Related, Radius Manager

Mikrotik: Using Firewall Filters to Acquire Wan Data Usage via Email

$
0
0

monitoring_report


Requirements:

An Operator [from Amsterdam] wanted to receive email on daily basis for the Daily usage of WAN link on the Mikrotik. Something like Mikrotik should send simple reporting email on daily basis like ‘XXX MB were downloaded Yesterday via WAN link’.

Solution:

Use following Script. All sections are well defined in it. Make sure you read it carefully line by line, and modify items required.

In this example I used FILTER rules approach to collect the bytes. Surely there are more elegant ways to fetch the data like … Linux base MRTG, NMS like DUDE, above all SNMP  and many others. I just used this method. You may select other as it suites you. This one worked neatly for me:)

You can customize it as per your requirements, like multi wan report, monthly report etc.


Requirements:

Mikrotik 6.x

  1. Schedule this script to run after 5 (or xx) minutes. When DATE change occurs, it will reset the counter file and filter rules counters.
  2. Create two FILTER rules in Mikrotik as following. SFP1 is the wan interface, so do change it accordingly.
/ip firewall filter
add action=passthrough chain=forward comment=WAN_1_IN in-interface=sfp1
add action=passthrough chain=forward comment=WAN_1_OUT out-interface=sfp1

the Script !


# Script to collect WAN DATA USAGE by FILTER rules, and send data to admin by Email Daily.
# And reset the counters on daily basis in night. it will preserve the data in a file even if the router reboots.
# Syed Jahanzaib / aacable @ hotmail . com
# https://aacable.wordpress.com
# 23-MAY-2016

# Make sure you add two firewall rules as showed below so that script can take bytes from it and reset it when date changes.
# Change the interface name accordingly, and make sure to enter the matching comments too.
# /ip firewall filter
#add action=passthrough chain=forward comment=WAN_1_IN in-interface=sfp1
#add action=passthrough chain=forward comment=WAN_1_OUT out-interface=sfp1

# Set comments for firewall filter rules, change them as required
:local WAN1INCOMMENT
:local WAN1OUTCOMMENT
:local WAN1INCOMMENT "WAN_1_IN"
:local WAN1OUTCOMMENT "WAN_1_OUT"

:local BYTESOUT [/ip firewall filter get [/ip firewall filter find comment="$WAN1INCOMMENT"] bytes]
:local BYTESIN [/ip firewall filter get [/ip firewall filter find comment="$WAN1OUTCOMMENT"] bytes]

# SET GMAIL for sending email, make sure you have configured /TOOLS,EMAIL option of mikrotik. and test it before using following.
:global gmailsmtp
:set gmailsmtp [:resolve "smtp.gmail.com"];
# Set your GMAIL Account Password
:local gmailpass
:set gmailpass GMAIL-PASSWORD
# Set your email where you want to receive the alert
:local mailsendto
:set mailsendto YOUR-ADMIN-EMAIL@xxxx.com

# set DATE TIME
:local date
:local time
:set date [/system clock get date];
:set time [/system clock get time];

# Create file (if file is not already there.) to update date time of last update
:if ([:len [/file find where name=counterslastupdate.txt ]] < 1 ) do={
/file print file=counterslastupdate.txt where name=counterslastupdate.txt
/file set counterslastupdate.txt contents="0";
};

# Create file (if file is not already there.) to store last update date time in normal format to be showed in email.
:if ([:len [/file find where name=counterslastupdatenormalformat.txt ]] < 1 ) do={
/file print file=counterslastupdatenormalformat where name=counterslastupdatenormalformat.txt
/file set counterslastupdatenormalformat contents="0";
};

# Setting variables
:local curDate [/system clock get date]
:local curYear [:pick $curDate 7 13]
:local curMon [ :pick $curDate 0 3 ]
:local curDay [:pick $curDate 4 6]
:local COMPANY "JZ"
:local CURRENTDATE "$curDay$curYear"
:local LASTUPDATEDATE value=[/file get counterslastupdate.txt contents]
:local LASTUPDATEDATENORMAL value=[/file get counterslastupdatenormalformat.txt contents]

# Update counters last update with current date time
/file set counterslastupdate.txt contents=$CURRENTDATE

# Calculate data in MB to be displayed in LOG and email
:local TOTAL
:set $TOTAL ($BYTESOUT+$BYTESIN)
:local TOTALMB
:set $TOTALMB ($TOTAL / 1024 / 1024)
#:log info ( "Traffic out = " . $BYTESOUT . " bytes" )
#:log info ( "Traffic in = " . $BYTESIN . " bytes" )
#:log warning ( "TOTAL TRAFFIC = " . $TOTAL. " bytes" )
:log warning "$TOTALMB MB Downloaded iva WAN link on $curDate"

# If date is changed (usually in night) , then send email using GMAIL , with the Data
:if ($CURRENTDATE = $LASTUPDATEDATE) do={
:log warning "No need to send email."
} else {
:log warning "DATE changed, sending email for last day data usage and also reset the Firewall Counters ..."
# Reset the firewall counters and counter files if date change is detected / zaib
/ip firewall filter reset-counters [find comment=$WAN1INCOMMENT ]
/ip firewall filter reset-counters [find comment=$WAN1OUTCOMMENT ]
/file set counter.txt contents="0";

# Set Email Subject
:local es "$[/system identity get name] $[/system clock get date] $[/system clock get time] $COMPANY MIKROTIK / $TOTALMB MB were downloaded via WAN link on $LASTUPDATEDATENORMAL"
# Set Email Body
:local eb "$[/system identity get name] $[/system clock get date] $[/system clock get time] $COMPANY MIKROTIK / $TOTALMB MB were downloaded via WAN link on $LASTUPDATEDATENORMAL"
# Finally send email
/tool e-mail send to=$mailsendto subject=$es body=$eb start-tls=yes
};

# Create file (if file is not already there.) to update download bytes
:if ([:len [/file find where name=counter.txt]] < 1 ) do={
/file print file=counter.txt where name=counter.txt;
/delay delay-time=1;
/file set counter.txt contents="0";
};

# If current value is bigger then older, then update the counters,
# Helpfule to save counters, when router reboots.

# Get value from stored data for matching
:local before value=[/file get counter.txt contents]

:if ($TOTAL > $before) do={
/file set counter.txt contents=$TOTAL
} else= {
# Else update both values in the file
:set $TOTAL ($TOTAL+$before)
/file set counter.txt contents=$TOTAL
};

# Update Date time stamp in both files / zaib
/file set counterslastupdate.txt contents=$CURRENTDATE
/file set counterslastupdatenormalformat.txt contents=$curDate

# Regard's
# Syed Jahanzaib


End Results !

downlaoded

 

 


Filed under: Mikrotik Related

Disconnect deleted user from the NAS ACTIVE list using RADCLIENT

$
0
0

disconnectimage


SCENARIO:


Problem:

[As required by an specific OP]

When the OP deleted any user account from the Radius Billing system (example Radius manager) AND if his session is ACTIVE on the NAS , he will not disconnect automatically from the active users list [on the NAS] and he will continue to use the internet as long as his old session is connected. If the network is stable enough, the user can continue to use internet for days . So ultimately the user will become blood sucking vampire : ) ~


Solution:

We can schedule following script to run every 5 minutes. It will fetch the deleted users from the rm_syslog events, and will display the list, and then sends DISCONNECT request to the NAS to remove those users.

We can also use SSH or API method [preferred] , but it requires additional steps and skills. and It largely depends on the OP requirements and his skills to manage things as desired.

If there are multiple paths to reach the destination,
Select one with the least complications !
/ zaiB


Requirements:

radclient , utility which will send the disconnect requests.


the SCript !

 


#!/bin/bash
# set -x
# SCRIPT to fetch data of users removed manually from teh radius and disconnect them from the mikrotik active list.
# Syed Jahanzaib / aacable @ hotmail.com / https://aacable.wordpress.com
# 24-MAY-2016

# Setting FILE Variables
TMPFILE="/tmp/disconusers.txt"
> $TMPFILE

# Mikrotik NAS Details
NAS="192.168.0.1"
NASPORT="1700"
SECRET="PUT_RADIUS_SECRET_HERE"
CURDATE=`date`

#MYSQL INFO
SQLUSER="root"
SQLPASS="zSQL_PASSWORD"

#Interval in minutes
INTERVAL="5"

# Mysql query to fetch users whoes accounts are deleted from radius database.

# Print info
#mysql -u$SQLUSER -p$SQLPASS -e "use radius; select data1 from rm_syslog where eventid = '2' AND datetime >= NOW() - INTERVAL $INTERVAL MINUTE;"
# store in file
mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select data1 from rm_syslog where eventid = '2' AND datetime >= NOW() - INTERVAL $INTERVAL MINUTE;" > $TMPFILE
# Check if no user is deleted in DEFINED interval
# Echo this info for admin info purposes.

if [ -s $TMPFILE ]
then
echo "Following Users have Found for disconnection at Mikrotik $NAS..."

echo "DATE | USERNAME | NAS"

# Apply Formula to read the file in which dismissed users list and act accordingly.
num=0
cat $TMPFILE | while read users
do
num=$[$num+1]
USERNAME=`echo $users | awk '{print $1}'`

# Send Disconnection Packet to Mikrotik/NAS in order to disconnect user now
echo "$CURDATE | $USERNAME | $NAS"
done
echo ""
echo "Holding 10 seconds so you can review the list then it will start disconnecting the users from NAS $NAS"
sleep 10

# Applying Formula again to DISCONNECT users from the NAS
num=0
cat $TMPFILE | while read users
do
num=$[$num+1]
USERNAME=`echo $users | awk '{print $1}'`

# SEND DISCONNECT REQUEST TO NAS FOR SPECIFIC USERS
echo user-name=$USERNAME | radclient -x $NAS:1700 disconnect $SECRET
done

else

echo "No user have found deleted. Nothing to do..."
fi

# Script End
# Regard's / zaib


Results:

disc

 


Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

Sending SMS/Email Alert upon manager login

$
0
0

2016-05-31 10.36.22

 

a1



Reference Note:

As per requested by OP, following script will send email and SMS alert to manager whose account is logged in successfully in last minutes at admin panel (ACP).

In this example we have used Kannel as SMS gateway and sendEmail application to send email using standard Gmail account. Schedule it to run after every 5 minutes interval.

Regard’s
Syed Jahanzaib~



#!/bin/bash
# set -x
# SCRIPT to send email / sms alert when any admin or manager logged in to radius manager billing panel.
# SMS will be sent via kannel sms gateway, you can change it as per your requirements
# Email will be sent using sendEMAIL application, via your GMAIL account. I wrote post on howto setup sendEMAIL,
# You can modify it as well.

# Syed Jahanzaib / aacable @ hotmail.com / https://aacable.wordpress.com
# Created: 31-MAY-2016

# Setting FILE Variables
TMPFILE1="/tmp/adminlog.txt"
> $TMPFILE1

COMPANY="YOUR COMPANY"
FOOTER="Powered by Syed Jahanzaib"

#DATE TIME
CURDATE=`date`

#MYSQL INFO
SQLUSER="root"
SQLPASS="MYSQL-PASSWORD"

#Interval in minutes
INTERVAL="5"

# Kannel SMS Gateway IP and username password Details
KHOST="127.0.0.1"
KID="kannel"
KPASS="KANNEL-PASSWORD"

#GMAIL DETAILS for sending email alert
GMAILID="YOUR-GMAIL-ID@gmail.com"
GMAILPASS="YOUR-GMAIL-PASSWORD"
ADMINMAIL1="aacable @ hotmail . com"

# Mysql query to fetch users whoes accounts are deleted from radius database.
# Print info
mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select name, ip, datetime from rm_syslog where eventid = '3' AND datetime >= NOW() - INTERVAL $INTERVAL MINUTE;" > $TMPFILE1

# Check if no user is deleted in DEFINED interval
# Echo this info for admin info purposes.

if [ -s $TMPFILE ]
then
echo "Following Managers have Found Logged in last $INTERVAL Minutes on Radius Billing System..."

# Apply Formula to read the file in which dismissed users list and act accordingly.
num=0
cat $TMPFILE1 | while read users
do
num=$[$num+1]
USERNAME=`echo $users | awk '{print $1}'`
IP=`echo $users | awk '{print $2}'`
DATETIME=`echo $users | awk '{print $3,$4}'`
FIRSTNAME=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select firstname from rm_managers where managername = '$USERNAME';"`
LASTNAME=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select lastname from rm_managers where managername = '$USERNAME';"`
MOBILE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select mobile from rm_managers where managername = '$USERNAME';"`
EMAIL=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select email from rm_managers where managername = '$USERNAME';"`

# PRINT INFO , for review
echo "GT Alert:
$FIRSTNAME $LASTNAME, You have successfully logged-in to billing admin panel.
ID = $USERNAME
DATE = $DATETIME
IP = $IP
MOBILE = $MOBILE

Regard's
$COMPANY
$FOOTER"

# create temporary holder where sms will be stored
echo "$FIRSTNAME $LASTNAME, You have successfully logged-in to billing admin panel.
ID = $USERNAME
DATE = $DATETIME
IP = $IP
MOBILE = $MOBILE

Regard's
$COMPANY
$FOOTER" > /tmp/$USERNAME.login.sms

# Finally SENDING SMS using KANNEL SMS GATEWAY, you can use other functions as well : D ~
curl "http://$KHOST:13013/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$MOBILE" -G --data-urlencode text@/tmp/$USERNAME.login.sms

# Make sure you install sendEMAIL tool and test it properly before using email section.
#SEND EMAIL Alert As well using sendEMAIL tool using GMAIL ADDRESS.
# If you want to send email , use below ...

echo "Sending SEMAIL ALERT to $EMAIL & $ADMINMAIL1..."
/temp/sendEmail-v1.56/sendEmail -u "GT Billing Alert: $USERNAME successfully logged-in to Billing Admin Panel." -o tls=yes -s smtp.gmail.com:587 -t $EMAIL -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=/tmp/$USERNAME.login.sms -o message-content-type=text

echo "$USERNAME loggedin at $DATETIME from $IP" >> /var/log/adminlog.txt
done
echo ""
else
echo "No MANAGER have found logged in last $INTERVAL minutes. Nothing to do..."
fi

# Script End
# Regard's / zaib

Filed under: Radius Manager

Cisco Switch / Shot notes

$
0
0

stml


 

3750

Disclaimer: This post is for my personal reference purpose only. It’s not aimed for professionals.


1# Howto to reset Cisco 3750 Switch to Factory Default

To reset the switch:

  1. Press and hold the Mode button.
  2. The switch LEDs will begin blinking after about 3 seconds. Continue holding down the Mode button.
  3. The LEDs stop blinking after 7 more seconds, and then the switch will reboot.
    (So you have to hold the MODE button for about 10-12 seconds max.)
  4. Once the reboot done, The switch will now behaves like an unconfigured switch. You can enter the switch IP information by using Express Setup.

EXPRESS SETUP:

Once the switch is reset to factory default, we have to configure an ip address / password.
For this purpose we should remove all ethernet cables from the switch and make sure nothing is connected with it.

  1. During Express Setup, the switch acts as a DHCP server.
  2. Make sure that nothing is connected to the switch.
  3. Power On the Switch. Wait for the switch to complete POST, which can take several minutes.
  4. When the SYST LED remains green. Press and hold the Mode button for 3 seconds. When all of the LEDs left of the Mode button turn green, release the Mode button.NOTE:  If the LEDs left of the Mode button begin to blink after you press the button, release it. Blinking LEDs mean that the switch has already been configured and cannot go into Express Setup mode. RUN THE RESET PROCESS FROM BEGINNING AGAIN.
  5. Verify that the switch is in Express Setup mode by confirming that all LEDs left of the Mode button are green.
  6. Connect your laptop / desktop ethernet cable directly to the switch
  7. It may take 1 minute to stable. The PC will take IP from switch DHCP automatically.

 

The Switch Default IP is

10.0.0.1

Start a web browser on your PC. Enter the IP address http://10.0.0.1 in the web browser, and press Enter !

 

sw1

>

sw2

Now you can browse base config which provides minimal options, or better to configure it using Cisco Network Assistant Software which is very enhance GUI application to manage the beast:)


2# Reset the Cisco 3750 Forgotten Password

To be continued …

 


 

Regard’s
Syed Jahanzaib


Filed under: Cisco Related

Getting ‘Out of the Box’ solution with Mikrotik , BASH & mySQL

$
0
0

codes


DISCLAIMER:

JUST AN EXAMPLE SAMPLE !

Following post is an example of fun coding. Just to learn and explore new ways of howto get ‘out of the box’ solution. In this example I have used Mikrotik Script, Bash Script, mySQL, and sendEmail tool all together. I made this solution, and surely I know that it’s not very elegant, not professional but I learned few things from it . This is just my own idea and sharing it , maybe someone will find it useful for some other project. Just to share my two cents …

Most of tasks described in this lengthy post can be achieved using mikrotik scripting alone, But

I just wanted to explore the possibilities on how multi platform systems , scripts, functions can be used all together to get our desired results with twisted, molded and formatted results in a way we want it to be !!! Simple is this !!!

BASH is Fun !

Regard's
Syed Jahanzaib

Scenario:

The OP have several dhcp pools in Mikrotik for users. In peak time , the dhcp assigned all or most available ips from the specific pool and error starts appearing in LOG.

Jun 1 14:46:51 X.X.X.X dhcp,error dhcp12: failed to give out IP address: pool <dhcp_pool12> is empty

mikrotik log error full pool

 


Requirements

The OP wanted to receive email alert when any pool configured in pool section of mikrotik crosses xx %.
and all pool statistics should be stored in mySQL as well, so that it can be used for various purposes. The script should also email the admin about the pool usage alert if it crosses XX %.


Solution

At mikrotik forum, dssmiktik posted an script which can query all pools and display there statistics.
Example of this script result on mikrotik terminal is as follows.

mtdhcplog

We will use this script on the mikrotik, and configure scheduler on Ubuntu/Lilnux to execute this script remotely and fetch the results in a local file, Format it, Store it in mySQL custom table, Do Comparison and ACT accordingly.

Example if any pool  crosses specific % limit, the bash script will update table accordingly, Send email and it will also prevent repeated email for the same.

 


Mikrotik Section #

Add following script in mikrotik script section …


# List stats for IP -> Pool
#
# criticalthreshold = output pool display in red if pool used is above this %
# warnthreshold = output pool display in gold if pool used is above this %

:local criticalthreshold 85
:local warnthreshold 50

# Internal processing below...
# ----------------------------------
/ip pool {
:local poolname
:local pooladdresses
:local poolused
:local poolpercent
:local minaddress
:local maxaddress
:local findindex
:local tmpint
:local maxindex
:local line

# :put ("IP Pool Statistics")
# :put ("------------------")

# Iterate through IP Pools
:foreach p in=[find] do={

:set poolname [get $p name]
:set pooladdresses 0
:set poolused 0
:set line ""

:set line (" " . $poolname)

# Iterate through current pool's IP ranges
:foreach r in=[:toarray [get $p range]] do={

# Get min and max addresses
:set findindex [:find [:tostr $r] "-"]
:if ([:len $findindex] > 0) do={
:set minaddress [:pick [:tostr $r] 0 $findindex]
:set maxaddress [:pick [:tostr $r] ($findindex + 1) [:len [:tostr $r]]]
} else={
:set minaddress [:tostr $r]
:set maxaddress [:tostr $r]
}

# Convert to array of octets (replace '.' with ',')
:for x from=0 to=([:len [:tostr $minaddress]] - 1) do={
:if ([:pick [:tostr $minaddress] $x ($x + 1)] = ".") do={
:set minaddress ([:pick [:tostr $minaddress] 0 $x] . "," . \
[:pick [:tostr $minaddress] ($x + 1) [:len [:tostr $minaddress]]]) }
}
:for x from=0 to=([:len [:tostr $maxaddress]] - 1) do={
:if ([:pick [:tostr $maxaddress] $x ($x + 1)] = ".") do={
:set maxaddress ([:pick [:tostr $maxaddress] 0 $x] . "," . \
[:pick [:tostr $maxaddress] ($x + 1) [:len [:tostr $maxaddress]]]) }
}

# Calculate available addresses for current range
:if ([:len [:toarray $minaddress]] = [:len [:toarray $maxaddress]]) do={
:set maxindex ([:len [:toarray $minaddress]] - 1)
:for x from=$maxindex to=0 step=-1 do={
# Calculate 256^($maxindex - $x)
:set tmpint 1
:if (($maxindex - $x) > 0) do={
:for y from=1 to=($maxindex - $x) do={ :set tmpint (256 * $tmpint) }
}
:set tmpint ($tmpint * ([:tonum [:pick [:toarray $maxaddress] $x]] - \
[:tonum [:pick [:toarray $minaddress] $x]]) )
:set pooladdresses ($pooladdresses + $tmpint)
# for x
}

# if len array $minaddress = $maxaddress
}

# Add current range to total pool's available addresses
:set pooladdresses ($pooladdresses + 1)

# foreach r
}

# Now, we have the available address for all ranges in this pool
# Get the number of used addresses for this pool
:set poolused [:len [used find pool=[:tostr $poolname]]]
:set poolpercent (($poolused * 100) / $pooladdresses)

# Output information
:set line ([:tostr $line] . " [" . $poolused . "/" . $pooladdresses . "]")
:set line ([:tostr $line] . " " . $poolpercent . " % used")

# Set colored display for used thresholds
:if ( [:tonum $poolpercent] > $criticalthreshold ) do={
:log error ("IP Pool " . $poolname . " is " . $poolpercent . "% full")
:put ([:terminal style varname] . $line)
} else={
:if ( [:tonum $poolpercent] > $warnthreshold ) do={
:log warning ("IP Pool " . $poolname . " is " . $poolpercent . "% full")
:put ([:terminal style syntax-meta] . $line)
} else={
:put ([:terminal style none] . $line)
}
}

# foreach p
}
# /ip pool
}


Create Tables in DB first !

Following is mysql table mikrodhcp.sql dump. Save it in file, and restore it using mysql command.

Example: [restore mikrodhcp table in mysql radius database, change it as per your own configuration]

mysql -u root -prootpassword radius < mikrodhcp.sql 


-- MySQL dump 10.13 Distrib 5.5.49, for debian-linux-gnu (i686)
--
-- Host: localhost Database: radius
-- ------------------------------------------------------
-- Server version 5.5.49-0ubuntu0.12.04.1

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `mikrodhcp`
--

DROP TABLE IF EXISTS `mikrodhcp`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mikrodhcp` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`mikrotikip` varchar(16) CHARACTER SET utf32 NOT NULL,
`poolname` text NOT NULL,
`poolipusedno` int(11) NOT NULL,
`pooliptotal` int(11) NOT NULL,
`percentage` int(11) NOT NULL,
`mailsent` tinyint(1) NOT NULL,
`status` tinyint(1) NOT NULL,
`lastupdate` datetime NOT NULL,
`autodateupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=727 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `mikrodhcp`
--

LOCK TABLES `mikrodhcp` WRITE;
/*!40000 ALTER TABLE `mikrodhcp` DISABLE KEYS */;
/*!40000 ALTER TABLE `mikrodhcp` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2016-06-02 15:58:13

IMPORTANT ! TEST THE TABLE !

One the table is imported without any error. Check it with following command

mysql -uroot -pROOTPASSWORD -e "use radius; describe mikrodhcp;"

 

and you may get following result if ALL is OK !

+----------------+------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------------+------+-----+-------------------+-----------------------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| mikrotikip | varchar(16) | NO | | NULL | |
| poolname | text | NO | | NULL | |
| poolipusedno | int(11) | NO | | NULL | |
| pooliptotal | int(11) | NO | | NULL | |
| percentage | int(11) | NO | | NULL | |
| mailsent | tinyint(1) | NO | | NULL | |
| status | tinyint(1) | NO | | NULL | |
| lastupdate | datetime | NO | | NULL | |
| autodateupdate | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+----------------+------------------+------+-----+-------------------+-----------------------------+

Now you can use following bash script …

the BASH SCRIPT !


#!/bin/bash
#set -x
# Script to fetch dhcp ip pool results from the mikrotik
# then update these results in mysql table, and email accordingly
# No portion of this script is copied from the internet.
# You are free to copy, modify, distribute it as you like
# Make sure you change all the variables as required like mysql id, tables etc.
# Created by : Syed Jahanzaib / aacable @ hotmail dot com
# https://aacable.wordpress.com
# Created: 2nd-MAY-2016

clear

# Colors Config . . . [[ JZ . . . ]]
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"

#Temporary Holder for DHCP Status from Mikrotik
RESULT="/tmp/dhcpstatus.txt"
> $RESULT

#Mikrotik Details
MIKROTIK="1.2.3.4"
MTPORT="8291"
MTDHCPSCRIPT="dhcpstatus"

# DATE TIME
DATE=`date`
TODAYTIME=$(date +"%Y-%m-%d %T")

#MYSQL INFO
SQLUSER="MYSQL-ROOT"
SQLPASS="MYSQL-PASSWPORD"
DB="radius"
TABLE="mikrodhcp"
MAINTABLE="rm_users"
ALERTPERCENTAGE="50"

#EMAIL SECTION
GMAILID="YOURGMAILID@gmail.com"
GMAILPASS="GMAILPASS"
ADMINMAIL1="YOURADMINMAIL@hotmail.com"
COMPANY="YOUR COMPANY (Pvt) LTD"
FOOTER="Powered by Syed Jahanzaib"
# Create mikrodhcp table if not exists
DBCHECK=`mysql -u$SQLUSER -p$SQLPASS -e " SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '$DB';"`
if [ ! -z "$DBCHECK" ];
then
echo -e "Step-1# Checking $DB DB ... $DB database Found OK, proceeding further ... $COL_GREEN OK $COL_RESET"
#sleep 3
else
echo -e "$COL_RED ERROR: $DB database does NOT exists in mysql. it is required to store dhcp pool status data ...$COL_RESET"
exit 0
fi
# Create mikrodhcp table if not exists
TABLECHECK=`mysql -u$SQLUSER -p$SQLPASS -e " SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '$DB' AND TABLE_NAME = '$TABLE';"`
if [ ! -z "$TABLECHECK" ];
then
echo -e "Step-2# Checking $TABLE table ... $TABLE TABLE Found OK, proceeding further ... $COL_GREEN OK $COL_RESET"
#sleep 3
else
echo -e "$COL_RED ERROR: $TABLE does NOT exists in $MAINTABLE. it is required to store mikroptik dhcp pool status data ...$COL_RESET"
exit 0
fi
# Check if Mikrotik is accessibel or not, if not then EXIT immediately with error / zaib
if [[ $(ping -q -c 1 $MIKROTIK) == @(*100% packet loss*) ]]; then
echo -e "$COL_RED ALERT ..... MIKROTIK $MIKROTIK is DOWN$COL_RESET"
exit
else
echo -e "Step-3# Mikroik is Accessible, now proceeding further ... $COL_GREEN OK $COL_RESET"
fi

# Execute script on mikrotik which will get the required results liek dhcp ip pool status
ssh -q -p $MTPORT admin@$MIKROTIK /sys script run $MTDHCPSCRIPT > $RESULT

# VERIFY $RESULT FILE
A=`cat $RESULT`
B="no such item"
if [ "$A" == "$B" ];
then
echo -e "$COL_RED Mikrotik Script name '$MTDHCPSCRIPT' not found on Mikrotik. Please verify script name, test it on mikrotik first .... $COL_RESET"
exit 0
fi
echo -e "Step-4# Mikroik script fetched is Accessible, now proceeding further ... $COL_GREEN OK $COL_RESET"

# Verify if file is downloaded from mikrotik or not, if not dueo to ssh delay bug or other , then print error and exit:) Security Check by zaib
{
if [ ! -f $RESULT ]; then
echo -e "$COL_RED ERROR: Mikrotik $MIKROTIK is live but it's SSH not accessible !!! $COL_RESET"
exit 0
fi
}
echo -e "Step-5# Mikroik $MIKROTIK SSH is accessible, now proceeding further ... $COL_GREEN OK $COL_RESET"

echo -e "Showing Results fetched from Mikrotik script ... $COL_GREEN OK $COL_RESET
"

echo -e "[POOL-NAME] [IP-USED-IN-POOL] [TOTAL-IP-IN-POOL] [POOL-USED-PERCENTAGE-%]" | awk '{printf "%-30s %-40s %-40s %-40s\n",$1,$2,$3,$4}'
echo ""
# Run Loop Formula
# Apply Formula to read the file in which dismissed users list and act accordingly.
num=0
cat $RESULT | while read data
do
num=$[$num+1]
POOLNAME=`echo $data | awk '{print $1}'`
POOLSTATUS=`echo $data | awk '{print $2}'`
POOLUSEDPERC=`echo $data | awk '{print $3}'`
POOLIPTOTAL=`echo $data | awk '{print $2}' | sed 's/\(\[\|\]\)//g' | sed 's#/#\ #g' | awk '{print $2}'`
POOLIPUSEDNO=`echo $data | awk '{print $2}' | sed 's/\(\[\|\]\)//g' | sed 's#/#\ #g' | awk '{print $1}'`

# Adding POOL names in table, so they can be updated according to teh usage in later stage ... zaib
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; INSERT INTO $TABLE (mikrotikip, poolname) SELECT * FROM (SELECT '$MIKROTIK', '$POOLNAME') AS tmp WHERE NOT EXISTS (
SELECT poolname FROM $TABLE WHERE poolname = '$POOLNAME') LIMIT 1;"
# If percentage is high, ALERT in RED
if [ "$POOLUSEDPERC" -gt $ALERTPERCENTAGE ]
then
#echo -e "$COL_RED ALERT: $POOLNAME have consumed $POOLIPUSEDNO ips from $POOLIPTOTAL Total IPs / Percetnage Used = $POOLUSEDPERC % $COL_RESET"
echo -e "$COL_RED$POOLNAME $POOLIPUSEDNO $POOLIPTOTAL $POOLUSEDPERC Crossed $ALERTPERCENTAGE% $COL_RESET" | awk '{printf "%-40s %-40s %-40s %-5s %-5s %-5s *** ALERT ***\n",$1,$2,$3,$4,$5,$6}'

# UPDATE pool status with ALERT Status and other info
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; UPDATE $TABLE SET mikrotikip = '$MIKROTIK' , poolipusedno = '$POOLIPUSEDNO' , pooliptotal = '$POOLIPTOTAL' , percentage = '$POOLUSEDPERC' , status = '1' , lastupdate = '$TODAYTIME' WHERE poolname = '$POOLNAME';"

else

# If percentage is low, Show result and update mysql table as well
#echo -e "$COL_GREEN NORMAL USAGE: $POOLNAME have consumed $POOLIPUSEDNO ips from $POOLIPTOTAL Total IPs / Percentage Used = $POOLUSEDPERC % $COL_RESET"
echo -e "$COL_GREEN$POOLNAME $POOLIPUSEDNO $POOLIPTOTAL $POOLUSEDPERC $COL_RESET" | awk '{printf "%-40s %-40s %-40s %-40s\n",$1,$2,$3,$4}'

# UPDATE pool status with normal values
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; UPDATE $TABLE SET mikrotikip = '$MIKROTIK' , poolipusedno = '$POOLIPUSEDNO' , pooliptotal = '$POOLIPTOTAL' , percentage = '$POOLUSEDPERC' , status = '0' , mailsent = '0' , lastupdate = '$TODAYTIME' WHERE poolname = '$POOLNAME';"
fi

# Testing if email is required to be sent, if not alreasy sent
MAILSENT=`mysql -uroot -pView*pak --skip-column-names -e "use radius; select mailsent from mikrodhcp where poolname = '$POOLNAME';"`
if [[ $POOLUSEDPERC -gt $ALERTPERCENTAGE && $MAILSENT -eq 0 ]]
then
echo "Sending email for $POOLNAME ..."
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; UPDATE $TABLE SET mailsent = '1' where poolname = '$POOLNAME';"

##################### START SENDING EMAIL
# create temporary holder where EMAIL will be stored
EMAILFILE="/tmp/$POOLNAME.dhcp.email"
> $EMAILFILE

echo "$COMPANY DHCP ALERT:

$POOLNAME pool in Mikrotik DHCP have crossed $ALERTPERCENTAGE % Limit

$POOLNAME have consumed $POOLIPUSEDNO ips from $POOLIPTOTAL Total IPs
$POOLNAME Percetnage Used = $POOLUSEDPERC %

Regard's

$COMPANY
$FOOTER" > $EMAILFILE

# Make sure you install sendEMAIL tool and test it properly before using email section.
# SEND EMAIL Alert As well using sendEMAIL tool using GMAIL ADDRESS.
# If you want to send email , use below ...

echo "Sending EMAIL ALERT to $ADMINMAIL1  ..."
/temp/sendEmail-v1.56/sendEmail -u "$COMPANY DHCP ALERT: $POOLNAME have consumed $POOLUSEDPERC %." -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$EMAILFILE -o message-content-type=text
fi
##################### EMAIL SENT DONE

fi

if [[ $POOLUSEDPERC -gt $ALERTPERCENTAGE && $MAILSENT -eq 1 ]]
then
echo "Email alert already sent for $POOLNAME to $ADMINMAIL1..."
#mysql -u$SQLUSER -p$SQLPASS -e "use $DB; UPDATE $TABLE SET mailsent = '1' where poolname = '$POOLNAME';"
fi
done

###### LOOP DONE ########
#Reset Terminal Color to Default
tput sgr0

POOLIPTOTAL=`cat $RESULT | awk '{print $2}' | sed 's/\(\[\|\]\)//g' | sed 's#/#\ #g' | awk '{print $2}'`
POOLIPUSEDNO=`cat $RESULT | awk '{print $2}' | sed 's/\(\[\|\]\)//g' | sed 's#/#\ #g' | awk '{print $1}'`

TOTALIP=`echo "$POOLIPTOTAL" | awk '{ sum+=$1} END {print sum}'`
USEDIP=`echo "$POOLIPUSEDNO" | awk '{ sum+=$1} END {print sum}'`

echo "
Total USED IPs = $USEDIP
Total IPs in POOL = $TOTALIP"
echo -e "Updating MYSQL Table on Billing @ $DATE ... $COL_GREEN OK $COL_RESET"
echo "Powered by Syed Jahanzaib"


END RESULTS ! with FANCY COLORED OUTPUT : ) We all love COLORS don’t we ?

 

SCRIPT EXECUTION RESULT #1

1-dhcp-alert-on-bash-screen

 

SCRIPT EXECUTION RESULT #2

 

2-dhcp-alert-on-bash-screen-and-show-already-sent email

 

TABLE RESULTS AFTER SCRIPT UPDATE !

5- table result


EMAIL ALERT SAMPLE #1

 

2- dhcp alert amil sub

EMAIL ALERT SAMPLE #2


3- dhcp billing alert full mail

 


Next Tasks:  To be continued …

Create MRTG graph for each pool, so that OP can have idea on which pool is most used in what timings exactly.

 


Filed under: Linux Related, Mikrotik Related, Radius Manager

Mikrotik: Script to re-connect wan pppoe-outx after X hours

$
0
0

link

Example of Mikrotik Script to execute customized function IF condition matches !


Requirements:

  • Mikrotik should disconnect wan client pppoe-out1 , only if its uptime is above 8 hours for that single session. There should be several checks like the script should check for following (to avoid errors)
  • Check for valid interface name , if interface not found, print error
  • Check for Running Status, if the pppoe-out interface is not connected to ppp server, print error
  • If the pppoe-out client uptime is above then the defined maximum uptime limit, it should disable interface, wait for 5 seconds, and then re-connect
  • Check if interface is in running status, print its IP address an strip its subnet

Solution:

the Script !

 

# Mikrotik Script to monitor UPTIME of the PPPOE-OUT(x) WAN interface, and act accordingly
# Useful when you want to disconnect your wan interface for any reason if it uptime crosses max up time limit defined.
# Maybe to hide router form Remote PPP Servers uptime Monitoring System

# Syed Jahanzaib / aacable @ hotmail . com / https://aacable.wordpress.com
# Tested with Mikrotik 6.35.2 / on RB3011UiAS (arm)
# Created: 8-JUN-2016

# Define which interface uptime you want to monitor, in this example, i used pppoe-out1, you may change it as required
:local PPPINT pppoe-out1;

# Define the UPTIME Limit that will be matched with uptime, Example is 8 hours
:local MAXUPTIMELIMIT 08:00:00;

# Define how long it should wait before re-connecting / re-enable wan interface, example 5 seconds
:local DELAY 5s;

###############################
# SCRIPT FUNCTIONS STARTS HERE ...
###############################

# Check if interface is available or not, IF NOT THEN EXIT
:if ([:len [/interface find name=$PPPINT]] = 0 ) do={ :log error "WARNING: No interface named $PPPTINT, please check configuration." }

# Check for Interface Running Status, if its not connected then give error
:global PPPINTSTATUS;
/interface pppoe-client monitor $PPPINT once do={ :set PPPINTSTATUS $status}
:if ($PPPINTSTATUS != "connected") do={
:log error "$PPPINT NOT CONNECTED TO THE REMOTE SERVER YET, NOT READY";
}

# Define variable to hold current uptime value of the interface
:local wanuptime;
/interface pppoe-client monitor $PPPINT once do={
:set $wanuptime $uptime;

# Print Uptime , just for testing
#:log warning "$PPPINT UP Time is > $uptime";
}

# Match interface current uptime with maximum uptime limit defined in MAXUPTIMELIMIT variable
# Greater then forumla / zaib
:if ($wanuptime>$MAXUPTIMELIMIT) do={
:log error "ALERT: $PPPINT UP Time have crossed $MAXUPTIMELIMIT Hours Limit ... Disconnecting it and will Re-Connect after 5 Seconds";

# Disable $PPPINT interface
/interface disable $PPPINT
delay $DELAY;
/interface enable $PPPINT
:log warning "$PPPINT have been enabled , check if its connected properly."
:delay $DELAY
:local PPPINTIP [ /ip address get [/ip address find interface=$PPPINT] address ]
:for i from=( [:len $PPPINTIP] - 1) to=0 step=-1 do={
:if ( [:pick $PPPINTIP $i] = "/") do={
:set PPPINTIP [:pick $PPPINTIP 0 $i]
:log warning "$PPPINT ip address is > $PPPINTIP / Script ENDS here ..."
}
}

# Show under limit message. if all ok

:if ([/interface get $PPPINT value-name=running]) do={
:if ($wanuptime<$MAXUPTIMELIMIT) do={
:log warning "$PPPINT UP-Time $wanuptime is under $MAXUPTIMELIMIT Hours Limit / Script ENDS here ...";

:local PPPINTIP [ /ip address get [/ip address find interface=$PPPINT] address ]
:for i from=( [:len $PPPINTIP] - 1) to=0 step=-1 do={
:if ( [:pick $PPPINTIP $i] = "/") do={
:set PPPINTIP [:pick $PPPINTIP 0 $i]
:log warning "$PPPINT ip address is > $PPPINTIP"
}
}
}
}
}

Regard’s
Syed Jahanzaib


Filed under: Mikrotik Related

BASH Script to check modem status and alert by email/sms accordingly

$
0
0

teltonika

wavewcom

 

Disclaimer:

This is a neat hack to query modem status and alert admin if found Down. This is no way a standard method to perform this task but I used it as it worked fine for some specific environment. I made this because first , I was unable to find any good solution for this, second, making our customized solution is always far better then ready made tools. because with customization, we can get our desired results by folding/molding and twisting about anything that gets in our way :~)


SCENARIO!

Serial modem is attached to Linux (Ubuntu) system for sending receiving sms via locally installed KANNEL as gateway. Rarely sometimes modem stops responding to sms requests and it require physical power off/on. if system is not very actively monitored by admin, or remote administration is being done, then we require a solution that can alert us by EMAIL if modem stopped working. and when it start working again, send us Email+SMS for the event. But it should not repeatedly send sms/email for same incident.Some checks must be there in order to prevent this.


REQUIREMENTS!

1- Make sure you have WVDIALCONF utility before executing this script. you can install wvidalconf in UBUNTU by following command

sudo apt-get install wvdial

2- for Email part, I used sendEmail which will use GMAIL account to send email.To install it use

TO Install sendEmail Tool …

mkdir /temp
cd /temp
wget http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz
tar zxvf sendEmail-v1.56.tar.gz
cd sendEmail-v1.56/

ADD SUPPORTING LIBRARY

for ubuntu

apt-get -y install libio-socket-ssl-perl libnet-ssleay-perl perl
for centos
yum -y install perl perl-Crypt-SSLeay perl-IO-Socket-SSL

SOLUTION!

the SCRIPT

Schedule (cron) the following to run after every hour or as required.

 

Use following script.

#!/bin/bash
# Linux BASH script to check MODEM Status (example wavecom or teltnokia serial modem or any other using wvdialconf)
# If Modem not responding, then send SMS/EMail alert to admin (trigger one time for each status changed)
# Useful for remote admins, who want to be informed when modem have any responding problem.
# Created: 9th-JUNE-2016
# Syed Jahanzaib
# aacable at hotmail dot com / https://aacable.wordpress.com
# set -x

# If you have kannel configured, then STOP KANNEL SERVICE first, so that it should not conflict with the wvdialconf results / locked pid / syed.jahanzaib
# If you dont have kannel, remote these entries
echo "Stopping Kannel Service to test modem results and sleep for 10 seconds so that kannel service can be shutdown gracefully..."
service kannel stop > /dev/null 2>&1
sleep 10
killall -9 bearerbox > /dev/null 2>&1
echo "Kannel Service Stopped . Processing further ..."

# You can name your modem, MAKE SURE THAT YOU ***DONOT*** ADD SPACES IN IT
MODEM1="SERIAL_MODEM"

# Text that will be checked in wvdialconf output file, if wvdialconf does not detects any modem, it usually add the following line
# Sorry, no modem was detected! Is it in use by another program?
# So we will simply use the grep to catch word **no modem**. You may use other technique that may work for you. Chill / zaib
TEXT_TO_CATCH="no modem"

# Hostname and other Variables
HOSTNAME=`hostname`
COMPANY="zaib (Pvt) Ltd."
FOOTER="Powered By Syed.Jahanzaib"
DATE=`date`

# Temporary file holder for MODEM status
MODEM1_STATUS_TMP_HOLDER="/tmp/modemstatus.txt"
MODEM_QUERY_RESULT="/tmp/modem_query_result.txt"
# Create temp file if not already present, usually for 1st time execution
touch $MODEM1_STATUS_TMP_HOLDER
touch $MODEM_QUERY_RESULT

# SMS RELATED and KANNEL INFO
# KANNEL SMS Gateway Info, will not be useful when modem is down, however it will be ok when moem will respond,
# for down status, we have to use GMAIL to send email
KANNELURL="127.0.0.1:13013"
KANNELID="kannel"
KANNELPASS="KANNELPASS"
CELL1="03333021909"

# GMAIL Section
GMAILID="YOURGMAILID@gmail.com"
GMAILPASS="YOURGMAILPASS"
ADMINMAIL1="TO@hotmail.com"

# sms/email message temporary holder
MSGDOWNHOLDER="/tmp/$MODEM1_down.msg"
MSGUPHOLDER="/tmp/$MODEM1_up.msg"

## SMS/EMAIL Messages for DOWN
MSG_DOWN="ALERT: SMS $MODEM1 not responding @ $DATE. Try to restart it by power off/on.

$COMPANY
$FOOTER"

## SME/EMAIL Messages for UP
MSG_UP="INFO: SMS $MODEM1 is now responding @ $DATE OK.

$COMPANY
$FOOTER"

# RUN WVDIALCONF utility to output modem query result in $MODEM_QUERY_RESULT file
wvdialconf > $MODEM_QUERY_RESULT

# Run the script
echo "Checking $MODEM1 Current Status @$DATE..."
for MODEM in $MODEM1
do

# Match $TEXT_TO_CATCH in the query result
STATUS=`cat $MODEM_QUERY_RESULT | grep "$TEXT_TO_CATCH"`
if [ -n "$STATUS" ]; then

# Print Result for information purposes
echo "ALERT: text ** $TEXT_TO_CATCH ** found in $MODEM_QUERY_RESULT"
echo "$MODEM seems to be DOWN ..."

# IF modem found DOWN, and email/SMS not already sent, then send it one time to $CELL1/x
if [ $(grep -c "$MODEM" "$MODEM1_STATUS_TMP_HOLDER") -eq 0 ]; then
echo "$MODEM is down at $(date) .. SENDING DOWN SMS/EMAIL for current incident / for one time only ..."

# Update down message to be sent via sms/email
echo "$MSG_DOWN" > $MSGDOWNHOLDER

# Update Modem down status in a file so that sms/email should not be sent again and again
echo "$MODEM1" > $MODEM1_STATUS_TMP_HOLDER

#cat $MSGDOWNHOLDER

# Sending DOWN SMS via KANNEL
echo "Sending SMS , if modem is down, sms will not be sent ..."
cat $MSGDOWNHOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-

######## EMAIL SECTION ##############
# Make sure you install sendEMAIL tool and test it properly before using email section.
#SEND EMAIL Alert As well using sendEMAIL tool using GMAIL ADDRESS.
# If you want to send email , use below ...
echo "Sending SEMAIL ALERT to $ADMINMAIL1  ..."
/temp/sendEmail-v1.56/sendEmail -u "ALERT: $MODEM1 not responding @ $DATE" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$MSGDOWNHOLDER -o message-content-type=text
fi

# Else if $TEXT_TO_CATCH does not found in $MODEM_QUERY_RESULT, then consider MODEM is UP
else
echo "INFO: Word ** $TEXT_TO_CATCH ** was NOT found in $MODEM_QUERY_RESULT"
echo "$MODEM seems to be responding OK!"

# If modem found UP and last status was DOWN, then send UP msg one time
if [ $(grep -c "$MODEM" "$MODEM1_STATUS_TMP_HOLDER") -eq 1 ]; then
echo "$MODEM is now responding at $(date)... SENDING UP SMS for current incident one time only ..."
echo "$MSG_UP" > $MSGUPHOLDER
#cat $MSGUPHOLDER

# START KANEL SERVICE SO THAT UP INFO SMM CAN BE SENT to ADMIN
echo "Starting Kannel Services so that UP sms can be sent via kannel (with 5 seconds delay) ..."
service kannel start > /dev/null 2>&1
sleep 5

# Sending UP SMS via KANNEL
echo "Sending UP SMS , if modem is down, sms will not be sent ..."
cat $MSGUPHOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-

############## EMAIL SECTION ##############
# Make sure you install sendEMAIL tool and test it properly before using email section.
#SEND EMAIL Alert As well using sendEMAIL tool using GMAIL ADDRESS.
# If you want to send email , use below ...

echo "Sending SEMAIL UP/OK to $ADMINMAIL1 & $ADMINMAIL2 ..."
/temp/sendEmail-v1.56/sendEmail -u "INFO: $MODEM1 responding now OK @ $DATE" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$MSGDOWNHOLDER -o message-content-type=text

# Update Modem UP status in a file so that sms/email should not be sent again and again
sed -i "/$MODEM1/d" "$MODEM1_STATUS_TMP_HOLDER"
fi
fi
done

# START KANEL SERVICE IN END, because we stopped it in the beginning
echo "Starting Kannel Services that we stopped in beginning of this script ..."
service kannel start > /dev/null 2>&1

# Script Ends Here ...
# z@iB

RESULT!

1- DOWN result

Screenshot_2016-06-09-11-24-08

 


Filed under: Linux Related

KANNEL not responding problem occasionally or after modem reset

$
0
0

kannellogo


Scenario:

We have Ubuntu 12.x installed and serial modem is attached (Teltonika G10). Kannel is installed and serving as SMS gateway.

Problem:

Sometimes modem stops responding and when we restart the modem, kannel starts giving error of Routing Failed. After restart of KANNEL service, the kannel starts responding to sms request and works fine.

Requirement:

This little issue can be really annoyed if you are doing remote administration OR if sms alerts are important for you to keep informed about various aspects of the network. We want some automatic mechanism that can detect this specific error and then act accordingly.

Example …

  • If KANNEL service is down , try to start it
  • If failed to start the service, then print error, and sends email about incident, (one email per incident), and exit script
  • If service starts successfully, then print info, and sends email about successful attempt. (one email per incident), and continue further
  • Test Kannel log last entries, and look for word Routing failed, if found, then restart kannel service and email. (one email per incident).
  • If it does not found any entry in LOG for specific word, then Print OK Result for all.

Solution!

 

Disclaimer:

This may or may not work for you. Because I made it for some very particular situation, and this script helped. So this script checks for two things only. 1st kannel service, 2nd kannel log error for routing failed. I am sure this may or may not help you in same situation because its possible that error can be due to something else. I carefully examined my situation and made script for it. You can get some idea by it and modify the script as required.

Schedule Script to run after every 15 minutes or whatever.

Cron Example

# Run KANNEL MONITOR Script after every 15 minutes
*/15 * * * * /temp/kanneltest.sh

 


the SCript !

mkdir /temp
cd /temp
touch /temp/kanneltest.sh
chmod +x /temp/kanneltest.sh
nano /temp/kanneltest.sh

Copy paste following script. Make sure you read it carefully and modify things accordingly.


#!/bin/bash
# No part of this script is copied from anywhere, you are free to use it, modify or distribute.
# Linux BASH script to check KANNEL service Status and internal component system (example kannel service is ok,but not responding to request giving error in logs
# If KANNEL not responding, then send EMail alert to admin (trigger one time for each status changed)
# Useful for remote admins, who want to be informed when KANNEL have any responding problem.
# Created: 9th-JUNE-2016
# Syed Jahanzaib
# aacable at hotmail dot com / https://aacable.wordpress.com
#set -x
# Colors Config . . . [[ JZ . . . ]]
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"
# Service name to monitor ...
KANNEL="kannel"
KANNEL_SERVICE_ERROR="kannel_main_service_down"
KANNEL_BEARERBOX="bearerbox"
# Text that will be checked in kannel logs output file,
# So we will simply use the grep to catch word **Routing failed**. You may use other technique that may work for you. Chill / zaib
TEXT_TO_CATCH="Routing failed"
# Hostname and other Variables
HOSTNAME=`hostname`
COMPANY="zaib (Pvt) Ltd."
FOOTER="Powered By Syed.Jahanzaib"
DATE=`date`
# Temporary file holder for KANNEL status
KANNEL_STATUS_TMP_HOLDER="/tmp/KANNELstatus.txt"
KANNEL_SERVICE_TMP_HOLDER="/tmp/kannelservice.txt"
KANNEL_SERVICE_TMP_HOLDER_ERR="/tmp/kannel_servic_error.txt"
KANNEL_QUERY_RESULT="/tmp/KANNEL_query_result.txt"
KANNEL_LOG_FILE="/var/log/kannel/bearerbox.log"
# Create temp file if not already present, usually for 1st time execution
touch $KANNEL_STATUS_TMP_HOLDER
touch $KANNEL_SERVICE_TMP_HOLDER
touch $KANNEL_SERVICE_TMP_HOLDER_ERR
touch $KANNEL_QUERY_RESULT
# EMAIL RELATED and KANNEL INFO
# for down status, we have to use GMAIL to send email
KANNELURL="127.0.0.1:13013"
KANNELID="kannel"
KANNELPASS="KANNELPASS"
CELL1="03333021909"
# GMAIL Section
GMAILID="YOURGMAILID@gmail.com"
GMAILPASS="YOURGMAILPASS"
ADMINMAIL1="aacableAThotmail.com"

###########################################################################################
# Testing KANNEL Service bearerbox status by its PID
echo -e "$COL_RED
Step 1:$COL_RESET INFO: Testing $KANNEL Service status , testing its PID ..."
PID=`pgrep $KANNEL_BEARERBOX`
if [ -n "$PID" ]; then
echo -e "$KANNEL Service Status = $COL_GREEN OK $COL_RESET with pid $PID"
sed -i "/$KANNEL_SERVICE_ERROR/d" "$KANNEL_SERVICE_TMP_HOLDER"
else
echo -e "$COL_RED$KANNEL Service = NOT RUNNING, trying to restarting it ...$COL_RESET"
service $KANNEL stop > /dev/null 2>&1
sleep 5
killall -9 $KANNEL_BEARERBOX > /dev/null 2>&1
sleep 2
service $KANNEL start > /dev/null 2>&1
sleep 5
# IF KANNEL MAIN SERVICE found DOWN, and email/SMS not already sent, then send it one time to $CELL1/x
PID=`pgrep $KANNEL_BEARERBOX`
if [ -z "$PID" ]; then
KSRVAFTRES="DOWN"
echo -e "Script tried to restart $KANNEL MAIN SERVICE and final status is = $COL_RED $KSRVAFTRES $COL_RESET..."
else
KSRVAFTRES="UP/OK"
echo -e "Script tried to restart $KANNEL MAIN SERVICE and final status is = $COL_GREEN $KSRVAFTRES .$COL_RESET..."
if [ $(grep -c "$KANNEL_SERVICE_ERROR" "$KANNEL_SERVICE_TMP_HOLDER") -eq 0 ]; then
echo -e "$COL_RED Sending SMS/EMAIL for KANNEL MAIN SERVICE...$COL_RESET"
PID=`pgrep $KANNEL_BEARERBOX`
if [ -n "$PID" ]; then
KSRVSTATUS="UP/OK"
echo -e "$KANNEL sevice was not running, After script attempt to restart it, its status is $COL_GREEN $KSRVSTATUS $COL_RESET with PID $PID"
KSRVUPMSG="/tmp/ksrvup.msg"
echo "$KANNEL sevice was not running, After script attempt to restart it, its status is $KSRVSTATUS with PID $PID" > $KSRVUPMSG
/temp/sendEmail-v1.56/sendEmail -u "ALERT: $KANNEL service was not working and finally its $KSRVSTATUS @ $DATE" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$KSRVUPMSG -o message-content-type=text
else
KSRVSTATUS="DOWN"
echo -e "After kannel restart attempt, its status is still $COL_RED $KSRVSTATUS, $COL_RESET... SMS/EMAIL Already sent ..."
#Updating its down log, so script should not repeat sms/email sending
echo "$KANNEL_SERVICE_ERROR" > $KANNEL_SERVICE_TMP_HOLDER
fi
fi
fi
fi

###########################################################################################
# Testing again if above step have started the service or not , if not EXIT the script with the error
# Because if kannel is not running, then checking modem is useless, kannel must be running first in order to proceed further
PID=`pgrep $KANNEL_BEARERBOX`
if [ -n "$PID" ]
then
echo ""
else
echo -e "$COL_REDALERT ALERT: $KANNEL service failed to respond on Service restart request .... please check$COL_RESET
$COL_RED Script cannot continue, exiting ...$COL_RESET"
#exit 0
fi

############## zaib final down
PID=`pgrep $KANNEL_BEARERBOX`
if [ -z "$PID" ]; then
if [ $(grep -c "$KANNEL_SERVICE_ERROR" "$KANNEL_SERVICE_TMP_HOLDER_ERR") -eq 0 ]; then
KSRVSTATUS="DOWN"
KSRVDOWNMSG="/tmp/ksrvdown.msg"
echo "After kannel restart attempt by the script, its status is still $KSRVSTATUS. You need to check it manualy. Now only Human can see what is going on ... "
echo "After kannel restart attempt by the script, its status is still $KSRVSTATUS. You need to check it manualy. Now only Human can see what is going on ... " > $KSRVDOWNMSG
/temp/sendEmail-v1.56/sendEmail -u "ALERT: $KANNEL service failed to restart. Status = $KSRVSTATUS @ $DATE / Check it manualy!" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$KSRVDOWNMSG -o message-content-type=text
#Updating its down log, so script should not repeat sms/email sending
echo "$KANNEL_SERVICE_ERROR" > $KANNEL_SERVICE_TMP_HOLDER_ERR
exit 0
fi
else
sed -i "/$KANNEL_SERVICE_ERROR/d" "$KANNEL_SERVICE_TMP_HOLDER_ERR"
fi

###########################################################################################
PID=`pgrep $KANNEL_BEARERBOX`
if [ -n "$PID" ]
then
echo ""
else
echo -e "$COL_REDALERT ALERT: $KANNEL service failed to respond on Service restart request .... please check$COL_RESET
$COL_RED Script cannot continue, exiting ...$COL_RESET"
exit 0
fi

###########################################################################################
# Run the script to test kannel internal processing ...
echo -e "$COL_RED
Step 2:$COL_RESET
Testing Kannel internal Service Status in LOGS for internal responding @DATE ..."
for KANNEL in $KANNEL
do
# Match $TEXT_TO_CATCH in the log file grep query result
STATUS=`tail -n 10 $KANNEL_LOG_FILE | grep "$TEXT_TO_CATCH"`
if [ -n "$STATUS" ]; then
# Print Result for information purposes
echo "ALERT: text ** $TEXT_TO_CATCH ** found in $KANNEL_QUERY_RESULT"
echo -e "$COL_RED
$KANNEL service is UP but internal system is not responding to SMS ... Trying to restarting $KANNEL service ...$COL_RESET"
# IF KANNEL found DOWN, and email/SMS not already sent, then send it one time to $CELL1/x
if [ $(grep -c "$KANNEL" "$KANNEL_STATUS_TMP_HOLDER") -eq 0 ]; then
# Restart the KANNEL service
service kannel stop > /dev/null 2>&1
sleep 5
killall -9 bearerbox > /dev/null 2>&1
sleep 2
service kannel start > /dev/null 2>&1
sleep 5
echo -e "$COL_RED
$KANNEL service is UP but internal system is not responding $DATE .. SENDING DOWN SMS/EMAIL for current incident / for one time only ...$COL_RESET"
# Update KANNEL down status in a file so that sms/email should not be sent again and again
echo "$KANNEL" > $KANNEL_STATUS_TMP_HOLDER
# Sending DOWN SMS via KANNEL
echo -e "$COL_REDSending SMS , if KANNEL SERVICE is down or internal system not responding, SMS will NOT be sent ...$COL_RESET
"
# Update down message to be sent via sms/email
echo "$MSG_DOWN" > $MSGDOWNHOLDER
# sen email using sendemail tool
cat $MSGDOWNHOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
######## EMAIL SECTION ##############
# Make sure you install sendEMAIL tool and test it properly before using email section.
#SEND EMAIL Alert As well using sendEMAIL tool using GMAIL ADDRESS.
# If you want to send email , use below ...
echo -e "$COL_REDSending EMAIL ALERT to $ADMINMAIL1 ...$COL_RESET
"
/temp/sendEmail-v1.56/sendEmail -u "ALERT: $KANNEL not responding @ $DATE" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$MSGDOWNHOLDER -o message-content-type=text
fi

###########################################################################################
# Else if $TEXT_TO_CATCH does not found in $KANNEL_QUERY_RESULT, then consider KANNEL is UP
else
echo -e "$COL_GREEN
INFO:$COL_RESET Word ** $TEXT_TO_CATCH ** was NOT found in $KANNEL_LOG_FILE
$COL_RED
FINAL RESULT:$COL_RESET
$KANNEL service = $COL_GREEN OK $COL_RESET
$KANNEL iternal system = $COL_GREEN OK $COL_RESET / All seems to be responding OK!
"
# If KANNEL found UP and last status was DOWN, then send UP msg one time
if [ $(grep -c "$KANNEL" "$KANNEL_STATUS_TMP_HOLDER") -eq 1 ]; then
echo "$KANNEL internal system is now responding at $(date)... SENDING UP SMS for current incident one time only ...
"
echo "$MSG_UP" > $MSGUPHOLDER
# Sending UP SMS via KANNEL
echo -e "Sending $COL_GREENUP$COL_RESET SMS , if KANNEL process is down, sms will not be sent ...
"
cat $MSGUPHOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
############## EMAIL SECTION ##############
# Make sure you install sendEMAIL tool and test it properly before using email section.
#SEND EMAIL Alert As well using sendEMAIL tool using GMAIL ADDRESS.
# If you want to send email , use below ...
echo "Sending SEMAIL UP/OK to $ADMINMAIL1 & $ADMINMAIL2 ...
"
/temp/sendEmail-v1.56/sendEmail -u "INFO: $KANNEL internal system is now responding OK @ $DATE" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$MSGDOWNHOLDER -o message-content-type=text
# Update KANNEL UP status in a file so that sms/email should not be sent again and again
sed -i "/$KANNEL/d" "$KANNEL_STATUS_TMP_HOLDER"
fi
fi
done
# Script Ends Here ...
# z@iB


Script Results:

1- script execute result

 

1- srv down and restarted ok up result

 

1- srv down failed to restart

1-upndown

3 -intok


Regard’s
Syed Jahanzaib


Filed under: Linux Related

Sending Email/SMS Alert to User for Service Change Event

$
0
0

srvchange


Reference Notes:

Requirements:

We want to send email/sms alert to user about his service package change with old/new package name details. Although this function is builtin in RM , but with customized scripts we can do other functions as well.


Solution:

We will create mysql trigger that will be executed every time srvid column will be changed in rm_users table. then we will create mysql table which will hold all these info. Then the trigger will add user info like old service id , new service id, user name, mobile etc in this table upon srvid change.

Neat & clean.


 

First create mySQL trigger which will be executed once there will be changes made in srvid column in rm_users table.

1- mySQL Trigger

Create file name srvchangetriggers.sql and paste following data

-- MySQL dump 10.13 Distrib 5.5.46, for debian-linux-gnu (i686)
-- Host: localhost Database: radius
-- Syed Jahanzaib
-- ------------------------------------------------------
-- Server version 5.5.46-0ubuntu0.12.04.2-log
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `myTrigger` BEFORE UPDATE ON `rm_users`
FOR EACH ROW BEGIN
IF NEW.srvid <> OLD.srvid THEN
INSERT INTO rm_usersrvchangehistory (datetime, username, newsrvid, oldsrvid, firstname, lastname, mobile) VALUES (NOW(), new.username, new.srvid, old.srvid, new.firstname, new.lastname, new.mobile);
END IF;
END */;;
DELIMITER ;
-- Dumping routines for database 'radius'
--

2- mySQL Table

Add mySQL table where records will be saved.

Create file name rmsrvchangetable.sql and paste following date

-- phpMyAdmin SQL Dump
-- version 3.4.10.1deb1
-- http://www.phpmyadmin.net
-- Syed Jahanzaib
-- Host: localhost
-- Generation Time: Jun 13, 2016 at 10:32 AM
-- Server version: 5.5.46
-- PHP Version: 5.3.10-1ubuntu3.21
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `radius`
--
-- --------------------------------------------------------
--
-- Table structure for table `rm_usersrvchangehistory`
--
CREATE TABLE IF NOT EXISTS `rm_usersrvchangehistory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`datetime` datetime NOT NULL,
`username` varchar(64) NOT NULL,
`newsrvid` varchar(64) NOT NULL,
`oldsrvid` varchar(64) NOT NULL,
`firstname` varchar(64) NOT NULL,
`lastname` varchar(64) NOT NULL,
`mobile` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=63 ;
--
-- Dumping data for table `rm_usersrvchangehistory`
--
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Importing the .sql files in Radius DB / mySQL

Now import both files  in radius DB by command

mysql -uroot -pSQLPASS radius < rmsrvchangetable.sql
mysql -uroot -pSQLPASS radius < srvchangetriggers.sql

Test The Changes …

Now try to change any user service, and check rm_usersrvchangehistory by following command

root@ubuntu:/temp# mysql -u root -pSQLPASS -e "use radius; select * from rm_usersrvchangehistory;"
+----+---------------------+----------+----------+----------+-----------+-----------+-------------+
| id | datetime | username | newsrvid | oldsrvid | firstname | lastname | mobile |
+----+---------------------+----------+----------+----------+-----------+-----------+-------------+
| 71 | 2016-06-13 12:24:00 | test | 4 | 13 | syed | jahanzaib | 03333021909 |
+----+---------------------+----------+----------+----------+-----------+-----------+-------------+

Script to fetch data on scheduled basis and SMS/EMAIL…

Create a script that will be scheduled to run after every 5 minutes , it will check in table rm_usersrvchangehistory and will send sms to user about package change event.

mkdir /temp && cd /temp
touch /temp/srvchange.sh
chmod +x temp/srvchange.sh
nano temp/srvchange.sh

and paste following data…

the Script:


#!/bin/bash
# srvchange.sh
# Bash script which will run after every 5 minutes and will fetch info from mysqltable
# and will send SMS/Email alert for service change event.
# Created by SYED JAHANZAIB
# aacable@hotmail.com
# https://aacable.wordpress.com
# Created : 13-JUN-2016
#set -x
SQLUSER="root"
SLQPASS="SQLPASS"

# File where user info wil be hold temporary
TMPUSRINFO=/tmp/usersrvinfo.txt

# Interval in minutes to check user record
INTERVAL="5"

# Fetch user info from the table.
mysql -uroot -p$SQLPASS --skip-column-names -e "use radius; select * from rm_usersrvchangehistory WHERE datetime >= NOW() - INTERVAL $INTERVAL MINUTE;" > $TMPUSRINFO

# KANNEL DETAILS
KHOST="127.0.0.1:13013"
KID="kannel"
KPASS="kannelpass"

# Company Footer
COMPANY="JZ_ISP"

# Apply Count Loop Formula while deleting first line which have junk text
num=0
cat $TMPUSRINFO | while read users
do
num=$[$num+1]
username=`echo $users | awk '{print $4}'`
firstname=`echo $users | awk '{print $7}'`
lastname=`echo $users | awk '{print $8}'`
mobile=`echo $users | awk '{print $9}'`
date=`echo $users | awk '{print $2,$3}'`
newsrvid=`echo $users | awk '{print $5}'`
oldsrvid=`echo $users | awk '{print $6}'`

# Print Info on screen
# Fetch old/new Package Name
OLDPKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$oldsrvid';" |awk 'FNR == 2'`
NEWPKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$newsrvid';" |awk 'FNR == 2'`

# Print FINAL Fetched info
echo "Dear $firstname $lastname ,
Your internet package against your User ID: $username has been upgraded from $OLDPKGNAME to $NEWPKGNAME !

$COMPANY"

# Store Info for sending SMS in /tmp folder where we will call kannel to send customized SMS
echo "Dear $firstname $lastname ,
Your internet package against your User ID: $username has been upgraded from $OLDPKGNAME to $NEWPKGNAME !

$COMPANY" > /tmp/$username.srvchange.sms

# send sms using kannel gateway
curl "http://$KHOST/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$mobile" -G --data-urlencode text@/tmp/$username.srvchange.sms

# If you send lot of SMS via local mobile SIM, then make sure you give enough delay so that your SIM may not get blocked by BULK SMS monitor by TELCOM authority like PTA.
#sleep 15
done
# once done, we should delete the .sms files to clear the garbage
rm -fr /tmp/*.sms


End Results !

Now execute the Script  and witness the Fun !

srvchange


Regard’s
Syed Jahanzaib


Filed under: Radius Manager

CRON examples ! Focus and save yourself from embarrassment !

$
0
0

cron examples

 

To add scheduled job in linux/ubuntu, use

crontab -e

To view installed cron

crontab -l

Examples:

Run Script at Every 1st day of Month.

@monthly /temp/script.sh

Run Script Daily at 00:00 hours (midnight)

@daily /temp/script.sh

Run Script every hour 

@hourly /temp/script.sh

Run Script every minute

* * * * * /temp/script.sh

Run Script after every 5 minutes

*/5 * * * * /temp/script.sh

Run Script on Specific Timings And Date of Months, Example run script on 10am and 11am  on 12th of every month.

00 10,11 12 * * /temp/script.sh

Run Script on Specific Hours of Every Month, Example run script on 9am of every month.

00 9 10 * * /temp/script.sh

Run Script on Specific Hours RANGES , Example run script on 10am to 8pm , means every hour from 10am-8pm

00 10-20 * * * /temp/script.sh


Shortcuts in CRON

@reboot        Run once, at startup.
@yearly        Run once a year, "0 0 1 1 *".
@annually      (same as @yearly)
@monthly       Run once a month, "0 0 1 * *".
@weekly        Run once a week, "0 0 * * 0".
@daily         Run once a day, "0 0 * * *".
@midnight      (same as @daily)
@hourly        Run once an hour, "0 * * * *".


 


Filed under: Linux Related

MRTG graph 120M Limitation

$
0
0

mrtg


If you are using MRTG and have gigabit network, you may notice that mrtg graphs will not show you traffic above then 120mb.  This is a common problem caused by 16-bit counter rollover. By default MRTG polls the device every 5min using SNMPv1, then a traffic greater than 120 Mbps will cause the 16 bit counter to wraparound in this time window.

therefore , MRTG only displays the lower traffic as it cannot tell how many times the counter has rolled over.

There are two workarounds to over come this issue.

  1. SNMP V2
  2. RRD

Quick Workaround:

I used SNMPv2. This is the best option, if your device supports it (Mikrotik do support SNMP v2). If using SNMPv2, then you can use the 64bit counters, which will not wrap around.

To do this, add

:::::2

(5 semicolons and 2) as a suffix to your Target definition to specify SNMPv2.


Working Example:

To edit existing configuration file.

Target[10.0.0.1_eth0]: #eth0:public@10.0.0.1:::::2

or with cfgmaker

cfgmaker public@10.0.0.1:::::2

I will write on RRD later which is the best option in my opinion , specially for heavy networks.

Regard’s
Syed Jahanzaib


Filed under: Linux Related

Routing & Natting with Failover ! Brothers in Arms

$
0
0

natro

~ Mikrotik CCR.1036 Performance Statistics ~

ccrload

 

mrtg


Reference Notes:

Mikrotik is a very powerful router that can perform variety of functions in one box. Sometimes It’s fun to do complex configuration with customized scriptings to achieve our desired results. I just wanted to share some thoughts on one scenario where I configured multiple WAN links with PCC config plus public ips routing for users in single CCR RB. Routing+Natting+Firewalling+QOS+Scriptings and much more all together. Later we added failover so that if pcc wan links fails it should switch to fiber link, and if fiber link fails, it should failover to dsl by blending public ips into PCC.

  • Mikrotik have 4 DSL links which are configured in PCC (Load balancing) and serving local pppoe clients.
  • We have added another WAN Link via Fiber which is 1 STM (155mbps) and have acquire another large public pool for users which is routed to our /29 ip on mikrotik.
  • We have configured services in such a way that normal users gets private ip upon pppoe connectivity, and goes via PCC/Natting. and few services are configured in such a way that user gets public ip and goes to internet via public ip Routing, (bypass natting, preserving his public ip)
  • We have configured VLANs to isolate the different areas/networks to minimize the broadcast and for better network management. Also some corporate clients are connected to separate vlans to provide them public ip pool to be used in there routers.
  • We connected some corporate clients, which of course should not be connected via pppoe method, they wanted direct public ip so they can configure it in there own router/system. So we did it by connecting that client on our vlan switch,TAG there port traffic, and on mikrotik we added new vlan interface (accordingly ) and assign public ip (as required like /30) and assigned it to this new vlan interface, and gave appropriate ip to the client.
  • We have configured FAILOVER by using following techniques
  • 4 vdsl links are configured as PCC. For fail over we are using script that monitor 2 internet hosts for each wan link. we have also created forced route for those hosts with black holes as well to make sure the hosts goes via specific wan link only. once the script failed to ping those 2 hosts, it will simply enable rule in (ip/route/rules) TABLE to lookup the speciifc wan marked packets via main table where fiber link have distance value of 1 which will be default rule. thus traffic for that failed dsl link will start natting via fiber link. of course there are various other measurements need to be done, like proper natting rules, etc.
  • For fiber fail over (public ips) to dsl, we have script that checks for 2 hosts, if it fails, it will simply add the public ip pool to pcc pool as well, so the public pool also starts mixing with the pcc quern😀
  • CCR performed amazingly good with complex configuration , lots of dynamic queues, and CPU usage usually remains under 10%. We can use PCQ base queues to lower the cpu usage in specific circumstances.
  • QOS is dynamically Done by the radius billing system. In this case DMASOFTLAB Radius Manager.
  • FTP are in DMZ, controlled by Mikrotik Firewall and separate QOS are setup to provide each user with 4 MB of downloads from local media server. This is done to prevent over utilization by each user. I used Queue type and then tag it with the simple queue for FTP. I also marked packets in mangle going to FTP, then later used in queues.
  • There are few other scripts configured like daily backup script, wan monitoring scripts, etc.
  • DDNS is also configured to access mikrotik and other servers/devices behind the MT, to pass through via PCC. port forwarding with the PCC is a bit tricky, and it requires additional rules in mangle and routes. I wrote about it in details in other posts.
  • Lot of port forwarding:)
  • Filter rules to block DDOSER, Block PING access ,Port Scanning etc…

 


Regard’s

Syed Jahanzaib


Filed under: Mikrotik Related

Bash script to update ‘simultaneous-use’ attribute value in BULK

$
0
0

mysql

Use following script if you want to change ‘Simultanous-Use‘ attribute value for *ALL* users.
I made it for a specific situation and was very successfull.

  • It will check for mysql service running status
  • then it will check mysql radius DB if its accessible ro not,
  • then it will update the attribute value that we define in the script.

All is customizable, do it as per your requirements.


the Script !

#!/bin/bash
# Script to update 'Simultanous-Use' attribute for ALL USERS of radius database 'radcheck' in mysql.
# It was useful in a specific situation.
# 20-Jun-2016
# Syed Jahanzaib
# https://aacable.wordpress.com aacable at hotmail dot com
#set -x
SQLUSER="SQL-USER"
SQLPASS="SQL-PASSWORD
TMPFILE="/tmp/simupdate.txt"
VALUE="2"
DB="radius"
SRV="mysql"
# Check if $SRV (in this case mysql) is running or not, if NOT, then exit the script
SRVSTATUS=$(pgrep $SRV | wc -l);
if [ "$SRVSTATUS" -ne 1 ];
then
echo "-$SRV is down. Pleasec check your $srv service first.
Exiting ...";
exit 1
else
echo "-$SRV is accessible OK. Proceeding further ..."
fi
# Check if $DB (in this case radius ) is accessible or not, if NOT, then exit the script
RESULT=`mysql -u $SQLUSER -p$SQLPASS --skip-column-names -e "SHOW DATABASES LIKE '$DB'"`
if [ "$RESULT" == "$DB" ]; then
echo "-$DB database exist OK. Proceeding further ..."
else
echo "-$DB database does not exist!"
exit 1
fi

# Fethch the ID of simultanous-use attribute
mysql -u$SQLUSER -p$SQLPASS -e "use radius; select * from radcheck;" | grep Simult | awk '{print $1}' > $TMPFILE
echo "
Updating $SRV / $DB table . . ."
# Fetch ID from radcheck table for SIMULTANOUS-USE check
num=0
cat $TMPFILE | while read users
do
num=$[$num+1]
ID=`echo $users | awk '{print $1}'`
mysql -u$SQLUSER -p$SQLPASS -e "UPDATE radius.radcheck SET value = $VALUE WHERE radcheck.id = $ID;"
done
echo "
Script End. All Done"
# END

Filed under: Linux Related

Retrieve User Old/Original Password in RM

$
0
0

lostpass

Please beware that this post is just for Example purpose Only. In real production environment you must be very careful for providing such option. Make it tightly secure, add captcha code & provide this feature to requesting users only. AVOID using bash, RELY on PHP !


As requested by an client, Following is an script that can retrieve user’s current current password from 'radcheck' table. This method is useful in some situation where operator dont want to change the password for user, but to provide them there old/original password.

  • In RM, user’s password are encrypted with MD5. which is a Digest algorithm. Think of it as converting a cow into a steak. Now try to reverse that:)
  • There are some online MD5 decrypter, but they can decrypt general or common words. If you have something complex password, it wont be able to decrypted.

So rather then getting into MD5 decryption mess, why not retrieve it under the table😉 by getting it from radcheck table.

There are few methods we can provide ‘current password retrieval’ funcion to user.

  1. We can configure playSMS to receive incoming SMS from user with specific command and username, then the system can retrieve user current password and sms to his Registered mobile number.
  2. Or we can make a simple PHP page where user can enter his user ID and then the system can send password to his Registered Mobile No. and Email address.

the Script ! [SAMPLE]

#!/bin/sh
#set -x
SQLUSER="SQL_USER"
SQLPASS="SQL_PASSWORD"
COMPANY="MyCompany"
CURDATE=$(date +"%Y-%m-%d")
echo $1 > /tmp/rawdata.txt
USERNAME=`cat /tmp/rawdata.txt |awk '{print $1}'`
echo ""
PASS=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select value from radcheck where username = '$USERNAME';" | awk 'FNR == 1'`
echo "Dear $USERNAME,

Your Password is $PASS

Regard's
$COMPANY"

Execute the script and see the result.

shpass


PHP Form base method using Shell Script !

f1

f2

 

Sample php/shell files uploaded to

https://drive.google.com/folderview?id=0B8B_P2ljEc2xSndud0hDV29HT2s&usp=sharing&tid=0B8B_P2ljEc2xcEdkd2ttV1ZmNFU

Make sure you add good security measurements first !

 

Regard’s
Syed Jahanzaib

 


Filed under: Radius Manager

RM: Auto Renew User if Deposit available

$
0
0

AutoRenewal

Revision History:
24-Jun-2015 / Added Base Script
29-Jun-2016 / Added Invoice function / Fixed bug if user quote is under 1 GB limit / few minor tweaks

As requested by an Valenzuela client.

In radius manager, there are few options to purchase credits via online payment gateways like paypal or others. If the user account is expired and he purchase service online, it adds the deposit into user account but it does not auto renew the service (as per my assumption, as paypal doesn’t works here in pakistan, so i have very little to no knowledge on it).

Example:

err

 

To make a workaround for this issue, I made a script that does the following.

  1. Scheduled to run after every 10 minutes
  2. Fetch users lists from rm_users table who have DEPOSIT available (credits above then 0)
  3. Check user account status , if Active Ignore it ,
  4. Else if expires, check the current service price and match it with the available deposit/credits,
  5. If deposit is not sufficient, then print error and exit,
  6. if deposit is enough, renew the service , add 30 days to service, add quota if any and sends email/sms to user about the renewal done by deposit : )

Disclaimer: The script can further be customized according to the requirements. No part of this script is copied from anywhere. You are free to use it, modify it as you like.This is my own idea Just to share with anyone who is in similar need or just for learning purposes !


SCRIPT!

#!/bin/bash
# Script to renew user account via check deposit and act accordingly
# For Radius Manager 4.1.x
# Created by Syed Jahanzaib
# https://aacable.wordpress.com / aacable@hotmail.com
# 24th Jun, 2016 , 18 Ramazan, 1437 Hijri
#set -x
# Colors Config . . . [[ JZ . . . ]]
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_YELLOW=$ESC_SEQ"33;01m"
COL_GREEN=$ESC_SEQ"32;01m"
SQLUSER="root"
SQLPASS="zaib1234"
USERLIST="/tmp/deposituserlist.txt"
#Create list of users which ahve deposite more then 0.00 value, means valid deposite
mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT username, credits FROM rm_users where credits > '0.00';" > $USERLIST
#LOOK FOR VALID USER IN FILE, IF EMPTY THEN EXIT
USRVALID=`cat $USERLIST`
if [ -z "$USRVALID" ]; then
echo -e "ERROR: NO USER FOUND for matching ... exiting!"
exit 0
fi
# Apply Formula to read the file in which users list and act accordingly.
num=0
cat $USERLIST | while read users
do
num=$[$num+1]
USR=`echo $users | awk '{print $1}'`
DEPOSIT=`echo $users | awk '{print $2}' | sed 's/\..*$//'`
######################
# ACCOUNT EXPIRY CHECK and other variables
######################
TODAY=$(date +"%Y-%m-%d")
TODAYDIGIT=`echo $TODAY | sed -e 's/-//g'`
MONTH=$(date +"-%m")
CMONTH=`echo $MONTH | sed -e 's/-//g'`
MONTHYEAR=$(date +"%B-%Y")
ALPHAMONTHYEAR=`echo $MONTHYEAR #| sed -e 's/-//g'`
SRVEXPIRYFULL=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2'`
FULLNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname, lastname FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2'`
MOBILE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT mobile FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2'`
COUNTRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT country FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2'`
STATE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT state FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2'`
ADDRESS=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT address FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2'`
SRVEXPIRYFULLD=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$USR';" |awk '{print $1}' | sed 's/expiration//'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2' | sed -e 's/-//g' | sed 's/00:.*//'`
NEXTEXPIRYADD=$(date +"%Y-%m-%d" -d "+30 days")
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$USR';" |awk 'FNR == 2 {print $1,$2}'`
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$USR';" |awk 'FNR == 2 {print $1}'`
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`
#LOOK FOR USER ACTUAL SERVICE NAME
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Look for Pakacge Quota trafficunitcomb
PKGQUOTA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT trafficunitcomb FROM rm_services WHERE srvid= '$SRVID';" |awk 'FNR == 2'`
PKGQUOTAB=$(($PKGQUOTA / 1024))
PKGQUOTABYTES=$(($PKGQUOTA * 1024 * 1024))
LASTUSRBAL=$(($DEPOSIT - $SRVPRICE))

TIMEUNITEXP=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT timeunitexp FROM radius.rm_services WHERE srvid = '$SRVID';"`
TIMEBASEEXP=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT timebaseexp FROM radius.rm_services WHERE srvid = '$SRVID';"`

if [ "$TIMEBASEEXP" == "2" ]; then
EXPERIOD="$TIMEUNITEXP Days"
#echo "$EXPERIOD"
fi
# Set Quota Limit variable which will be used in the end
if [ "$TIMEBASEEXP" == "3" ]; then
EXPERIOD="$TIMEUNITEXP Month"
#echo "$EXPERIOD"
fi

#######zzzzzzzz#timebaseexp
# Set Expiry Date/Month Unit
if [ $PKGQUOTA -eq 0 ]
then
QT="UNLIMITED"
else
QT="$PKGQUOTA MB"
fi


# Check Service Expiry Date, if Active then ignore
if [ $SRVEXPIRY -gt $TODAYDIGIT ]; then
echo -e "$COL_GREEN User Account = $USR | ALREADY ACTIVE | TIMEUNIT = $EXPERIOD | Expiry Date = $SRVEXPIRYFULLD | User Deposit Available = $DEPOSIT | Pacakge Price = $SRVPRICE PKR | Next Expiry = $NEXTEXPIRYADD | Quota = $QT $COL_RESET
"
else
########### ACCOUNT STATUS EXPIRED BUT NOT ENOUGH DEPOSIT to RENEW ACTION ############
if [ "$DEPOSIT" -lt "$SRVPRICE" ]; then
echo -e "$COL_RED User Account = $USR | TIMEUNIT = $EXPERIOD | ERROR: Account was expired on $SRVEXPIRYFULLD but user $USR DOES NOT HAVE ENOUGH DEPOSIT IN USER ACCOUNT! Current Deposite is $DEPOSIT and Required is $SRVPRICE $COL_RESET
"
else
########### ACCOUNT STATUS EXPIRED and DEPOSIT IS ENOUGH TO RENEW ACTION ############
if [ $SRVEXPIRY -lt $TODAYDIGIT ] || [$SRVEXPIRY -eq $TODAYDIGIT ]; then

# RENEW USERS IF ALL CONDITIONS MATCHED / PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo -e "$COL_YELLOW User Account = $USR ** RENEWING NOW ** | TIMEUNIT = $EXPERIOD | Expiry Date = $SRVEXPIRYFULLD | User Deposite Available = $DEPOSIT | Pacakge Price = $SRVPRICE PKR | Next Expiry = $NEXTEXPIRYADD | Quota = $QT $COL_RESET
Now Balance is = $LASTUSRBAL PKR"

# ADD 30 DAYS VALUE TO EXPIRED USER ACCOUNT
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET expiration = '$NEXTEXPIRYADD' WHERE username = '$USR';"
# ADD COMMENTS
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET comment = 'This account was last refresh from DEPOSIT $DATE' WHERE username = '$USR';"
# ADD SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), 'n/a', 'DEPOSIT_$USR', '$USR', '$USR renewd service > $PKGNAME');"
# UPDATE User Balance
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET credits = '$LASTUSRBAL' WHERE username = '$USR';"
# ADD INVOICE
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, date, bytesdl, bytesul, bytescomb, downlimit, uplimit, comblimit, time, uptimelimit,
 days, expiration, capdl, capul, captotal, captime, capdate, service, comment, transid, amount, invnum,
 address, city, zip, country, state, fullname, taxid, paymentopt, paymode, invtype, paid, price, tax, remark,
 balance, gwtransid, phone, mobile, vatpercent )
 VALUES
 ('admin', '$USR', NOW(), '0', '0', '$PKGQUOTABYTES', '0', '0', '$PKGQUOTABYTES', '0', '0', '30', '$NEXTEXPIRYADD', '0', '0', '1', '0', '1', '$PKGNAME', 'This user service renewed by Deposit/Payment', '577343812eee0', '1', '2016-0021', '$ADDRESS', '$CITY', '00000', '$COUNTRY', '$STATE', '$FULLNAME', 'n/a',
 DATE_ADD(CURDATE(), INTERVAL '10' DAY), '0', '0', '$TODAY', '$SRVPRICE', '0.000000', '', '$LASTUSRBAL', '', '$MOBILE', '$MOBILE', '0.00' );"

mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, amount, price, tax, vatpercent, balance,
 date, service, paymode, invgroup, paymentopt, transid)
 VALUES ('admin', 'admin', 1, '-$SRVPRICE', '0', '0.00',
 '', NOW(), 'Ref.: C-$TODAY', '2', '1', DATE_ADD(CURDATE(), INTERVAL '10' DAY),
 '577343812eee0' );"

# UPDATE Quota limitations if any, else ignore
if [ "$PKGQUOTA" -ne 0 ]; then
echo "Adding $PKGQUOTA MB Quota Limit for $USR as well
"
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET comblimit = '$PKGQUOTABYTES' WHERE username = '$USR';"
else
echo "No need to add quota"
fi
fi
fi
fi
done
# THE END SCRIPT ENDS HERE #
# SYED JAHANZAIB

RESULT!

1


 


Filed under: Radius Manager

Postfix as GMAIL relay to send email

$
0
0

postfix-logo


This post was made to illustrate howto send emails via postfix mail server using Gmail. Previously I was using sendmail with gmail in combination but few times sendmail made troubles in new installation, therefore i switched to postfix which is quite simple as compared to sendmail complexity. I have tested it at various networks and so far found it reliable.

It can be used by other mail applications like mail utility, radius manager web bulk mail function, or any other you like.  We will use GMAIL as relay to send our emails using our gmail account. You need functional gmail account for this purpose, and make sure ‘allow less secure application’ is turned on to availe this function.

TIP:
We can also use this as centralized email server gateway so that all of our devices on the LAN like Mikrotik Router, Cisco Switches, Mobile Devices and others can send via this email gateway so that we can get rid of configuring email services at each system separately.

That’s why in some specific situation, I say “Work Smarter, Not Harder” / Za!b


Software Used:

OS : Ubuntu 12.4 / 32bit
Email Server : POSTFIX 2.9.6

Let’s Start …

First we need to update ubuntu apt-get and then install the postfix mail server application

Step#1

apt-get update && apt-get install postfix mailutils libsasl2-modules

When prompted for “General type of mail configuration” choose Internet Site.
When prompted for a “Mail name,” you can use default name.

Once above installation is done,

Create and edit new file which will store the Gmail ID and Password

touch /etc/postfix/sasl_passwd
nano /etc/postfix/sasl_passwd

and paste following [Make sure you replace YOURGMAILID+YOURPASS with valid gmail credentials.

[smtp.gmail.com]:587 YOURGMAILID@gmail.com:YOURPASS

Save & Exit.

Step#2

Now Make it accessible for root

chmod 600 /etc/postfix/sasl_passwd

Step#3

Edit postfix main configuration File by

nano /etc/postfix/main.cf

Remove all previous lines and paste following ….

#Postfix main configuration file / Syed Jahanzaib / aacable at hotmail dot com / http:// aacable . wordpress . com
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
append_dot_mydomain = no
readme_directory = no
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
myhostname = radius.localhost
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = radius.localhost, localhost.localhost, , localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Save & Exit.

Step#4

Use postmap command to compile and hash the contents of sasl_passwd. The results will be stored in your Postfix configuration directory in the file sasl_passwd.db.

postmap /etc/postfix/sasl_passwd

Step#5

Create folder to hold mails

mkfifo /var/spool/postfix/public/pickup

Step#6

Change the FROM address. It will be displayed at user inbox.

chfn -f 'YOUR COMPANY NAME' root

Step#7

Make sure you have Enable “Less Secure Apps” In Gmail
https://www.google.com/settings/security/lesssecureapps

Step#8

If sendmail was previously installed, then remove it and stop its service

apt-get remove sendmail
service sendmail stop

Step#9

Finally Restart POSTFIX service

sudo /etc/init.d/postfix restart

FINAL Step#10 / TESTiNG the Ride !

Now try to send email by using command in the terminal, change the email address to your email address

mail -s "Test subject from postfix by Syed.Jahanzaib" aacable@hotmail.com

After this it will ask cc: , just press enter
it will show blank cursor where you can type the email body, type it any text or leave it blank , then press press CTRL+D to finally send the email

Now at the same time in other window, Check mail log for any error

tail -f /var/log/mail.log

psotfix log

 

Result:

3


Filed under: Linux Related
Viewing all 408 articles
Browse latest View live