Syed Jahanzaib Personal Blog to Share Knowledge !

June 28, 2016

RM: Auto Renew User if Deposit available

Filed under: Radius Manager — Tags: , — Syed Jahanzaib / Pinochio~:) @ 11:04 AM

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


 

June 22, 2016

Retrieve User Old/Original Password in RM

Filed under: Radius Manager — Tags: — Syed Jahanzaib / Pinochio~:) @ 10:44 AM

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

 

June 20, 2016

Routing & Natting with Failover ! Brothers in Arms

Filed under: Mikrotik Related — Tags: — Syed Jahanzaib / Pinochio~:) @ 1:39 PM

natro

~ Mikrotik CCR.1036 Performance Statistics ~

4vdsl-1fiber

 

 

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 scripting 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+Fire-walling+QOS+Scripting 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 (100mb each) 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…

 


TIPS for running NATING and ROUTING TOGETHER ~

Updated: 21-Sep-2016

As few asked how to run both natting and routing together in one router, here are few tips, (as I cannot post whole configuration because every network is different so rather then getting the code, try to understand the logic and apply it on your network if required)

Example:

We have Mikrotik RouterOS with 4 DLS(100mb x 4) links plus 1 Fiber Link (1 STM bandwidth) on /30 pool and two separate /24 pools (routed to /30 pool via ISP) for user end. We also have freeradius billing system where all users account / billing is managed. Mikrotik is acting as NAS / PPPoE Server as well.

Now we want that default normal group of clients should use these 4 dsl via PCC (using src-address approach as its more stable and have no ip changing issue) and selected group of users should get public ip and go directly via routing (while preserving their own public ip). here how I did this.

on Mikrotik I have defined two pools. One for the normal clients that will be natted using PCC. and other pool with public IP’s for users that will be routed.

1- pppoe_private_pool / 172.16.0.1-172.16.10.255
2- pppoe_public_pool / 123.0.0.1-123.0.1.255

In Mikrotik pppoe server, default pool for users is pppoe_private_pool (172.16.0.1-172.16.10.255) so any client connects to pppoe server will get ip from 172.16.x.x series. in PCC Mangle rules I defined 172.16.0.1-172.16.10.255 in src-address , this way only clients with these ip series will be processed via PCC and will go via dsl links. Same I did for default NAT rules, I defined this private pool in NAT src-address as well, This is must other wise all users will be natted (private or public). So make sure you pay attention to this portion.

Now to route public ips, I add the route of Fiber link ISP Gateway as Default route with distance value of 1 (all other routes of PCC have values of 2,3,4,5 (default routes for pcc / dsl is not required because they already have routes with marked traffic, but I still created default routes on dsl with different distance values to avail failover if one dsl fail , other should take over auto using MAIN TABLE) .

Then in radius panel, I created new services with pool defined “pppoe_public_pool”. and assign this profile to users whom I wanted to get public ip. this way when these particular users connects, they gets public IP, and they don’t processed by NAT rules and straightforward goes via routing table 🙂

Z@ib

 


Regard’s

Syed Jahanzaib

MRTG graph 120M Limitation

Filed under: Linux Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 11:00 AM

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

June 13, 2016

CRON examples ! Focus and save yourself from embarrassment !

Filed under: Linux Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 3:07 PM

cron examples

 Following commands are made for reference purposes only … zaib


To add scheduled job in linux/ubuntu, use

crontab -e

To view installed cron

crontab -l

Examples:

Run Script after every 5 seconds [Updated 8th Aug, 2016]

I had a UPS monitor script that should run after every 5 seconds to poll the KE input voltage / battery remaining time etc. but as we know that with CRON we can configure interval of minimum 1 minute or above, we cannot set time in seconds. so I make following workaround.

conrtab -e

and added script as follows

# UPMON.SH is my script to monitor UPS
# 10.0.0.1 is my UPS network card
* * * * * /temp/upsmon.sh 10.0.0.1
* * * * * sleep 5; /temp/kemon.sh 10.0.0.1
* * * * * sleep 10; /temp/kemon.sh 10.0.0.1
* * * * * sleep 15; /temp/kemon.sh 10.0.0.1
* * * * * sleep 20; /temp/kemon.sh 10.0.0.1
* * * * * sleep 25; /temp/kemon.sh 10.0.0.1
* * * * * sleep 30; /temp/kemon.sh 10.0.0.1
* * * * * sleep 35; /temp/kemon.sh 10.0.0.1
* * * * * sleep 40; /temp/kemon.sh 10.0.0.1
* * * * * sleep 45; /temp/kemon.sh 10.0.0.1
* * * * * sleep 55; /temp/kemon.sh 10.0.0.1
* * * * * sleep 60; /temp/kemon.sh 10.0.0.1

this way the script will run and wait for five seconds before next execution. 🙂 lalalala / zaib


Run Script at Every 1st day of Month [Every Month]

@monthly /temp/script.sh


Run Script on 1-am on every Monday

0 1 * * MON /temp/xdrive_noupdate.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 * * * *".


Scheduled CON Job running but not producing results …

[Monday 27th Feb,2017]

I scheduled few scripts on my Ubuntu 14.x box that queries remote servers for storage and send customized reports via email. I can see its execution in /var/log/syslog but the script was not able to query the remote win server.

To solve it I had to add the PATH command in the script , sample as below…

#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/temp

this solved the issue 🙂

These are little things that you learn on daily basis ,


Regard’s
Syed Jahanzaib

Sending Email/SMS Alert to User for Service Change Event

Filed under: Radius Manager — Tags: — Syed Jahanzaib / Pinochio~:) @ 12:58 PM

srvchange

 

Screenshot_2016-06-13-12-56-48

SMS Alert


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

KANNEL not responding problem occasionally or after modem reset

Filed under: Linux Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 10:22 AM

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

June 9, 2016

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

Filed under: Linux Related — Tags: , , , , , , — Syed Jahanzaib / Pinochio~:) @ 12:31 PM

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

 

June 8, 2016

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

Filed under: Mikrotik Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 12:36 PM

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

Older Posts »

%d bloggers like this: