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

Sharing Ideas … Get User Account Info via SMS in Radius Manager

$
0
0

userinfo

usereinfo

Changelog:

  • Removed bug , when user have not used any data or account is new, script returns NULL errors
  • Added Online / Offline Status

1- TASK

The task was to provide user a method to inquire his/her account information via sending SMS in specific format to the Billing system.

In this example, we are using DMASOFTLAB Radius Manager as our billing system, and KANNEL along-with the playSMS is already configured and in working condition. kannel+playSMS configuration details have already been described briefly with examples in my previous posts.

We have created an script on the billing system which fetches the user account status and other information from the MYSQL database and print them as per our defined format.

This is just for demonstration purpose. the script have lot of junk data and should be modified before production deployment. I am just sharing some thoughts and ideas only :)

Script is as follows FYR. Hope it may help someone :$

cat userinfo.sh

#!/bin/bash
# Script to check Radius Manager Status , Expiry Date, Service Plan, Data Used
# Syed Jahanzaib
# aacable @ hotmail.com
# https://aacable.wordpress.com
# Modified on 3rd June, 2015

# MYSQL USER NAME AND PASSOWRD Variables
SQLUSER="root"
SQLPASS="zaib1234"
CURRENCY="PKR"

# Check User Validation, if not found exit with error , else continue
echo
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT * FROM radius.rm_users WHERE rm_users.username = '$1';"`
if [ "$USRVALID" == "" ]; then
echo -e "USER NOT FOUND !"
else

######################
# ACCOUNT EXPIRY CHECK
######################

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 = '$1';" |awk 'FNR == 2'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2' | sed 's/00:.*//' | sed -e 's/-//g'`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$1';"  |awk 'FNR == 2 {print $1,$2}'`

if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
        echo "Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE"

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
        echo "ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE"

else
echo -e "Radius Manager User Information Sample:"
echo "Account STATUS= OK!"

###############
# Check Account Expiry Date
EXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
#SRVLIMIT=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT comblimit FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`

#Get ACcounting Data for the Current Month Only
DOWNDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $1}'`

# Check for NULL DATA in download section of user
if [ "$DOWNDATA" == "NULL" ]
then
#       echo "NOT USED NO DOWN DATA FOUND"

#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
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"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2,$3}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = Not Used"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
else

UPDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $2}'`
TOTCOMBINED=`echo "($DOWNDATA+$UPDATA)/(1024)/(1024)" |bc`
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
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"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = $TOTCOMBINED MB"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
# Check User Current Online Status
ONLINE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT framedipaddress FROM radacct WHERE AcctStopTime IS NULL AND UserName = '$1';"`
if [ "$ONLINE" == "" ]; then
echo -e "Current Online Status = OFFLINE"
else
echo -e "Current Online Status = ONLINE"
fi
fi
fi
fi

2- playSMS SECTION

Now we have to add COMMAND in playSMS which will actually receive the sms and will act accordingly if found the keyword info

userinfo-playsms-=command


 3- TEST PHASE

You can test by executing the script or send sms , as per your choice.

Both methods results are as follows …

 

by CLI

userinfo-cli

by SMS

userinfo


 Another Version of GETUSERINFO with VLAN connected users numbers

Another Version of GETUSERINFO with more details like current ONLINE STATUS, and QUOTA assigned, used and left counters.

As showed in the below image …

userinf-2


root@rm:/var/lib/playsms/sms_command/1# cat userinfo.sh
#!/bin/bash
# Script to check Radius Manager Status , Expiry Date, Service Plan, Data Used
# Syed Jahanzaib
# aacable @ hotmail.com
# https://aacable.wordpress.com
# Modified on 9th June, 2015

# MYSQL USER NAME AND PASSWORD Variables
SQLUSER="root"
SQLPASS="sqlapssword"
SQLHOST="localhost"
SQLPORT="3306"
CURRENCY="PKR"

# Check User Validation, if not found exit with error , else continue
echo
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT * FROM radius.rm_users WHERE rm_users.username = '$1';"`
if [ "$USRVALID" == "" ]; then
echo -e "USER NOT FOUND !"
else

######################
# ACCOUNT EXPIRY CHECK
######################

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 -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2' | sed 's/00:.*//' | sed -e 's/-//g'`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$1';"  |awk 'FNR == 2 {print $1,$2}'`

if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
echo "Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE"

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo "ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE"

else
echo -e "Radius Manager User Information Sample:"
echo "Account STATUS= OK!"

###############
# Check Account Expiry Date
EXPIRY=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
#SRVLIMIT=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT comblimit FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`

#Get ACcounting Data for the Current Month Only
DOWNDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $1}'`

# Check for NULL DATA in download section of user
if [ "$DOWNDATA" == "NULL" ]
then
#       echo "NOT USED NO DOWN DATA FOUND"

#UPDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0$
CURRENCY="PKR"
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2,$3}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = Not Used"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
#echo -e "Service Quota Limit = $SRVLIMITMB MB"
#echo -e "Downloaded Data = $DOWNDATAUSED - MB"
#echo -e "Uploaded Data = $UPDATAUP - MB"

else

UPDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $2}'`
TOTCOMBINED=`echo "($DOWNDATA+$UPDATA)/(1024)/(1024)" |bc`
TOTCOMBINED2=`echo "($TOTCOMBINED)/(1024)" |bc`
#SRVLIMITMB=`echo "($SRVLIMIT)/(1024)/(1024)" |bc`
#DOWNDATAUSED=`echo "($DOWNDATA)/(1024)/(1024)" |bc`
#UPDATAUP=`echo "($UPDATA)/(1024)/(1024)" |bc`
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# Print Service Download Limit QUOTA - TOTAL
QUOTA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT trafficunitcomb FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Quota Allowed = $QUOTA MB"
echo -e "Total Data Used in $ALPHAMONTHYEAR = $TOTCOMBINED MB"
QUOTALEFT=`echo "( $QUOTA)-($TOTCOMBINED)" |bc`
echo -e "Total Quota LEFT = $QUOTALEFT MB"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
# Check User Current Online Status
ONLINE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT framedipaddress FROM radacct WHERE AcctStopTime IS NULL AND UserName = '$1';"`
if [ "$ONLINE" == "" ]; then
echo -e "Current Online Status = OFFLINE"
else
echo -e "Current Online Status = ONLINE"
fi
fi
fi
fi

 

Regard’s
SYED JAHANZAIB

 


Filed under: Linux Related, Radius Manager

Gnuplot = The DADA ABBU (Grandfather) of Graphing done via CLI

$
0
0

1-data-downloaded-in-year


 

Whatis Gnuplot:

As defined the Wikipedia. …

Gnuplot is a command-line program that can generate two- and three-dimensional plots of functions, data, and data fits. It is frequently used for publication-quality graphics as well as education. The program runs on all major computers and operating systems (GNU/Linux, Unix, Microsoft Windows, Mac OS X, and others).

I remember when I got in love with the MRTG and I spent many nights in mastering this giant. MRTG is overall a very good graphing too graph about any device but it usually works with snmp (and in some cases with shell scripts too). But what if I have data in a file with simple human readable format and I want to plot different columns in it? MRTG will not help in such cases, Gnuplot will come to rescue :)

I used Gnuplot to graph user download for the current month, In this example user data is taken from MYSQL radius DB and then graphed/plotted with Gnuplot.

As always being a duffer , dumber and incompetent, It took me 2-3 Days of continuous efforts to make it as a single script to make it bundled package.

Requirements for this script:

[You can modify it as per your requirements very easily, I just made it as per my own requirements : D ]

  1. Linux / Ubuntu
  2. Mysql with Radius DB
  3. Gnuplot

What this script will do ?

This script will take accounting data for the specified users for the current month by auto detecting the month/year.The file will look something like following

2015-03-01   1688961371   937706875
2015-03-02   2989190965   2974464964
2015-03-04   534479492   31747041
2015-03-05   809968366   170112567
2015-03-06   2189812711   1555484772

First column is DATE
Second column is user DOWNLOADED data in bytes
Third column is user UPLOADED data in bytes
Then it will save this accounting data in /tmp/USERNAME.TXT  (Username is what supplied by the user)
Then gnuplot will start its magic and will graph the data based on the supplied data.


 

To install Gnuplot on Ubuntu , issue following command

apt-get install -y gnuplot

Now create bash script as follows

mkdir /temp
touch /temp/usergraph.sh
nano /temp/usergraph.sh

and paste following. Make sure to change things according to your network

#!/bin/sh
# Freeradius / Mysql user graph ON THE FLY using GNUPLOT
# It will also detect current year and current month and will pull only current time data
# You can modify this function by providing $2 function in the sql command
# By Syed Jahanzaib / aacable [at] hotmail.com
# Last modified on 5th June, 2015

# Defining BASH Variables
SQLUSER="root"
SQLPASS="sqlpassword"
SQLHOST="localhost"

# Date functions to find current date, month year
NOW=$(date)
MONTH=$(date +"-%m")
CMONTH=`echo $MONTH  | sed -e 's/-//g'`
YEAR=$(date +"-%Y")
CYEAR=`echo $YEAR  | sed -e 's/-//g'`
FMONTH=$(date +"%B")
FULLMONTH=`echo $FMONTH # | sed -e 's/-//g'`

# Name of file in which mysql will dump the user accounting data for the current month
TMP="/tmp/$1.txt"

# Fetch Accounting Data from MYSQL Freeradius radius DB, by using current Year/Month using username provide with the script , and output to file
mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST -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, 10) 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, 7) LIKE '$CYEAR-$CMONTH%' AND radacct.username LIKE '$1' AND  FramedIPAddress LIKE '%' AND CallingStationId LIKE '%'   GROUP BY radacct.radacctid
) AS tmp GROUP BY date LIMIT 0, 50;" |awk '{print $1,$2,$3}' > $TMP
sed '1d' -i $TMP

# Run GNUPLOT SCRIPT on the FLY / by zaib
gnuplot << EOF
reset
set terminal jpeg size 1600,600
# Set output according to your requirement, like you can create file with the username for easier identification
set output "/var/www/radius.jpg"
set xdata time
set timefmt "%Y-%m-%d"
set format x "%d/%m"
set xtics 86400
set xtics rotate by -45
set xlabel "Date (day/month)"
set ylabel "Data Downloaded in GB"
set title "$1 - Download/Upload Report $FULLMONTH $YEAR\nThis report was created on $NOW\nPowered by Syed Jahanzaib / aacable@hotmail.com"
set key outside
set grid
set style data histogram
set style histogram cluster gap 1
set style fill solid
set boxwidth 0.9

plot "$TMP" using 1:(\$2/2**30):(sprintf("%.2f", \$2/2**30)) w boxes title "Download" lw 10, \
"$TMP" using 1:(\$3/2**30):(sprintf("%.2f", \$3/2**30)) w boxes lw 6 title "Upload", \
"$TMP" using 1:(\$2/2**30):(sprintf("%.2f", \$2/2**30)) w labels notitle tc rgb 'red', \
"$TMP" using 1:(\$3/2**30):(sprintf("%.2f", \$3/2**30)) w labels notitle tc rgb 'green'

EOF
# GNUPLOT Script ends here
# Thank you : )

 

Running the SCRIPT

Now execute the script by

/temp/usergraph.sh USERNAME

(like usergraph.sh zaib)

If everything goes well and you dont’ see any errors after executing this script, then you can view the output by

http://yourip/radius.jpg

gnuplot


That’s it …

I showed the very basic usage of Gnuplot. Very Very Basic Level of it. This is only what I have learned so far. But Gnuplot can do things beyond your imagination. Look at this gallery.

http://commons.wikimedia.org/wiki/Category:Gnuplot_diagrams

Gnuplot is a very good and customizable tool which is used all over the world to create simple OR very complex graphs in a go. Above all good part is that it can take data from local files and all can be done via scripting or terminal.

You should give it a try :)


Another version which takes year from your input and then create graph for the whole year usage for the network (overall)

This is another version which input year from you and then create graph for the whole year for overall network usage,


root@radius:/temp# cat year.sh
#!/bin/sh
# MYSQL USER NAME AND PASSOWRD Variables
SQLUSER="root"
SQLPASS="SQLPASS"

# Date functions to find current date, month year
NOW=$(date)
MONTH=$(date +"-%m")
CMONTH=`echo $MONTH  | sed -e 's/-//g'`
YEAR=$(date +"-%Y")
CYEAR=`echo $YEAR  | sed -e 's/-//g'`
FMONTH=$(date +"%B")
FULLMONTH=`echo $FMONTH # | sed -e 's/-//g'`

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 '%' AND
FramedIPAddress LIKE '%' AND CallingStationId LIKE '%'
GROUP BY radacct.radacctid
) AS tmp
GROUP BY date
LIMIT 0, 50;"  |awk '{print $1,$2,$3}' >  /tmp/raw

sed '1d' -i /tmp/raw
awk '{ print $1, $2 + $3; }' /tmp/raw > /tmp/final
echo DONE
# Name of file in which mysql will dump the user accounting data for the current month
TMP="/tmp/final"

# Run GNUPLOT SCRIPT on the FLY / by zaib
gnuplot << EOF
reset
set terminal jpeg size 1600,600
# Set output according to your requirement, like you can create file with the username for easier identification
set output "/var/www/radius.jpg"
set xdata time
set timefmt "%Y-%m"
set format x "%Y/%m"
#set ytics 1
set xtics rotate by -45
set xlabel "Date (month/year)"
set ylabel "Data Downloaded in GB"
set title "Download/Upload Report for $1\nThis report was created on $NOW\nPowered by Syed Jahanzaib / aacable@hotmail.com"
set key outside
set grid
set style data histogram
set style histogram cluster gap 1
set style fill solid
set boxwidth 0.9

plot "$TMP" using 1:(\$2/2**30):(sprintf("%.0f", \$2/2**30)) w boxes title "Download" lw 10, \
"$TMP" using 1:(\$2/2**30):(sprintf("%.0f", \$2/2**30)) w labels title "Data in GB" center offset 0,1 tc rgb 'red'

EOF
# GNUPLOT Script ends here
# Thank you : )

Now execute script as follows

./year.sh 2015

you ahve to supply year o it will generate overall graph which will look odd as we are graphing details for 1 year only,

Sample of above script will generate graph as follows

1-data-downloaded-in-year

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

Send Expiry Alert via SMS/Email For Freeradius/Mysql Users

$
0
0

 

 

sms-alert

As some one asked me on howto send sms (or possibly email) to users whose expiry is after XX days in freeradius/mysql base billing system, Here is a simple script to do the task. It’s not very elegant way to achieve the task but since I donot have any programming level experience so this is how achieve it some Desi style coding :) & the good part is , It’s doing the job and you can at least get some ideas from the code.

So basically this post is just another Sharing Idea’s Series


 

Requirements:

  • You must have working billing system in freeradius/mysql with the appropriate tables like radius, username, expiration etc.

 

In this example I used Radius Manager base system which also uses FREERADIUS/MYSQL as its backend DB.Radius Manager already have expiry alerts notification in its core configurable via web panel, but its a 3rd party paid application. So I am showing you a way howto achieve the same with your own billing system.

So basically what I did was to simply ran mysql query which pulled user name and mobile number from the table [mobile number column must be be created with appropriate values] and exported it to local file. Then I applied a simple ‘Loop‘ formula to go through this file and then applied appropriate action in the end like send SMS via mobile / usb modem attached , use any external http Gateway , or send EMAIL.

You can use this logic to achieve the results on about any other billing system (which is open source or readable) OR any other purposes as well.

Just Go through this script ,its very simple, modify it as per your network and setup. If you manage to add some enhancements, do post here for the sake of every one. :~)

I will add some more details later.

Happy Alerting !

Syed Jahanzaib


Create SMS Script

mkdir /temp
touch /temp/sms.sh
chmod +x /temp/sms.sh
nano /temp/sms.sh

Now paste the following script

#!/bin/sh
# BASH base SMS script for sending expiry notification for Freeradius/mysql users
# the simple logic can be applied for about any other task as well.
# I tried to make it as simple as it can be
# By Syed Jahanzaib
# Created on : 8th June, 2015

SQLUSER="root"
SQLPASS="sqlpassword"
# Interval before alert which should be sent to user before this number days
EXPIRY="3"

# Export usernames and mobile from the mysql table in a file,  which Expiry is after 3 days
mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT username,mobile FROM radius.rm_users  WHERE expiration = DATE_ADD(CURDATE(), INTERVAL $EXPIRY DAY);" > /tmp/list

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
cat /tmp/list |sed '1d' |awk 'NF > 1' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $1}'`
mobile=`echo $users | awk '{print $2}'`

# Add action like send sms or email as per required or designed / zaib
# Here I am just echoing , You must change this if you want some action liek sms or mail as showed in the end
echo "Dear $username, Your account will expire after 3 days. Your cell is $mobile"

# GAMMU SENDMS Example
# gammu sendsms TEXT $mobile -text "Dear $username, Your account will expire after 3 days / ABC ISP"

# KANNEL SMS HTTP GATEWAY Example, 192.168.1.1 is kannel server ip
# curl "http://192.168.1.1:13013/cgi-bin/sendsms?username=kannel&password=KANNELPASS&to=$mobile&text=Dear+$username+Your+account+will+expire+after+3+days++ABC+ISP

# Email Example using -mail- tool
# mail -s 'Dear $username, Your account will expire after 3 days / ABC ISP' $email

done

 

OUTPUT:

[Just echoing in this example]

Run the script manually for test purposes and you should then be able to see something like if you already have proper billing configured with enough data. Below example is a working radius system showing accounts with mobile numbers which will expire in next 3 days. We can show more info if required.

 

sms-alert-list


 

Schedule to run it DAILY

You can schedule it to run on daily basis so it can check for accounts expiring on next xx days and take appropriate action as required.

Example of scheduled job bycrontabcommand:

crontab -l

@daily /temp/sms.sh

With above code, this script will run daily at 00:00 hours [in night] daily. Then it will search for accounts whose account will expire after 3 days, then it will take defined action.

Jz!

 


Filed under: Linux Related, Radius Manager

Freeradius/mysql Account Expiry SMS notification Script using ‘itelservices.net’ bulk SMS Gateway

$
0
0

sms

This post is somewhat very specific to PK base bulk sms provider API. Its a simple bash script made on someone’s request [who had a custom billing system based on freeeradius/mysql] and it can be used to send account expiry notifications to users using freeradius/mysql account query  , BUT specifically using HTTP base SMS Gateway services from http://itelservices.net/

However this specific SMS gateway was a bit different as compared to our KANNEL base gw.

  1. It requires ‘Unique transaction ID’ for each sms, therefore i used current time/seconds with username as Transaction ID
  2. The number should be in international format like 923333021909 and the problem was that the operator had simple format for mobile numbers like 03333021909 is all accounts, and it was not acceptable from the API provider, therefore as a workaround, I used awk/sed tools to remove 0 and then in curl added 92 before every number.

At the moment there are two scripts

1- SMS for account expiry notification
2- SMS for new account creation with user details if possible

You must modify the script as required. This is just a simple way to achieve this task, however there are more sophisticated method like using php or other programing language, I just prefer to select the BASH route !

 

Posting it for   H U M A S   as I love them, They’re Amazing ! :)


1- SMS for account expiry notification

 

mkdir /temp
touch /temp/sms.sh
chmod +x /temp/sms.sh
nano /temp/sms.sh

Now paste the following code.

#!/bin/sh
# set -x
# BASH base SMS script for sending expiry notification for Freeradius/mysql users
# the simple logic can be applied for about any other task as well.
# I tried to make it as simple as it can be
# By Syed Jahanzaib
# Created on : 8th June, 2015
# Modified on : 18th june, 2015
# This script was specially modified for APITEL http sms gateway services
# which requires unique transaction ID each time, so i used datetimesecond feature as jugaar
# made for KHI

# MYSQL root id and password
SQLUSER="root"
SQLPASS="sqlpass"
DB="radiusdb"

# APITEL User Name & Password, must be filled
APIUSER="xxxx"
APIPASS="xxxx"
API="YOURSENDERNAME"

# Date functions to find current date, month year and Transaction id using seconds ; ) jugaar way ; )
NOW=$(date)
TID=$(date +"-%s")

# Interval before alert which should be sent to user before this number days
EXPIRY=3

# Export usernames and mobile from the mysql table in a file,  which Expiry is after 3 days
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; SELECT login,mobile FROM users WHERE expirydate = DATE_ADD(CURDATE(), INTERVAL $EXPIRY DAY);"
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; SELECT login,mobile FROM users WHERE expirydate = DATE_ADD(CURDATE(), INTERVAL $EXPIRY DAY);" > /tmp/list

# Remove 0 if any in mobile number and export it to final list
cat /tmp/list | awk '{gsub("^0","",$2); print $1,$2}' > /tmp/finallist

# Add DATE TIME in sms.log to separate date wise entries / zaib
echo ====================================================== >> /var/log/sms.log
echo $NOW >> /var/log/sms.log
echo ====================================================== >> /var/log/sms.log

# Add DATE TIME in smsapi.log to separate date wise entries WITH API STATUS for cross verification / zaib
echo ====================================================== >> /var/log/smsapi.log
echo $NOW >> /var/log/smsapi.log
echo ====================================================== >> /var/log/smsapi.log

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
cat /tmp/finallist |sed '1d' |awk 'NF > 1' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $1}'`
mobile=`echo $users | awk '{print $2}'`

# SMS Body
BODY="Soft+Reminder:+Dear+$username,+Your+Internet+Service++Will+Expire+after+$EXPIRY+days++++zaibisp"

echo "$NOW ! Expiry Notification have been sent to $username, on cell number 0$mobile"
echo "$NOW ! Expiry Notification have been sent to $username, on cell number 0$mobile" >> /var/log/sms.log

# Add action like send sms or email as per required or designed / zaib
# Sending sms via APITEL API SMS Gatewy / syed jahanzaib / aacable@hotmail.com

curl "http://api1.itelservices.net/send.php?transaction_id=$TID$username&user=$APIUSER&pass=$APIPASS?&number=%2B92$mobile&text=$BODY&from=$API" >> /tmp/smsapi.log
done

sed 's/\(Status\)/\n\1/g' /tmp/smsapi.log >> /var/log/smsapi.log
echo ======================================================
echo Result for SMSAPI , so that you can verify that how much sms are actually sent with the status codes
cat  /var/log/smsapi.log



 

CRON JOB TO RUN IT DAILY IN NIGHT

Now set cron job to run it daily in night

@daily /temp/sms.sh


 LOGS

you can view log files in following location
/var/log/sms.log

Sample:

Thu Jun 18 11:43:20 PKT 2015 ! Expiry Notification have been sent to USER1, on cell number 033333333333
Thu Jun 18 11:43:20 PKT 2015 ! Expiry Notification have been sent to USER2, on cell number 0333132121211

/var/log/smsapi.log

Results with status from api gateway services (Useful to track the messages are actually sent or having errors from provider like server down, credit finished etc etc)

Sample:

Status: 013, Id: -1434609800USER1, Number: +923452266605
Status: 013, Id: -1434609800USER2, Number: +923222656143


2- SMS for NEW Account Creation

1

mkdir /temp
touch /temp/sms-new-account.sh
chmod +x /temp/sms-new-account.sh
nano /temp/sms-new-account.sh

#!/bin/sh
# set -x
# BASH base SMS script for NEW ACCOUNTnotification for Freeradius/mysql users
# the simple logic can be applied for about any other task as well.
# I tried to make it as simple as it can be
# By Syed Jahanzaib
# CREATED on : 19th june, 2015
# This script was specially modified for APITEL http sms gateway services
# which requires unique transaction ID each time, so i used datetimesecond feature as jugaar
# made for KHI/PK

# MYSQL root id and password
SQLUSER="root"
SQLPASS="pass"
DB="radius-db"

# APITEL User Name & Password
APIUSER="APIUSER"
APIPASS="APIPASS"
API="SENDERID"

# Date functions to find current date, month year and Transaction id using seconds ; ) jugaar way ; )
NOW=$(date)
TID=$(date +"-%s")

# Check Account which are created before this number of MINUTES
CREATION=5

touch /tmp/sms-new-account.log
touch /tmp/sms-new-account-api.log
> /tmp/sms-new-account.log
> /tmp/sms-new-account-api.log

# Export usernames and mobile from the mysql table in a file,  which Expiry is after 3 days
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e "use $DB; select creationdate,login,package,expirydate,mobile from users WHERE creationdate >= NOW() - INTERVAL $CREATION MINUTE;"`
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; select creationdate,login,package,expirydate,mobile from users WHERE creationdate >= NOW() - INTERVAL $CREATION MINUTE;" > /tmp/newact

# Check User Validation, if not found exit with error , else continue
echo
if [ "$USRVALID" == "" ]; then
echo -e "No new user created in last minutes, so nothign to do , zaib !"
else
echo -E "user Created found , proceeding..."

# Remove 0 if any in mobile number and export it to final list
cat /tmp/newact | awk '{gsub("^0","",$7); print $1,$2,$3,$4,$5,$6,$7}' > /tmp/newactfinal

# Add DATE to separate entries in sms-new-account.log
echo ================================ >> /var/log/sms-new-account.log
echo $NOW >> /var/log/sms-new-account.log
echo ================================ >> /var/log/sms-new-account.log

echo ================================ >> /var/log/sms-new-account-api.log
echo $NOW >> /var/log/sms-new-account-api.log
echo ================================ >> /var/log/sms-new-account-api.log

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
cat /tmp/newactfinal |sed '1d' |awk 'NF > 6' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $3}'`
mobile=`echo $users | awk '{print $7}'`
pkg=`echo $users | awk '{print $4}'`
exp=`echo $users | awk '{print $5}'`
#echo "Welcome to MYNET Broadband Services! Your account details are as follow...
#Username = $username
#Package = $pkg
#Expiry = $exp
#Cell No = $mobile"

# SMS Body
BODY="Welcome+to+MYISP+Services,+Your+account+details+are:++id=$username+/+Package=+$pkg+/+Expiry=+$exp+/+Cell=+0$mobile++++MYISP+BROADBAND"

echo "$NOW ! New Acount Creation Notification have been sent to $username, on cell number 0$mobile"
echo "$NOW ! New Acount Creation Notification have been sent to $username, on cell number 0$mobile" >> /var/log/sms-new-account.log

# Add action like send sms or email as per required or designed / zaib
# Sending sms via APITEL API SMS Gatewy / syed jahanzaib / aacable@hotmail.com

curl "http://api1.itelservices.net/send.php?transaction_id=$TID$username&user=$APIUSER&pass=$APIPASS?&number=%2B92$mobile&text=$BODY&from=$API" >> /tmp/sms-new-account-api.log
sed 's/\(Status\)/\n\1/g' /tmp/sms-new-account-api.log >> /var/log/sms-new-account-api.log
echo
echo Result for SMSAPI , so that you can verify that how much sms are actually sent with the status codes
#cat  /var/log/sms-new-account.log
done

fi

Cron it to run after every 5 minutes

*/5 * * * * /temp/sms-new-account.sh


 3- SMS for ALL users (I deployed it for Webmin usage)


#!/bin/bash
# set -x
# Script to send GENERAL SMS via WEBMIn
# Syed Jahanzaib
# aacable @ hotmail.com
# https://aacable.wordpress.com
# Created on 24th June, 2015

SQLUSER="root"
SQLPASS="mysqlpassword"
DB="radiusdb"

# APITEL User Name & Password
APIUSER="xxxx"
APIPASS="xxxxx"
API="xxxx"

######################
# ACCOUNT EXPIRY CHECK
######################

# Date functions to find current date, month year and Transaction id using seconds ; ) jugaar way ; )
NOW=$(date)
TID=$(date +"-%s")

# Adding files
touch /tmp/smspanel.log
touch /tmp/smapanel-api.log
> /tmp/smspanel.log
> /tmp/smapanel-api.log

mysql -uroot -pgatewayb3 -e "use mynet; SELECT login,mobile FROM users;"  > /tmp/smspanellist

# Remove 0 if any in mobile number and export it to final list
cat /tmp/smspanellist | awk '{gsub("^0","",$2); print $1,$2}' > /tmp/smspanellistfinal

# Add DATE TIME in /tmp/smspanel.log to separate date wise entries / zaib
echo ====================================================== >> /var/log/smspanel.log
echo $NOW >> /var/log/smspanel.log
echo ====================================================== >> /var/log/smspanel.log

# Add DATE TIME in /tmp/smspanel-api.log to separate date wise entries WITH API STATUS for cross verification / zaib
echo ====================================================== >> /var/log/smspanel-api.log
echo $NOW >> /var/log/smspanel-api.log
echo ====================================================== >> /var/log/smspanel-api.log

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
# remove first line which have simple text, then remove dash in second column which is mobile numbers
cat /tmp/smspanellistfinal |sed '1d' |awk 'NF > 1' | awk '{gsub("-","",$2)}1' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $1}'`
mobile=`echo $users | awk '{print $2}'`

# SMS Body in local file and remove new lines and replace spaces with plus sign for api acceptance
BODY=`cat /tmp/smspanelmsg.txt  |tr '\r\n' ' ' | sed -e "s/\s\{1,\}/+/g"`

#echo "$NOW ! $BODY ---- MSG was sent to $username, on cell number 0$mobile"
echo "$NOW ! Your MSG was sent to $username, on cell number 0$mobile" >> /var/log/smspanel.log

# Sending sms via APITEL API SMS Gatewy / syed jahanzaib / aacable@hotmail.com

curl "http://api1.itelservices.net/send.php?transaction_id=$TID$username&user=$APIUSER&pass=$APIPASS?&number=%2B92$mobile&from=$API&text=$BODY" >> /tmp/smspanel-api.log
sed 's/\(Status\)/\n\1/g' /tmp/smspanel-api.log >> /var/log/smspanel-api.log
done

 

ITELSERVICES.NET related information

Sample of URL to send SMS

http://api1.itelservices.net/send.php?transaction_id=message1&user=bilal&pass=bilal2015?&number=%2B923333021909&text=hello&from=MyNet

Please note that the transaction id must be unique for each sms, example message1, message2 and so on any word is acceptable, i used date time as transaction id, you may use your own.

 

INFORMATION AND ERROR CODES related to API

For the information/error codes

 

1

 

2

 

3


 

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

RADIUS Redundancy by using MYSQL Master-Master Replication

$
0
0

master-master

In this Guide, I will show you howto create replica of your radius server so that in case of any server failure , you can instantly switch to backup server with the latest data available. In this model we will use MYSQL master-master concept in which whatever changes / records you make on any server, it will replicate to other as well. Also in mikrotik we can use primary and secondary radius server entries OR we can make a script to detect both radius status and act accordingly, all depend on your network requirements & infrastructure.

Scenario:

In this example we have RADIUS MANAGER billing system which uses freeradius and MYSQL DB as its backend engine,  installed (with basic level of installation) on two servers. Now we want to create redundancy by replicating radius DB to each other so that in case of one server failure, second server should come to rescue.

Requirements:

  • I assume that you have working radius manager installed on both PC and tested its working by creating users in it.

Components Used:

  • SERVER1 NAME = MASTER-RADIUS
    OS = Centos 6.5 32bit
    IP = 101.11.11.241
  • SERVER2 NAME = REPLICA-RADIUS
    OS = Centos 6.5 32bit
    IP = 101.11.11.245
  • MIKROTIK PPPOE SERVER = Mikrotik
    OS = Mikrotik 5.xx
    IP = 101.11.11.255

Let’s Start

 

Step – 1

Server1 = ‘master-radius’ Configuration

Open mysql config file

nano /etc/my.cnf

and add following under [mysqld] section

log-bin=mysql-bin
binlog-do-db=radius
server-id=1
auto_increment_increment = 2
auto_increment_offset = 1

SAVE and EXIT.

Now restart mysqld service so changes can take effect.

service mysqld restart

Now we need to create a user that will be used by mysql for replicating data between our two radius (or mysql) servers. As an example I am using id “zaib”. Replace “password” with the password you wish to use for replication.

create user 'zaib'@'%' identified by 'password';
grant replication slave on *.* to 'zaib'@'%'; 

Now we need to get some information about the current MySQL instance which we will later provide to server2 (replica).

The following command will output a few pieces of important information, which we will need to make note of:

show master status;

The output will look similar to the following, and will have two pieces of critical information: [file and position note it down)

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      336 | radius       |                  |
+------------------+----------+--------------+------------------+

1 row in set (0.00 sec)

We need to make a note of the file and position which will be used in the next step.


 

Step – 2

Server2 = ‘replica-radius’ Configuration

 

Open mysql config file

nano /etc/my.cnf

and add following under [mysqld] section

log-bin=mysql-bin
binlog-do-db=radius
server-id=2
auto_increment_increment = 2
auto_increment_offset = 2

Make sure server-id is different then primary server

SAVE and EXIT.

Now restart mysqld service so changes can take effect.

service mysqld restart

Here we are going to create the user which will be responsible for the replication. Replace “password” with the password you wish to use.

create user 'zaib'@'%' identified by 'password';
grant replication slave on *.* to 'zaib'@'%'; 

The next step involves taking the information that we took a note of earlier and applying it to our mysql instance. This will allow replication to begin. The following should be typed at the mysql shell:

slave stop;

CHANGE MASTER TO MASTER_HOST = '101.11.11.241', MASTER_USER = 'zaib', MASTER_PASSWORD = 'password', MASTER_LOG_FILE = 'mysql-bin.000001', MASTER_LOG_POS = 336;

slave start; 

Your values for MASTER_LOG_FILE and MASTER_LOG_POS may differ than those above. You should copy the values that “SHOW MASTER STATUS” returns on Server-1.

 

The last thing we have to do before we complete the mysql master-master replication is to make note of the master log file and position to use to replicate in the other direction (from Server 2 to Server 1).

We can do that by typing the following:

SHOW MASTER STATUS; 

The output will look similar to the following:

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000002 |      125 | radius       |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

Take note of the file and position, as we will have to enter those on server 1, to complete the two-way replication.

The next step will explain how to do that.

 

Step – 3

Completing Replication on Server1 [Master-radius]

Back on Server 1, we need to finish configuring replication on the command line.

Running this command will replicate all data from Server 2.

slave stop;
CHANGE MASTER TO MASTER_HOST = '101.11.11.245', MASTER_USER = 'zaib', MASTER_PASSWORD = 'password', MASTER_LOG_FILE = 'mysql-bin.000002', MASTER_LOG_POS = 125;
slave start; 

Keep in mind that your values may differ from those above. Please also replace the value of MASTER_PASSWORD with the password you created when setting up the replication user.

The output will look similar to the following:

Query OK, 0 rows affected (0.01 sec)

 

Now test the status by issuing command to mysql cli

show slave status\G

and you should see something similar to this. [don’t get confused with different numbers of log file file and position number, as this snap was taken in another lab]

replica-status


 

TEST

The last thing to do is to test that replication is working on both servers.

Open server1 radius panel, and try to create new user, after creation, it will be automatically replicated to server2 : )

As showed in the images below …

At a moment no users have been created.

server1-empty

 

Now create test user

server1-users-create

 

After creation, Goto Server2 (Replica) and check Users List, and you will find the user replicated.

server2-new0user0replicate-ok

and when you will create any user , it will replicate back to server1.


Adding both Radius Server entries in Mikrotik

Add both radius server

add-radius

and at radius manager, add the NAS (mikrotik)

add-nas

Don’t forget to rebuild clients.conf (from the menu) at secondary radius as well.

Now test by connecting any client , once successful, disconnect the primary radius, and try to connect the client again, once mikrotik will be unable to find primary entry, it will auto contact secondary server. as showed in the images below …

2radius

I will add few more details later….

 

Regard’s
Syed Jahanzaib

 


Filed under: Linux Related, Radius Manager

Modifying MYSQL table to add hh:mm in date to facilitate Radius Manager SMS sending upon account renewal

$
0
0

Personnel Notes: For future retrieval of the code

1

2

Task:

DMASOFTLAB Radius Manager have the limited facility to send sms on different events like account creation welcome msg, expiry, password retrieval.

rmRM send following SMS upon new account creation

Welcome to our system! Your account name is {USERNAME}, password is {PASSWORD}

But the OP wanted to send some customized SMS with few other info as well like login details, upon every account renewal (which RM does not support).

+ the system should be able to detect that if the account is registered today, then it should send WELCOME message along with details, BUT if the account is old and only it get renewed, then it should send RENEWAL message.


 

 

Solution:

First you need to modify the DATE type to DATETIME in rm_invoices table, you can use phpmyadmin to do the task easily, or use the command as follows:

login to mysql and issue following commands

use radius;
ALTER TABLE `rm_invoices` CHANGE `date` `date` DATETIME NOT NULL ;

Now you can use following script.

mkdir /temp
touch /temp/expirynotification.sh
chmod +x /temp/expirynotification.sh
nano /temp/expirynotification.sh

Add following date in the script

#!/bin/sh
# set -x
# BASH base SMS script for NEW ACCOUNT / RENEWAL notification for RADIUS MANAGER based on Freeradius/mysql
# the simple logic can be applied for about any other task as well. I tried to make it as simple as it can be
# By Syed Jahanzaib
# CREATED on : 16th July, 2015

SQLUSER="root"
SQLPASS="sql_password"
MNT="5"
CURDATE=`date`
KANNELID="kannel"
KANNELPASS="kannelpass"
GMAILID="yourgmailid"
GMAILPASS="yourgmailpass"
ADMINMAIL="aacable@hotmail.com"

# Setting Date as variable
TODAY=$(date +"%Y-%m-%d")
# Removing DASH from date to use it in compare formula later
TODAYDIGIT=`echo $TODAY  | sed -e 's/-//g'`

> /var/log/renewal.log

# Simply print the info
mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT rm_invoices.username, rm_invoices.paid, rm_users.createdon, rm_invoices.expiration, rm_users.mobile, rm_users.owner  FROM rm_invoices INNER JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= NOW() - INTERVAL $MNT MINUTE  AND (paymode = '0' ) AND (invgroup = '0'  OR invgroup = '1' );"

# Check User Validation, if not found exit with error , else continue
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT rm_invoices.username, rm_invoices.paid, rm_users.createdon, rm_invoices.expiration, rm_users.mobile FROM rm_invoices INNER JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= NOW() - INTERVAL $MNT MINUTE  AND (paymode = '0' ) AND (invgroup = '0'  OR invgroup = '1' );"`
if [ ! -n "$USRVALID" ]; then
echo  "No account have been updated in last $MNT minutes !"
exit 0
fi

# Fetch user account details which were created in last 5 minutes from rm tables using inner joing function in mysql
mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT rm_invoices.username, rm_invoices.paid, rm_users.createdon, rm_invoices.expiration, rm_users.mobile, rm_users.owner FROM rm_invoices INNER JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= NOW() - INTERVAL $MNT MINUTE  AND (paymode = '0' ) AND (invgroup = '0'  OR invgroup = '1' );" > /tmp/temp

# Apply Count Loop Formula while deleting first line which have junk text
num=0
cat /tmp/temp |sed '1d' | while read users
do
num=$[$num+1]
username=`echo $users | awk '{print $1}'`
paidwod=`echo $users | awk '{print $2}' | sed -e 's/-//g'`
paid=`echo $users | awk '{print $2}'`
cratedwod=`echo $users | awk '{print $3}' | sed -e 's/-//g'`
crated=`echo $users | awk '{print $3}'`
expiration=`echo $users | awk '{print $4}'`
mobile=`echo $users | awk '{print $5}'`
dealer==`echo $users | awk '{print $6}'`

#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$username';" |awk 'FNR == 2 {print $1}'`

# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# If user account creation date is today, then send welcome message with other details
if [ $cratedwod  -eq $paidwod ]
then

# Use following if you want to send SMS
# curl "http://localhost:13013/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$mobile&text=Welcome+$username,%0AYour+Internet+Services+have+been+activated+with+$PKGNAME+Service.%0ALogin+details+are+username+=+$username%0AActivation+Date+=+$paid%0AExpiration+Date=+$expiration%0AGALAXY+TECH"
# Or just ECHO
echo "$CURDATE : Following account creation and renewal have been done \nUsername = $username \nPacakge = $PKGNAME \nNext Expiry = $expiration" > /var/log/renewal.log
echo "**********************" >> /var/log/renewal.log

# If you want to send email , use below ...
#/temp/sendEmail-v1.56/sendEmail -t aacable@hotmail.com -u "Account Creation/Renewal Report" -o tls=yes -s smtp.gmail.com:587 -xu aacablenetworks@gmail.com -xp CapricorN*88 -f aacablenetworks@gmail.com -o message-file=/var/log/renewal.log  -o message-content-type=text

# Delete the today account so that separate message should be sent to old users
sed -i "/$username/d" /tmp/temp

# If user account creation date is old, then send RENEWAL message with other details
else

# If you want to send sms then use curl
#curl "http://localhost:13013/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$mobile&text=Dear+$username,%0AYour+Internet+Services+have+been+activated+with+$PKGNAME+Service.%0ALogin+details+are+username+=+$username%0AActivation+Date+=+$paid%0AExpiration+Date=+$expiration%0AGALAXY+TECH"
# OR simply ECHO print the data
echo "$CURDATE : \nDEALER  $dealer \nFollowing account renewal have been done \nUsername = $username \nPacakge = $PKGNAME \nNext Expiry = $expiration" >> /var/log/renewal.log
echo ================================================= >> /var/log/renewal.log
# OR EMAIL the Result
#/temp/sendEmail-v1.56/sendEmail -t $ADMINMAIL -u "GT $CURDATE : Account Renewal Report of last $MNT minutes" -o tls=yes -s smtp.gmail.com:587 -xu $GMAILID@gmail.com -xp $GMAILPASS -f aacablenetworks@gmail.com -o message-file=/var/log/renewal.log  -o message-content-type=text
#/temp/sendEmail-v1.56/sendEmail -t thestrangeryes@hotmail.com -u "GT $CURDATE : Account Renewal Report of last $MNT minutes" -o tls=yes -s smtp.gmail.com:587 -xu $GMAILID@gmail.com -xp $GMAILPASS -f aacablenetworks@gmail.com -o message-file=/var/log/renewal.log  -o message-content-type=text

fi
done

For test, renew two accounts using RM / add credits section in respective users. One account that should be created today, and one account which was created earlier. and you may see following results : )


[root@radius-master temp]# ./expirynotification.sh
+-----------+------------+------------+------------+
| username  | paid       | createdon  | expiration |
+-----------+------------+------------+------------+
| todayuser | 2015-07-16 | 2015-07-16 | 2015-08-16 |
| olduser   | 2015-07-16 | 2014-01-16 | 2015-08-16 |
+-----------+------------+------------+------------+
Welcome todayuser, Your Internet Services have been activated with 1mb  Service. Login details are / username = todayuser / Activation Date = 2015-07-16 / Expiration Date= 2015-08-16
Dear olduser, Your account have been renewed with 2mb Service. Login details are / username = olduser / Renewal Date = 2015-07-16 / Expiration Date= 2015-08-16

olduser

Note: for demonstration purpose, I printed the output using echo command, you can use your other tools to send sms using your local mobile/usb modem using GAMMU, or http base sms gateway using curl. i wrote many examples on it in previous posts.

 


 

Regard’s
Syed Jahanzaib

 


Filed under: Linux Related, Radius Manager

Enabling Authentication Logs in Freeradius

$
0
0

logs-error

Sometimes in freeradius base billing system, user is unable to authenticate with the system. To quickly investigate the issue, its better to enable freeradius authentication logs to see if its the user end id password issue or something else.

To enable Free- Radius LOGS to get additional information on users authentication ,

Edit /usr/local/etc/raddb/radiusd.conf

nano /usr/local/etc/raddb/radiusd.conf

and modify following

auth = no
auth_badpass = no
auth_goodpass = no

to following

auth = yes
auth_badpass = yes
auth_goodpass = yes

Save and Exit.

Now restart radius service by

service radiusd restart

Check Logs by

tail -f /usr/local/var/log/radius/radius.log

and you will AUTH logs for Good and Bad Login Attempts, It helps a lot in troubleshooting troubled users.

Thu Aug  6 14:52:06 2015 : Auth: Login OK: [usernameX/username] (from client CCR-GW port 15747979 cli xx:D1:11:64:B8:39)
Thu Aug  6 14:52:07 2015 : Auth: Login OK: [usernameX/username] (from client CCR-GW port 15747975 cli xx:44:76:72:A7:9C)
Thu Aug  6 14:52:08 2015 : Auth: Login OK: [usernameX/username] (from client CCR-GW port 15747978 cli xx:44:76:72:9E:9C)

Thu Aug  6 14:58:48 2015 : Auth: Login incorrect: [usernameY<via Auth-Type = mschap>] (from client pppoe2 port 16056177 cli xx:DE:27:2F:23:95)
Thu Aug  6 14:58:49 2015 : Auth: Login incorrect: [usernameZ/<via Auth-Type = mschap>] (from client pppoe1 port 15819569 cli xx:F3:C1:AD:70:17)

 

Regard’s

Syed Jahanzaib

 

 


Filed under: Linux Related, Radius Manager

Passing PHP variables to Shell Script with CAPTCHA code [Example renew account via web]

$
0
0


For my personnel archive purpose only:

All of these tests were made in lab and later on tested on production network as well and worked perfectly. BUT before deploying it in production, one must ensure security , specially try to host it on https server, MUST add captcha in form to prevent BOTS attack, + one should consider BASH security and trimming + some functions to match with real live environment. all can be done easily if you have some knowledge on html/php/bash.


 

Scenario:

A simple portal page is required where user can input there user name and refill code in order to renew there internet account on billing system [in this example radius manager is being used]. then this html page will pass the user name and card number variable to php page which will execute an shell script to trigger renewal action based on the supplied variables. The shell script will check for following

  • Check for Valid Users name in Billing
  • Check for Valid Card number in billing refill card database
  • Check if card is used or not
  • Check the user current package and compare it with the card value
  • If all OK, renew the user account for next 30 days (or whatever actions is required)
  • Output the result to browser

 


 

Following file will present FORM where user can enter there user name and pin code/refill code.

input.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Refill your account ! </title>
</head>
<body>
<h1>Refill your account using scratch code:</h1>
<form method="post" action="function.php">
User Name: <br />
<input type="text" name="USERNAME" size="35" />
<br />
Card No: <br />
<input type="text" name="CARDNO" size="35" />
<br /> <br />
<input type="submit" value="Submit:" />
<br />
</form>
</body>
</html>

Following file will execute the SHELL script with the supplied username and pincode variable and echo there result in the browser.

function.php

<?php
$USERNAME = $_POST[‘USERNAME’];
$CARDNO = $_POST[‘CARDNO’];

if(empty($USERNAME ) || empty($CARDNO )) {
echo “<h2>You must fill in all fields</h2>\n” ;
die (“Click Back to start again.”);
}
echo “<h2>You have entered the following information:</h2>”;
echo “<pre>Customer name\t=\t$USERNAME <br></pre> “;
echo “<pre>Card No\t\t=\t$CARDNO</pre>”;

echo “<h2>BILLING RESPONSE</h2>”;
echo “======================”;
$var = shell_exec(“TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO”);
echo “<pre>$var</pre>”;
?>



BASH Shell script which will be executed by the function.php file

Contents of /var/www/html/renew.sh

{lab testing version, working ok, it may contain lot of junk or it can be trimmed, it’s upto you to make it look pro}

#!/bin/bash
#set -x
# SCRIPT TO RENEW USER ACCOUNT IN RADIUS MANAGER VIA WEB PORTAL
SQLUSER=”root”
SQLPASS=”zaib1234″
echo $1 $2 > /tmp/user-card
USR=`cat /tmp/user-card | awk {‘ print $1 ‘}`
CARD=`cat /tmp/user-card | awk {‘ print $2 ‘}`
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

#LOOK FOR EMPTY CARD NO IF ENTERED , EXIT
if [ “$1” == “” ]; then
echo -e “ERROR: ENTER USER NAME WITH CARD NUMBER PLEASE!”
exit 0
fi

#LOOK FOR VALID USER IN RADIUS
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = ‘$USR’;”`
if [ “$USRVALID” == “” ]; then
echo -e “ERROR: USER NOT FOUND IN BILLING SYSTEM!!”
exit 0
fi

#LOOK FOR EMPTY CARD NO IF ENTERED , EXIT
if [ “$2” == “” ]; then
echo -e “ERROR: PLEASE ENTER CARD NUMBER!!”
exit 0
fi

# LOOK FOR USED CARDS
CARDSTATUS=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT SQL_CALC_FOUND_ROWS cardnum, used, revoked, expiration, value, date, owner FROM rm_cards WHERE cardtype = ‘1’ AND cardnum = ‘$2’  ORDER BY cardnum ASC LIMIT 0, 50;” |  awk {‘print $8}’`
if [ -n “$CARDSTATUS” ]; then
echo -e “CARD IS ALREADY USED”
exit 0
fi

######################
# ACCOUNT EXPIRY CHECK
######################

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’`
SRVEXPIRYFULLD=`mysql -u$SQLUSER -p$SQLPASS -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:.*//’`
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”.”`
CARDPRICE=`mysql -u$SQLUSER -p$SQLPASS -e “use radius;  SELECT value FROM rm_cards WHERE cardnum = $CARD;” |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))
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = ‘$1’;” |awk ‘FNR == 2 {print $1,$2,$3}’;`

# LOOK FOR VALID REFILL CARD CODE IN RADIUS CARDS LIST
CARDVALIDATION=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT value, expiration FROM rm_cards WHERE cardnum = ‘$CARD’ AND used = ‘0000-00-00 00:00:00’;”`
if [ “$CARDVALIDATION” == “” ]; then
echo -e “ERROR: INVALID CARD NUMBER!”
exit 0
else

# IF CARD VALUE IS LESS THEN CURRENT PACKAGE PRICE THEN PRINT ERROR AND GOTO END
if [ $CARDPRICE -lt $SRVPRICE ]
then
echo -e “ERROR: CARD PRICE IS NOT SUFFICIENT TO REFRESH $PKGNAME SERVICE”
exit 0
else

# IF CARD VALUE IS EQUAL OR HIGHER  THEN CURRENT PACKAGE PRICE THEN OK
if [ $CARDPRICE -eq $SRVPRICE ]
then
echo
fi

########### ACCOUNT STATUS EXPIRED TODAY ACTION ############
if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
echo “Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE”
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

# 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 scratch code by SMS’ 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’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

########### ACCOUNT STATUS EXPIRED IN PAST ACTION ############

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo “ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE”
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

# 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 scratch code by SMS’;”

# ADD SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e “use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), ‘n/a’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

# Update QUOTA for the USER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET comblimit = ‘$PKGQUOTAB’ WHERE username = ‘$USR’;”

else
########### ACCOUNT STATUS OK! ACTION ############

echo -e “User Billing Info:”
echo “Account STATUS= OK!”

NEXTEXPIRYADD=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; select DATE_ADD(expiration, INTERVAL 31 DAY) as x from rm_users where username= ‘$USR’;” |awk ‘FNR == 2’`

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo Owner = $USERFLNAME
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

NEXTEXPIRYADD=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; select DATE_ADD(expiration, INTERVAL 31 DAY) as x from rm_users where username= ‘$USR’;” |awk ‘FNR == 2’`

# 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 scratch code by SMS’ 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’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

fi
fi
fi

########### ACCOUNT STATUS EXPIRED TODAY ACTION ############
if [ $PKGQUOTA -eq 0 ]
then
echo -e “Total Quota Allowed = No Quota”
else
echo -e “Total Quota Allowed = $PKGQUOTAB GB”
fi
echo -e “Done/Note: Card Number $CARD is marked as used in DB to prevent re-usege”


 

RESULTS:

1- enter details


 

If the script found that the user name not valid in the billing , spit the error

0- user not found


 

If the script found that the card number is not available in the billing , spit the error

2- invalid number


 

If the script found that the card number entered is already used , spit the error

3- card already used


 

If the script found both fields blank, spit the error

4- you must fill in all fields


 

If the script found user name and card matches, then proceed to renew the account

5- if all ok renew the account

You can also take different actions like send Email / SMS to ADMIN, and user both or any other action.


 


 


 


 


 

re-captcha

ADDING CAPTCHA SECURITY IN FORM

To add captcha security in html form, (which should be must in my opinion for security reasons)

Download secureimage and unzip in your web folder like /var/www/html/secureimage

mkdir /temp

cd /temp

wget https://www.phpcaptcha.org/latest.tar.gz

tar zxvf latest.tar.gz

mv securimage/ /var/www/html/

Now edit the html form to add the captcha facility

TEST.HTML [Red highlighted are our code for captcha]

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Refill your account ! </title>
</head>
<body>
<h1>Refill your account using scratch code:</h1>
<form method=”post” action=”test.php”>
User Name: <br />
<input type=”text” name=”USERNAME” size=”35″ />
<br />
Card No: <br />
<input type=”text” name=”CARDNO” size=”35″ />
<br /> <br />
<input type=”submit” value=”Submit:” />
<br />
</body>
<img id=”captcha” src=”/securimage/securimage_show.php” alt=”CAPTCHA Image” />
<input type=”text” name=”captcha_code” size=”10″ maxlength=”6″ />
<a href=”#” onclick=”document.getElementById(‘captcha’).src = ‘/securimage/securimage_show.php?’ + Math.random(); return false”>[ Different Image ]</a>
</form>
</html>

TEST.PHP [Red highlighted are our code for captcha]

<?php
include_once $_SERVER[‘DOCUMENT_ROOT’] . ‘/securimage/securimage.php’;
$securimage = new Securimage();
if ($securimage->check($_POST[‘captcha_code’]) == false) {
  echo “The CAPTCHA security code entered was incorrect. Make Sure You are HUMAN  zaib!<br /><br />”;
  echo “Please go <a href=’javascript:history.go(-1)’>back</a> and try again.”;
  exit;
}
$USERNAME = $_POST[‘USERNAME’];
$CARDNO = $_POST[‘CARDNO’];
if(empty($USERNAME ) || empty($CARDNO )) {
echo “<h2>You must fill in all fields</h2>\n” ;
die (“Click Back to start again.”);
}
echo “<h2>You have entered the following information: zaib</h2>”;
echo “<pre>Customer name\t=\t$USERNAME <br></pre> “;
echo “<pre>Card No\t\t=\t$CARDNO</pre>”;
echo “<h2>BILLING RESPONSE</h2>”;
echo “======================”;
$var = shell_exec(“TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO”);
echo “<pre>$var</pre>”;
?>

Now result would be as follow

captcha

captcha-wrong


Regard’s
Syed JAHANZAIB


Filed under: Linux Related, Radius Manager

Re-seller Sales Activity Report Via Email in Billing System

$
0
0

This post is my personnel notes (for future retrieval or reference) on a script that can be used to query billing system (in this example Radius Manager) and gather data for all re-seller’s yesterday sales activity and summarize it in a file and email it to Administrator. It comes handy to get idea which dealer made how much sale with number of activated users, sale amount, balance and summarize it in the end for admin view.

As showed in the image below …

2

 

1

 


 

SCRIPT

dealer_renewal_yesterday.sh

  • mkdir /temp
  • touch /temp/dealer_renewal_yesterday.sh
  • chmod +x /temp/dealer_renewal_yesterday.sh
  • nano /temp/dealer_renewal_yesterday.sh

Paste the following data [but do make sure you modify the data like id password or other before deploying it.]


# Script to query all re-seller's account for yesterday's sale and there balances.
# and at end, email the results to admin in html format .

#!/bin/bash
#set -x
clear
# MYSQL USER ID PASSWORD
SQLUSER="root"
SQLPASS="YOUR_SQL_PASSWORD"

# DATE RELATED STUFF
TODAY=`date +"%Y-%m-%d"`
YESTERDAY=`date +"%Y-%m-%d" -d '-1 days'`
CURDATE=`date`

# EMAIL RELATED STUFF
TO1="ADMIN@hotmail.com"
GMAILID="YOURGMAIL_ID@gmail.com"
GMAILPASS="GMAILID_PASSWORD"
CONTENT_TYPE="text/html"

# LOG FILES
FILE="/tmp/dealer_renewal_today.html"
FINALFILE="/tmp/dealer_renewal_today_final.html"
COMPANY="SYED_JAHANZAIB_(Pvt)_Ltd.
This System is powered by Syed_Jahanzaib / aacable@hotmail.com"
BODY_TITLE="Report_For_Dealer_Account_For_$YESTERDAY"
> $FILE
> $FINALFILE

echo "<pre>" > $FILE
echo "<b>$BODY_TITLE</b>" >> $FILE
echo "<b>DEALER            User's_Activated        Used_Amount     Balance</b>" >> $FILE

# QUERY MANAGERS FROM RM_MANAGERS TABLE
mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; select managername from rm_managers;" | while read dealer
do
num=$[$num+1]
DEALER=`echo $dealer | awk '{print $1}'`

# GATHER DATA OF ACTIVE USERS, USED AMOUNT, CURRENT BALANCE, (MOBILE NUMBER IF SMS IS REQUIRED TO SEND)

ACTIVEUSERSNO=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.managername, rm_invoices.username, rm_invoices.date, rm_invoices.expiration, rm_invoices.service, rm_invoices.amount, rm_invoices.price FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$YESTERDAY' AND date <= '$TODAY' AND (paymode = '0'  OR paymode = '2' ) AND (invgroup = '0'  OR invgroup = '1' ) AND invnum != '' AND rm_users.owner = '$DEALER' ORDER BY id LIMIT 0, 500;" | wc -l`

USEDAMOUNT=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.price, rm_invoices.id, rm_invoices.invnum, rm_invoices.managername, rm_invoices.username, rm_invoices.date, rm_invoices.bytesdl, rm_invoices.bytesul, rm_invoices.bytescomb, rm_invoices.downlimit, rm_invoices.uplimit, rm_invoices.comblimit, rm_invoices.time, rm_invoices.uptimelimit, rm_invoices.days, rm_invoices.expiration, rm_invoices.comment, rm_invoices.service, rm_invoices.amount, rm_invoices.paid, rm_invoices.paymentopt, rm_invoices.paymode, rm_invoices.tax, rm_invoices.balance, rm_invoices.invgroup FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$YESTERDAY' AND date <= '$TODAY' AND (paymode = '0'  OR paymode = '2' ) AND (invgroup = '0'  OR invgroup = '1' )  AND invnum != '' AND rm_users.owner = '$DEALER'  ORDER BY id  LIMIT 0, 500;" | sed '/credited/d' | awk '{ sum+=$1} END {print sum}'`

BALANCE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; select balance from rm_managers WHERE managername = '$DEALER';" |cut -f1 -d"."`

MOBILE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; select mobile from rm_managers WHERE managername = '$DEALER';"`

#LOOK FOR ZERO VALUE AMOUNT AND REPLACE IT WITH 0 , IF FOUND
if [ ! -n "$USEDAMOUNT" ]; then
#if [ "USEDAMOUNT  == "" ]; then
USEDAMOUNT="0"

# PRINT ALL GATHERED DATA INTO FILE
echo "$DEALER                   $ACTIVEUSERSNO          $USEDAMOUNT               $BALANCE" >> $FILE
else

# PRINT ALL GATHERED DATA INTO FILE
echo "$DEALER                   $ACTIVEUSERSNO          $USEDAMOUNT               $BALANCE" >> $FILE

fi
done


# MAKE COLUMNS SO THAT IT GETs EASIER TO READS
sed -e 's/\t//g' $FILE |  column -t | awk '1;!(NR%1){print "----------------------------------------------------------------";}' | sed 's/                         //g'  > $FINALFILE

ACTIVE=`cat $FILE | awk '{ sum+=$2} END {print sum}'`
SALE=`cat $FILE | awk '{ sum+=$3} END {print sum}'`
echo "
Total Users Activated/Renewed on $YESTERDAY     = <b>$ACTIVE</b>
Total SALES Done on $YESTERDAY                  = <b>$SALE</b>" >> $FINALFILE


echo "<b>$COMPANY</b>" >> $FINALFILE
echo "</pre>" >> $FINALFILE

#Finally send email with all the data gathered USING SEND_EMAIL TOOL
#/temp/sendEmail-v1.56/sendEmail -t $TO1 -u "INFO: $COMPANY DEALERS DAILY BILLING INFO for $YESTERDAY" -o tls=yes -s smtp.gmail.com:587 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$FINALFILE  -o message-content-type=$CONTENT_TYPE

#If you dont have sendemail utility, then you can simply sms it or cat / echo it.

cat $FINALFILE


 

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 [Life is really easy on ubuntu but with some glitches)

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

TEST SENDING EMAIL

Try to send email using command line: Example

/temp/sendEmail-v1.56/sendEmail -t TO_YOURMAIL@hotmail.com -u "Test Email" -s smtp.gmail.com:587 -xu YOURMGAILID@gmail.com -xp YOURGMAILPASSWORD -f  YOURMGAILIDgmail.com -o tls=yes

If you get message something like “sendEmail[xxxx]: Email was sent successfully!”, then you are good to GO LIVE !


 

Regard’s

Syed Jahanzaib


Filed under: Linux Related, Radius Manager

Sharing Ideas … Get User Account Info via SMS in Radius Manager

$
0
0

userinfo

usereinfo

Changelog:

  • Removed bug , when user have not used any data or account is new, script returns NULL errors
  • Added Online / Offline Status

1- TASK

The task was to provide user a method to inquire his/her account information via sending SMS in specific format to the Billing system.

In this example, we are using DMASOFTLAB Radius Manager as our billing system, and KANNEL along-with the playSMS is already configured and in working condition. kannel+playSMS configuration details have already been described briefly with examples in my previous posts.

We have created an script on the billing system which fetches the user account status and other information from the MYSQL database and print them as per our defined format.

This is just for demonstration purpose. the script have lot of junk data and should be modified before production deployment. I am just sharing some thoughts and ideas only :)

Script is as follows FYR. Hope it may help someone :$

cat userinfo.sh

#!/bin/bash
# Script to check Radius Manager Status , Expiry Date, Service Plan, Data Used
# Syed Jahanzaib
# aacable @ hotmail.com
# http://aacable.wordpress.com
# Modified on 3rd June, 2015

# MYSQL USER NAME AND PASSOWRD Variables
SQLUSER="root"
SQLPASS="zaib1234"
CURRENCY="PKR"

# Check User Validation, if not found exit with error , else continue
echo
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT * FROM radius.rm_users WHERE rm_users.username = '$1';"`
if [ "$USRVALID" == "" ]; then
echo -e "USER NOT FOUND !"
else

######################
# ACCOUNT EXPIRY CHECK
######################

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 = '$1';" |awk 'FNR == 2'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2' | sed 's/00:.*//' | sed -e 's/-//g'`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$1';"  |awk 'FNR == 2 {print $1,$2}'`

if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
        echo "Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE"

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
        echo "ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE"

else
echo -e "Radius Manager User Information Sample:"
echo "Account STATUS= OK!"

###############
# Check Account Expiry Date
EXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
#SRVLIMIT=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT comblimit FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`

#Get ACcounting Data for the Current Month Only
DOWNDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $1}'`

# Check for NULL DATA in download section of user
if [ "$DOWNDATA" == "NULL" ]
then
#       echo "NOT USED NO DOWN DATA FOUND"

#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
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"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2,$3}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = Not Used"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
else

UPDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $2}'`
TOTCOMBINED=`echo "($DOWNDATA+$UPDATA)/(1024)/(1024)" |bc`
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
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"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = $TOTCOMBINED MB"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
# Check User Current Online Status
ONLINE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT framedipaddress FROM radacct WHERE AcctStopTime IS NULL AND UserName = '$1';"`
if [ "$ONLINE" == "" ]; then
echo -e "Current Online Status = OFFLINE"
else
echo -e "Current Online Status = ONLINE"
fi
fi
fi
fi

2- playSMS SECTION

Now we have to add COMMAND in playSMS which will actually receive the sms and will act accordingly if found the keyword info

userinfo-playsms-=command


 3- TEST PHASE

You can test by executing the script or send sms , as per your choice.

Both methods results are as follows …

 

by CLI

userinfo-cli

by SMS

userinfo


 Another Version of GETUSERINFO with VLAN connected users numbers

Another Version of GETUSERINFO with more details like current ONLINE STATUS, and QUOTA assigned, used and left counters.

As showed in the below image …

userinf-2


root@rm:/var/lib/playsms/sms_command/1# cat userinfo.sh
#!/bin/bash
# Script to check Radius Manager Status , Expiry Date, Service Plan, Data Used
# Syed Jahanzaib
# aacable @ hotmail.com
# http://aacable.wordpress.com
# Modified on 9th June, 2015

# MYSQL USER NAME AND PASSWORD Variables
SQLUSER="root"
SQLPASS="sqlapssword"
SQLHOST="localhost"
SQLPORT="3306"
CURRENCY="PKR"

# Check User Validation, if not found exit with error , else continue
echo
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT * FROM radius.rm_users WHERE rm_users.username = '$1';"`
if [ "$USRVALID" == "" ]; then
echo -e "USER NOT FOUND !"
else

######################
# ACCOUNT EXPIRY CHECK
######################

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 -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2' | sed 's/00:.*//' | sed -e 's/-//g'`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$1';"  |awk 'FNR == 2 {print $1,$2}'`

if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
echo "Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE"

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo "ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE"

else
echo -e "Radius Manager User Information Sample:"
echo "Account STATUS= OK!"

###############
# Check Account Expiry Date
EXPIRY=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
#SRVLIMIT=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT comblimit FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`

#Get ACcounting Data for the Current Month Only
DOWNDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $1}'`

# Check for NULL DATA in download section of user
if [ "$DOWNDATA" == "NULL" ]
then
#       echo "NOT USED NO DOWN DATA FOUND"

#UPDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0$
CURRENCY="PKR"
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2,$3}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = Not Used"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
#echo -e "Service Quota Limit = $SRVLIMITMB MB"
#echo -e "Downloaded Data = $DOWNDATAUSED - MB"
#echo -e "Uploaded Data = $UPDATAUP - MB"

else

UPDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $2}'`
TOTCOMBINED=`echo "($DOWNDATA+$UPDATA)/(1024)/(1024)" |bc`
TOTCOMBINED2=`echo "($TOTCOMBINED)/(1024)" |bc`
#SRVLIMITMB=`echo "($SRVLIMIT)/(1024)/(1024)" |bc`
#DOWNDATAUSED=`echo "($DOWNDATA)/(1024)/(1024)" |bc`
#UPDATAUP=`echo "($UPDATA)/(1024)/(1024)" |bc`
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# Print Service Download Limit QUOTA - TOTAL
QUOTA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT trafficunitcomb FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Quota Allowed = $QUOTA MB"
echo -e "Total Data Used in $ALPHAMONTHYEAR = $TOTCOMBINED MB"
QUOTALEFT=`echo "( $QUOTA)-($TOTCOMBINED)" |bc`
echo -e "Total Quota LEFT = $QUOTALEFT MB"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
# Check User Current Online Status
ONLINE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT framedipaddress FROM radacct WHERE AcctStopTime IS NULL AND UserName = '$1';"`
if [ "$ONLINE" == "" ]; then
echo -e "Current Online Status = OFFLINE"
else
echo -e "Current Online Status = ONLINE"
fi
fi
fi
fi

 

Regard’s
SYED JAHANZAIB

 


Filed under: Linux Related, Radius Manager

Gnuplot = The DADA ABBU (Grandfather) of Graphing done via CLI

$
0
0

1-data-downloaded-in-year


 

Whatis Gnuplot:

As defined the Wikipedia. …

Gnuplot is a command-line program that can generate two- and three-dimensional plots of functions, data, and data fits. It is frequently used for publication-quality graphics as well as education. The program runs on all major computers and operating systems (GNU/Linux, Unix, Microsoft Windows, Mac OS X, and others).

I remember when I got in love with the MRTG and I spent many nights in mastering this giant. MRTG is overall a very good graphing too graph about any device but it usually works with snmp (and in some cases with shell scripts too). But what if I have data in a file with simple human readable format and I want to plot different columns in it? MRTG will not help in such cases, Gnuplot will come to rescue :)

I used Gnuplot to graph user download for the current month, In this example user data is taken from MYSQL radius DB and then graphed/plotted with Gnuplot.

As always being a duffer , dumber and incompetent, It took me 2-3 Days of continuous efforts to make it as a single script to make it bundled package.

Requirements for this script:

[You can modify it as per your requirements very easily, I just made it as per my own requirements : D ]

  1. Linux / Ubuntu
  2. Mysql with Radius DB
  3. Gnuplot

What this script will do ?

This script will take accounting data for the specified users for the current month by auto detecting the month/year.The file will look something like following

2015-03-01   1688961371   937706875
2015-03-02   2989190965   2974464964
2015-03-04   534479492   31747041
2015-03-05   809968366   170112567
2015-03-06   2189812711   1555484772

First column is DATE
Second column is user DOWNLOADED data in bytes
Third column is user UPLOADED data in bytes
Then it will save this accounting data in /tmp/USERNAME.TXT  (Username is what supplied by the user)
Then gnuplot will start its magic and will graph the data based on the supplied data.


 

To install Gnuplot on Ubuntu , issue following command

apt-get install -y gnuplot

Now create bash script as follows

mkdir /temp
touch /temp/usergraph.sh
nano /temp/usergraph.sh

and paste following. Make sure to change things according to your network

#!/bin/sh
# Freeradius / Mysql user graph ON THE FLY using GNUPLOT
# It will also detect current year and current month and will pull only current time data
# You can modify this function by providing $2 function in the sql command
# By Syed Jahanzaib / aacable [at] hotmail.com
# Last modified on 5th June, 2015

# Defining BASH Variables
SQLUSER="root"
SQLPASS="sqlpassword"
SQLHOST="localhost"

# Date functions to find current date, month year
NOW=$(date)
MONTH=$(date +"-%m")
CMONTH=`echo $MONTH  | sed -e 's/-//g'`
YEAR=$(date +"-%Y")
CYEAR=`echo $YEAR  | sed -e 's/-//g'`
FMONTH=$(date +"%B")
FULLMONTH=`echo $FMONTH # | sed -e 's/-//g'`

# Name of file in which mysql will dump the user accounting data for the current month
TMP="/tmp/$1.txt"

# Fetch Accounting Data from MYSQL Freeradius radius DB, by using current Year/Month using username provide with the script , and output to file
mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST -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, 10) 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, 7) LIKE '$CYEAR-$CMONTH%' AND radacct.username LIKE '$1' AND  FramedIPAddress LIKE '%' AND CallingStationId LIKE '%'   GROUP BY radacct.radacctid
) AS tmp GROUP BY date LIMIT 0, 50;" |awk '{print $1,$2,$3}' > $TMP
sed '1d' -i $TMP

# Run GNUPLOT SCRIPT on the FLY / by zaib
gnuplot << EOF
reset
set terminal jpeg size 1600,600
# Set output according to your requirement, like you can create file with the username for easier identification
set output "/var/www/radius.jpg"
set xdata time
set timefmt "%Y-%m-%d"
set format x "%d/%m"
set xtics 86400
set xtics rotate by -45
set xlabel "Date (day/month)"
set ylabel "Data Downloaded in GB"
set title "$1 - Download/Upload Report $FULLMONTH $YEAR\nThis report was created on $NOW\nPowered by Syed Jahanzaib / aacable@hotmail.com"
set key outside
set grid
set style data histogram
set style histogram cluster gap 1
set style fill solid
set boxwidth 0.9

plot "$TMP" using 1:(\$2/2**30):(sprintf("%.2f", \$2/2**30)) w boxes title "Download" lw 10, \
"$TMP" using 1:(\$3/2**30):(sprintf("%.2f", \$3/2**30)) w boxes lw 6 title "Upload", \
"$TMP" using 1:(\$2/2**30):(sprintf("%.2f", \$2/2**30)) w labels notitle tc rgb 'red', \
"$TMP" using 1:(\$3/2**30):(sprintf("%.2f", \$3/2**30)) w labels notitle tc rgb 'green'

EOF
# GNUPLOT Script ends here
# Thank you : )

 

Running the SCRIPT

Now execute the script by

/temp/usergraph.sh USERNAME

(like usergraph.sh zaib)

If everything goes well and you dont’ see any errors after executing this script, then you can view the output by

http://yourip/radius.jpg

gnuplot


That’s it …

I showed the very basic usage of Gnuplot. Very Very Basic Level of it. This is only what I have learned so far. But Gnuplot can do things beyond your imagination. Look at this gallery.

http://commons.wikimedia.org/wiki/Category:Gnuplot_diagrams

Gnuplot is a very good and customizable tool which is used all over the world to create simple OR very complex graphs in a go. Above all good part is that it can take data from local files and all can be done via scripting or terminal.

You should give it a try :)


Another version which takes year from your input and then create graph for the whole year usage for the network (overall)

This is another version which input year from you and then create graph for the whole year for overall network usage,


root@radius:/temp# cat year.sh
#!/bin/sh
# MYSQL USER NAME AND PASSOWRD Variables
SQLUSER="root"
SQLPASS="SQLPASS"

# Date functions to find current date, month year
NOW=$(date)
MONTH=$(date +"-%m")
CMONTH=`echo $MONTH  | sed -e 's/-//g'`
YEAR=$(date +"-%Y")
CYEAR=`echo $YEAR  | sed -e 's/-//g'`
FMONTH=$(date +"%B")
FULLMONTH=`echo $FMONTH # | sed -e 's/-//g'`

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 '%' AND
FramedIPAddress LIKE '%' AND CallingStationId LIKE '%'
GROUP BY radacct.radacctid
) AS tmp
GROUP BY date
LIMIT 0, 50;"  |awk '{print $1,$2,$3}' >  /tmp/raw

sed '1d' -i /tmp/raw
awk '{ print $1, $2 + $3; }' /tmp/raw > /tmp/final
echo DONE
# Name of file in which mysql will dump the user accounting data for the current month
TMP="/tmp/final"

# Run GNUPLOT SCRIPT on the FLY / by zaib
gnuplot << EOF
reset
set terminal jpeg size 1600,600
# Set output according to your requirement, like you can create file with the username for easier identification
set output "/var/www/radius.jpg"
set xdata time
set timefmt "%Y-%m"
set format x "%Y/%m"
#set ytics 1
set xtics rotate by -45
set xlabel "Date (month/year)"
set ylabel "Data Downloaded in GB"
set title "Download/Upload Report for $1\nThis report was created on $NOW\nPowered by Syed Jahanzaib / aacable@hotmail.com"
set key outside
set grid
set style data histogram
set style histogram cluster gap 1
set style fill solid
set boxwidth 0.9

plot "$TMP" using 1:(\$2/2**30):(sprintf("%.0f", \$2/2**30)) w boxes title "Download" lw 10, \
"$TMP" using 1:(\$2/2**30):(sprintf("%.0f", \$2/2**30)) w labels title "Data in GB" center offset 0,1 tc rgb 'red'

EOF
# GNUPLOT Script ends here
# Thank you : )

Now execute script as follows

./year.sh 2015

you ahve to supply year o it will generate overall graph which will look odd as we are graphing details for 1 year only,

Sample of above script will generate graph as follows

1-data-downloaded-in-year

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

Send Expiry Alert via SMS/Email For Freeradius/Mysql Users

$
0
0

 

 

sms-alert

As some one asked me on howto send sms (or possibly email) to users whose expiry is after XX days in freeradius/mysql base billing system, Here is a simple script to do the task. It’s not very elegant way to achieve the task but since I donot have any programming level experience so this is how achieve it some Desi style coding :) & the good part is , It’s doing the job and you can at least get some ideas from the code.

So basically this post is just another Sharing Idea’s Series


 

Requirements:

  • You must have working billing system in freeradius/mysql with the appropriate tables like radius, username, expiration etc.

 

In this example I used Radius Manager base system which also uses FREERADIUS/MYSQL as its backend DB.Radius Manager already have expiry alerts notification in its core configurable via web panel, but its a 3rd party paid application. So I am showing you a way howto achieve the same with your own billing system.

So basically what I did was to simply ran mysql query which pulled user name and mobile number from the table [mobile number column must be be created with appropriate values] and exported it to local file. Then I applied a simple ‘Loop‘ formula to go through this file and then applied appropriate action in the end like send SMS via mobile / usb modem attached , use any external http Gateway , or send EMAIL.

You can use this logic to achieve the results on about any other billing system (which is open source or readable) OR any other purposes as well.

Just Go through this script ,its very simple, modify it as per your network and setup. If you manage to add some enhancements, do post here for the sake of every one. :~)

I will add some more details later.

Happy Alerting !

Syed Jahanzaib


Create SMS Script

mkdir /temp
touch /temp/sms.sh
chmod +x /temp/sms.sh
nano /temp/sms.sh

Now paste the following script

#!/bin/sh
# BASH base SMS script for sending expiry notification for Freeradius/mysql users
# the simple logic can be applied for about any other task as well.
# I tried to make it as simple as it can be
# By Syed Jahanzaib
# Created on : 8th June, 2015

SQLUSER="root"
SQLPASS="sqlpassword"
# Interval before alert which should be sent to user before this number days
EXPIRY="3"

# Export usernames and mobile from the mysql table in a file,  which Expiry is after 3 days
mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT username,mobile FROM radius.rm_users  WHERE expiration = DATE_ADD(CURDATE(), INTERVAL $EXPIRY DAY);" > /tmp/list

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
cat /tmp/list |sed '1d' |awk 'NF > 1' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $1}'`
mobile=`echo $users | awk '{print $2}'`

# Add action like send sms or email as per required or designed / zaib
# Here I am just echoing , You must change this if you want some action liek sms or mail as showed in the end
echo "Dear $username, Your account will expire after 3 days. Your cell is $mobile"

# GAMMU SENDMS Example
# gammu sendsms TEXT $mobile -text "Dear $username, Your account will expire after 3 days / ABC ISP"

# KANNEL SMS HTTP GATEWAY Example, 192.168.1.1 is kannel server ip
# curl "http://192.168.1.1:13013/cgi-bin/sendsms?username=kannel&password=KANNELPASS&to=$mobile&text=Dear+$username+Your+account+will+expire+after+3+days++ABC+ISP

# Email Example using -mail- tool
# mail -s 'Dear $username, Your account will expire after 3 days / ABC ISP' $email

done

 

OUTPUT:

[Just echoing in this example]

Run the script manually for test purposes and you should then be able to see something like if you already have proper billing configured with enough data. Below example is a working radius system showing accounts with mobile numbers which will expire in next 3 days. We can show more info if required.

 

sms-alert-list


 

Schedule to run it DAILY

You can schedule it to run on daily basis so it can check for accounts expiring on next xx days and take appropriate action as required.

Example of scheduled job bycrontabcommand:

crontab -l

@daily /temp/sms.sh

With above code, this script will run daily at 00:00 hours [in night] daily. Then it will search for accounts whose account will expire after 3 days, then it will take defined action.

Jz!

 


Filed under: Linux Related, Radius Manager

Freeradius/mysql Account Expiry SMS notification Script using ‘itelservices.net’ bulk SMS Gateway

$
0
0

sms

This post is somewhat very specific to PK base bulk sms provider API. Its a simple bash script made on someone’s request [who had a custom billing system based on freeeradius/mysql] and it can be used to send account expiry notifications to users using freeradius/mysql account query  , BUT specifically using HTTP base SMS Gateway services from http://itelservices.net/

However this specific SMS gateway was a bit different as compared to our KANNEL base gw.

  1. It requires ‘Unique transaction ID’ for each sms, therefore i used current time/seconds with username as Transaction ID
  2. The number should be in international format like 923333021909 and the problem was that the operator had simple format for mobile numbers like 03333021909 is all accounts, and it was not acceptable from the API provider, therefore as a workaround, I used awk/sed tools to remove 0 and then in curl added 92 before every number.

At the moment there are two scripts

1- SMS for account expiry notification
2- SMS for new account creation with user details if possible

You must modify the script as required. This is just a simple way to achieve this task, however there are more sophisticated method like using php or other programing language, I just prefer to select the BASH route !

 

Posting it for   H U M A S   as I love them, They’re Amazing ! :)


1- SMS for account expiry notification

 

mkdir /temp
touch /temp/sms.sh
chmod +x /temp/sms.sh
nano /temp/sms.sh

Now paste the following code.

#!/bin/sh
# set -x
# BASH base SMS script for sending expiry notification for Freeradius/mysql users
# the simple logic can be applied for about any other task as well.
# I tried to make it as simple as it can be
# By Syed Jahanzaib
# Created on : 8th June, 2015
# Modified on : 18th june, 2015
# This script was specially modified for APITEL http sms gateway services
# which requires unique transaction ID each time, so i used datetimesecond feature as jugaar
# made for KHI

# MYSQL root id and password
SQLUSER="root"
SQLPASS="sqlpass"
DB="radiusdb"

# APITEL User Name & Password, must be filled
APIUSER="xxxx"
APIPASS="xxxx"
API="YOURSENDERNAME"

# Date functions to find current date, month year and Transaction id using seconds ; ) jugaar way ; )
NOW=$(date)
TID=$(date +"-%s")

# Interval before alert which should be sent to user before this number days
EXPIRY=3

# Export usernames and mobile from the mysql table in a file,  which Expiry is after 3 days
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; SELECT login,mobile FROM users WHERE expirydate = DATE_ADD(CURDATE(), INTERVAL $EXPIRY DAY);"
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; SELECT login,mobile FROM users WHERE expirydate = DATE_ADD(CURDATE(), INTERVAL $EXPIRY DAY);" > /tmp/list

# Remove 0 if any in mobile number and export it to final list
cat /tmp/list | awk '{gsub("^0","",$2); print $1,$2}' > /tmp/finallist

# Add DATE TIME in sms.log to separate date wise entries / zaib
echo ====================================================== >> /var/log/sms.log
echo $NOW >> /var/log/sms.log
echo ====================================================== >> /var/log/sms.log

# Add DATE TIME in smsapi.log to separate date wise entries WITH API STATUS for cross verification / zaib
echo ====================================================== >> /var/log/smsapi.log
echo $NOW >> /var/log/smsapi.log
echo ====================================================== >> /var/log/smsapi.log

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
cat /tmp/finallist |sed '1d' |awk 'NF > 1' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $1}'`
mobile=`echo $users | awk '{print $2}'`

# SMS Body
BODY="Soft+Reminder:+Dear+$username,+Your+Internet+Service++Will+Expire+after+$EXPIRY+days++++zaibisp"

echo "$NOW ! Expiry Notification have been sent to $username, on cell number 0$mobile"
echo "$NOW ! Expiry Notification have been sent to $username, on cell number 0$mobile" >> /var/log/sms.log

# Add action like send sms or email as per required or designed / zaib
# Sending sms via APITEL API SMS Gatewy / syed jahanzaib / aacable@hotmail.com

curl "http://api1.itelservices.net/send.php?transaction_id=$TID$username&user=$APIUSER&pass=$APIPASS?&number=%2B92$mobile&text=$BODY&from=$API" >> /tmp/smsapi.log
done

sed 's/\(Status\)/\n\1/g' /tmp/smsapi.log >> /var/log/smsapi.log
echo ======================================================
echo Result for SMSAPI , so that you can verify that how much sms are actually sent with the status codes
cat  /var/log/smsapi.log



 

CRON JOB TO RUN IT DAILY IN NIGHT

Now set cron job to run it daily in night

@daily /temp/sms.sh


 LOGS

you can view log files in following location
/var/log/sms.log

Sample:

Thu Jun 18 11:43:20 PKT 2015 ! Expiry Notification have been sent to USER1, on cell number 033333333333
Thu Jun 18 11:43:20 PKT 2015 ! Expiry Notification have been sent to USER2, on cell number 0333132121211

/var/log/smsapi.log

Results with status from api gateway services (Useful to track the messages are actually sent or having errors from provider like server down, credit finished etc etc)

Sample:

Status: 013, Id: -1434609800USER1, Number: +923452266605
Status: 013, Id: -1434609800USER2, Number: +923222656143


2- SMS for NEW Account Creation

1

mkdir /temp
touch /temp/sms-new-account.sh
chmod +x /temp/sms-new-account.sh
nano /temp/sms-new-account.sh

#!/bin/sh
# set -x
# BASH base SMS script for NEW ACCOUNTnotification for Freeradius/mysql users
# the simple logic can be applied for about any other task as well.
# I tried to make it as simple as it can be
# By Syed Jahanzaib
# CREATED on : 19th june, 2015
# This script was specially modified for APITEL http sms gateway services
# which requires unique transaction ID each time, so i used datetimesecond feature as jugaar
# made for KHI/PK

# MYSQL root id and password
SQLUSER="root"
SQLPASS="pass"
DB="radius-db"

# APITEL User Name & Password
APIUSER="APIUSER"
APIPASS="APIPASS"
API="SENDERID"

# Date functions to find current date, month year and Transaction id using seconds ; ) jugaar way ; )
NOW=$(date)
TID=$(date +"-%s")

# Check Account which are created before this number of MINUTES
CREATION=5

touch /tmp/sms-new-account.log
touch /tmp/sms-new-account-api.log
> /tmp/sms-new-account.log
> /tmp/sms-new-account-api.log

# Export usernames and mobile from the mysql table in a file,  which Expiry is after 3 days
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e "use $DB; select creationdate,login,package,expirydate,mobile from users WHERE creationdate >= NOW() - INTERVAL $CREATION MINUTE;"`
mysql -u$SQLUSER -p$SQLPASS -e "use $DB; select creationdate,login,package,expirydate,mobile from users WHERE creationdate >= NOW() - INTERVAL $CREATION MINUTE;" > /tmp/newact

# Check User Validation, if not found exit with error , else continue
echo
if [ "$USRVALID" == "" ]; then
echo -e "No new user created in last minutes, so nothign to do , zaib !"
else
echo -E "user Created found , proceeding..."

# Remove 0 if any in mobile number and export it to final list
cat /tmp/newact | awk '{gsub("^0","",$7); print $1,$2,$3,$4,$5,$6,$7}' > /tmp/newactfinal

# Add DATE to separate entries in sms-new-account.log
echo ================================ >> /var/log/sms-new-account.log
echo $NOW >> /var/log/sms-new-account.log
echo ================================ >> /var/log/sms-new-account.log

echo ================================ >> /var/log/sms-new-account-api.log
echo $NOW >> /var/log/sms-new-account-api.log
echo ================================ >> /var/log/sms-new-account-api.log

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
cat /tmp/newactfinal |sed '1d' |awk 'NF > 6' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $3}'`
mobile=`echo $users | awk '{print $7}'`
pkg=`echo $users | awk '{print $4}'`
exp=`echo $users | awk '{print $5}'`
#echo "Welcome to MYNET Broadband Services! Your account details are as follow...
#Username = $username
#Package = $pkg
#Expiry = $exp
#Cell No = $mobile"

# SMS Body
BODY="Welcome+to+MYISP+Services,+Your+account+details+are:++id=$username+/+Package=+$pkg+/+Expiry=+$exp+/+Cell=+0$mobile++++MYISP+BROADBAND"

echo "$NOW ! New Acount Creation Notification have been sent to $username, on cell number 0$mobile"
echo "$NOW ! New Acount Creation Notification have been sent to $username, on cell number 0$mobile" >> /var/log/sms-new-account.log

# Add action like send sms or email as per required or designed / zaib
# Sending sms via APITEL API SMS Gatewy / syed jahanzaib / aacable@hotmail.com

curl "http://api1.itelservices.net/send.php?transaction_id=$TID$username&user=$APIUSER&pass=$APIPASS?&number=%2B92$mobile&text=$BODY&from=$API" >> /tmp/sms-new-account-api.log
sed 's/\(Status\)/\n\1/g' /tmp/sms-new-account-api.log >> /var/log/sms-new-account-api.log
echo
echo Result for SMSAPI , so that you can verify that how much sms are actually sent with the status codes
#cat  /var/log/sms-new-account.log
done

fi

Cron it to run after every 5 minutes

*/5 * * * * /temp/sms-new-account.sh


 3- SMS for ALL users (I deployed it for Webmin usage)


#!/bin/bash
# set -x
# Script to send GENERAL SMS via WEBMIn
# Syed Jahanzaib
# aacable @ hotmail.com
# https://aacable.wordpress.com
# Created on 24th June, 2015

SQLUSER="root"
SQLPASS="mysqlpassword"
DB="radiusdb"

# APITEL User Name & Password
APIUSER="xxxx"
APIPASS="xxxxx"
API="xxxx"

######################
# ACCOUNT EXPIRY CHECK
######################

# Date functions to find current date, month year and Transaction id using seconds ; ) jugaar way ; )
NOW=$(date)
TID=$(date +"-%s")

# Adding files
touch /tmp/smspanel.log
touch /tmp/smapanel-api.log
> /tmp/smspanel.log
> /tmp/smapanel-api.log

mysql -uroot -pgatewayb3 -e "use mynet; SELECT login,mobile FROM users;"  > /tmp/smspanellist

# Remove 0 if any in mobile number and export it to final list
cat /tmp/smspanellist | awk '{gsub("^0","",$2); print $1,$2}' > /tmp/smspanellistfinal

# Add DATE TIME in /tmp/smspanel.log to separate date wise entries / zaib
echo ====================================================== >> /var/log/smspanel.log
echo $NOW >> /var/log/smspanel.log
echo ====================================================== >> /var/log/smspanel.log

# Add DATE TIME in /tmp/smspanel-api.log to separate date wise entries WITH API STATUS for cross verification / zaib
echo ====================================================== >> /var/log/smspanel-api.log
echo $NOW >> /var/log/smspanel-api.log
echo ====================================================== >> /var/log/smspanel-api.log

# Apply Count Loop Formula while deleting first line which have simple text, and also any line which dont have mobile number [in second column]
num=0
# remove first line which have simple text, then remove dash in second column which is mobile numbers
cat /tmp/smspanellistfinal |sed '1d' |awk 'NF > 1' | awk '{gsub("-","",$2)}1' | while read users
do
num=$[$num+1]
username=`echo $users |awk '{print $1}'`
mobile=`echo $users | awk '{print $2}'`

# SMS Body in local file and remove new lines and replace spaces with plus sign for api acceptance
BODY=`cat /tmp/smspanelmsg.txt  |tr '\r\n' ' ' | sed -e "s/\s\{1,\}/+/g"`

#echo "$NOW ! $BODY ---- MSG was sent to $username, on cell number 0$mobile"
echo "$NOW ! Your MSG was sent to $username, on cell number 0$mobile" >> /var/log/smspanel.log

# Sending sms via APITEL API SMS Gatewy / syed jahanzaib / aacable@hotmail.com

curl "http://api1.itelservices.net/send.php?transaction_id=$TID$username&user=$APIUSER&pass=$APIPASS?&number=%2B92$mobile&from=$API&text=$BODY" >> /tmp/smspanel-api.log
sed 's/\(Status\)/\n\1/g' /tmp/smspanel-api.log >> /var/log/smspanel-api.log
done

 

ITELSERVICES.NET related information

Sample of URL to send SMS

http://api1.itelservices.net/send.php?transaction_id=message1&user=bilal&pass=bilal2015?&number=%2B923333021909&text=hello&from=MyNet

Please note that the transaction id must be unique for each sms, example message1, message2 and so on any word is acceptable, i used date time as transaction id, you may use your own.

 

INFORMATION AND ERROR CODES related to API

For the information/error codes

 

1

 

2

 

3


 

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

RADIUS Redundancy by using MYSQL Master-Master Replication

$
0
0

master-master

In this Guide, I will show you howto create replica of your radius server so that in case of any server failure , you can instantly switch to backup server with the latest data available. In this model we will use MYSQL master-master concept in which whatever changes / records you make on any server, it will replicate to other as well. Also in mikrotik we can use primary and secondary radius server entries OR we can make a script to detect both radius status and act accordingly, all depend on your network requirements & infrastructure.

Scenario:

In this example we have RADIUS MANAGER billing system which uses freeradius and MYSQL DB as its backend engine,  installed (with basic level of installation) on two servers. Now we want to create redundancy by replicating radius DB to each other so that in case of one server failure, second server should come to rescue.

Requirements:

  • I assume that you have working radius manager installed on both PC and tested its working by creating users in it.

Components Used:

  • SERVER1 NAME = MASTER-RADIUS
    OS = Centos 6.5 32bit
    IP = 101.11.11.241
  • SERVER2 NAME = REPLICA-RADIUS
    OS = Centos 6.5 32bit
    IP = 101.11.11.245
  • MIKROTIK PPPOE SERVER = Mikrotik
    OS = Mikrotik 5.xx
    IP = 101.11.11.255

Let’s Start

 

Step – 1

Server1 = ‘master-radius’ Configuration

Open mysql config file

nano /etc/my.cnf

and add following under [mysqld] section

log-bin=mysql-bin
binlog-do-db=radius
server-id=1
auto_increment_increment = 2
auto_increment_offset = 1

SAVE and EXIT.

Now restart mysqld service so changes can take effect.

service mysqld restart

Now we need to create a user that will be used by mysql for replicating data between our two radius (or mysql) servers. As an example I am using id “zaib”. Replace “password” with the password you wish to use for replication.

create user 'zaib'@'%' identified by 'password';
grant replication slave on *.* to 'zaib'@'%'; 

Now we need to get some information about the current MySQL instance which we will later provide to server2 (replica).

The following command will output a few pieces of important information, which we will need to make note of:

show master status;

The output will look similar to the following, and will have two pieces of critical information: [file and position note it down)

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      336 | radius       |                  |
+------------------+----------+--------------+------------------+

1 row in set (0.00 sec)

We need to make a note of the file and position which will be used in the next step.


 

Step – 2

Server2 = ‘replica-radius’ Configuration

 

Open mysql config file

nano /etc/my.cnf

and add following under [mysqld] section

log-bin=mysql-bin
binlog-do-db=radius
server-id=2
auto_increment_increment = 2
auto_increment_offset = 2

Make sure server-id is different then primary server

SAVE and EXIT.

Now restart mysqld service so changes can take effect.

service mysqld restart

Here we are going to create the user which will be responsible for the replication. Replace “password” with the password you wish to use.

create user 'zaib'@'%' identified by 'password';
grant replication slave on *.* to 'zaib'@'%'; 

The next step involves taking the information that we took a note of earlier and applying it to our mysql instance. This will allow replication to begin. The following should be typed at the mysql shell:

slave stop;

CHANGE MASTER TO MASTER_HOST = '101.11.11.241', MASTER_USER = 'zaib', MASTER_PASSWORD = 'password', MASTER_LOG_FILE = 'mysql-bin.000001', MASTER_LOG_POS = 336;

slave start; 

Your values for MASTER_LOG_FILE and MASTER_LOG_POS may differ than those above. You should copy the values that “SHOW MASTER STATUS” returns on Server-1.

 

The last thing we have to do before we complete the mysql master-master replication is to make note of the master log file and position to use to replicate in the other direction (from Server 2 to Server 1).

We can do that by typing the following:

SHOW MASTER STATUS; 

The output will look similar to the following:

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000002 |      125 | radius       |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

Take note of the file and position, as we will have to enter those on server 1, to complete the two-way replication.

The next step will explain how to do that.

 

Step – 3

Completing Replication on Server1 [Master-radius]

Back on Server 1, we need to finish configuring replication on the command line.

Running this command will replicate all data from Server 2.

slave stop;
CHANGE MASTER TO MASTER_HOST = '101.11.11.245', MASTER_USER = 'zaib', MASTER_PASSWORD = 'password', MASTER_LOG_FILE = 'mysql-bin.000002', MASTER_LOG_POS = 125;
slave start; 

Keep in mind that your values may differ from those above. Please also replace the value of MASTER_PASSWORD with the password you created when setting up the replication user.

The output will look similar to the following:

Query OK, 0 rows affected (0.01 sec)

 

Now test the status by issuing command to mysql cli

show slave status\G

and you should see something similar to this. [don’t get confused with different numbers of log file file and position number, as this snap was taken in another lab]

replica-status


 

TEST

The last thing to do is to test that replication is working on both servers.

Open server1 radius panel, and try to create new user, after creation, it will be automatically replicated to server2 : )

As showed in the images below …

At a moment no users have been created.

server1-empty

 

Now create test user

server1-users-create

 

After creation, Goto Server2 (Replica) and check Users List, and you will find the user replicated.

server2-new0user0replicate-ok

and when you will create any user , it will replicate back to server1.


Adding both Radius Server entries in Mikrotik

Add both radius server

add-radius

and at radius manager, add the NAS (mikrotik)

add-nas

Don’t forget to rebuild clients.conf (from the menu) at secondary radius as well.

Now test by connecting any client , once successful, disconnect the primary radius, and try to connect the client again, once mikrotik will be unable to find primary entry, it will auto contact secondary server. as showed in the images below …

2radius

I will add few more details later….

 

Regard’s
Syed Jahanzaib

 


Filed under: Linux Related, Radius Manager

Modifying MYSQL table to add hh:mm in date to facilitate Radius Manager SMS sending upon account renewal

$
0
0

Personnel Notes: For future retrieval of the code

1

2

Task:

DMASOFTLAB Radius Manager have the limited facility to send sms on different events like account creation welcome msg, expiry, password retrieval.

rmRM send following SMS upon new account creation

Welcome to our system! Your account name is {USERNAME}, password is {PASSWORD}

But the OP wanted to send some customized SMS with few other info as well like login details, upon every account renewal (which RM does not support).

+ the system should be able to detect that if the account is registered today, then it should send WELCOME message along with details, BUT if the account is old and only it get renewed, then it should send RENEWAL message.


 

 

Solution:

First you need to modify the DATE type to DATETIME in rm_invoices table, you can use phpmyadmin to do the task easily, or use the command as follows:

login to mysql and issue following commands

use radius;
ALTER TABLE `rm_invoices` CHANGE `date` `date` DATETIME NOT NULL ;

Now you can use following script.

mkdir /temp
touch /temp/expirynotification.sh
chmod +x /temp/expirynotification.sh
nano /temp/expirynotification.sh

Add following date in the script

#!/bin/sh
# set -x
# BASH base SMS script for NEW ACCOUNT / RENEWAL notification for RADIUS MANAGER based on Freeradius/mysql
# the simple logic can be applied for about any other task as well. I tried to make it as simple as it can be
# By Syed Jahanzaib
# CREATED on : 16th July, 2015

SQLUSER="root"
SQLPASS="sql_password"
MNT="5"
CURDATE=`date`
KANNELID="kannel"
KANNELPASS="kannelpass"
GMAILID="yourgmailid"
GMAILPASS="yourgmailpass"
ADMINMAIL="aacable@hotmail.com"

# Setting Date as variable
TODAY=$(date +"%Y-%m-%d")
# Removing DASH from date to use it in compare formula later
TODAYDIGIT=`echo $TODAY  | sed -e 's/-//g'`

> /var/log/renewal.log

# Simply print the info
mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT rm_invoices.username, rm_invoices.paid, rm_users.createdon, rm_invoices.expiration, rm_users.mobile, rm_users.owner  FROM rm_invoices INNER JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= NOW() - INTERVAL $MNT MINUTE  AND (paymode = '0' ) AND (invgroup = '0'  OR invgroup = '1' );"

# Check User Validation, if not found exit with error , else continue
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT rm_invoices.username, rm_invoices.paid, rm_users.createdon, rm_invoices.expiration, rm_users.mobile FROM rm_invoices INNER JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= NOW() - INTERVAL $MNT MINUTE  AND (paymode = '0' ) AND (invgroup = '0'  OR invgroup = '1' );"`
if [ ! -n "$USRVALID" ]; then
echo  "No account have been updated in last $MNT minutes !"
exit 0
fi

# Fetch user account details which were created in last 5 minutes from rm tables using inner joing function in mysql
mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT rm_invoices.username, rm_invoices.paid, rm_users.createdon, rm_invoices.expiration, rm_users.mobile, rm_users.owner FROM rm_invoices INNER JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= NOW() - INTERVAL $MNT MINUTE  AND (paymode = '0' ) AND (invgroup = '0'  OR invgroup = '1' );" > /tmp/temp

# Apply Count Loop Formula while deleting first line which have junk text
num=0
cat /tmp/temp |sed '1d' | while read users
do
num=$[$num+1]
username=`echo $users | awk '{print $1}'`
paidwod=`echo $users | awk '{print $2}' | sed -e 's/-//g'`
paid=`echo $users | awk '{print $2}'`
cratedwod=`echo $users | awk '{print $3}' | sed -e 's/-//g'`
crated=`echo $users | awk '{print $3}'`
expiration=`echo $users | awk '{print $4}'`
mobile=`echo $users | awk '{print $5}'`
dealer==`echo $users | awk '{print $6}'`

#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$username';" |awk 'FNR == 2 {print $1}'`

# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# If user account creation date is today, then send welcome message with other details
if [ $cratedwod  -eq $paidwod ]
then

# Use following if you want to send SMS
# curl "http://localhost:13013/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$mobile&text=Welcome+$username,%0AYour+Internet+Services+have+been+activated+with+$PKGNAME+Service.%0ALogin+details+are+username+=+$username%0AActivation+Date+=+$paid%0AExpiration+Date=+$expiration%0AGALAXY+TECH"
# Or just ECHO
echo "$CURDATE : Following account creation and renewal have been done \nUsername = $username \nPacakge = $PKGNAME \nNext Expiry = $expiration" > /var/log/renewal.log
echo "**********************" >> /var/log/renewal.log

# If you want to send email , use below ...
#/temp/sendEmail-v1.56/sendEmail -t aacable@hotmail.com -u "Account Creation/Renewal Report" -o tls=yes -s smtp.gmail.com:587 -xu aacablenetworks@gmail.com -xp CapricorN*88 -f aacablenetworks@gmail.com -o message-file=/var/log/renewal.log  -o message-content-type=text

# Delete the today account so that separate message should be sent to old users
sed -i "/$username/d" /tmp/temp

# If user account creation date is old, then send RENEWAL message with other details
else

# If you want to send sms then use curl
#curl "http://localhost:13013/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$mobile&text=Dear+$username,%0AYour+Internet+Services+have+been+activated+with+$PKGNAME+Service.%0ALogin+details+are+username+=+$username%0AActivation+Date+=+$paid%0AExpiration+Date=+$expiration%0AGALAXY+TECH"
# OR simply ECHO print the data
echo "$CURDATE : \nDEALER  $dealer \nFollowing account renewal have been done \nUsername = $username \nPacakge = $PKGNAME \nNext Expiry = $expiration" >> /var/log/renewal.log
echo ================================================= >> /var/log/renewal.log
# OR EMAIL the Result
#/temp/sendEmail-v1.56/sendEmail -t $ADMINMAIL -u "GT $CURDATE : Account Renewal Report of last $MNT minutes" -o tls=yes -s smtp.gmail.com:587 -xu $GMAILID@gmail.com -xp $GMAILPASS -f aacablenetworks@gmail.com -o message-file=/var/log/renewal.log  -o message-content-type=text
#/temp/sendEmail-v1.56/sendEmail -t thestrangeryes@hotmail.com -u "GT $CURDATE : Account Renewal Report of last $MNT minutes" -o tls=yes -s smtp.gmail.com:587 -xu $GMAILID@gmail.com -xp $GMAILPASS -f aacablenetworks@gmail.com -o message-file=/var/log/renewal.log  -o message-content-type=text

fi
done

For test, renew two accounts using RM / add credits section in respective users. One account that should be created today, and one account which was created earlier. and you may see following results : )


[root@radius-master temp]# ./expirynotification.sh
+-----------+------------+------------+------------+
| username  | paid       | createdon  | expiration |
+-----------+------------+------------+------------+
| todayuser | 2015-07-16 | 2015-07-16 | 2015-08-16 |
| olduser   | 2015-07-16 | 2014-01-16 | 2015-08-16 |
+-----------+------------+------------+------------+
Welcome todayuser, Your Internet Services have been activated with 1mb  Service. Login details are / username = todayuser / Activation Date = 2015-07-16 / Expiration Date= 2015-08-16
Dear olduser, Your account have been renewed with 2mb Service. Login details are / username = olduser / Renewal Date = 2015-07-16 / Expiration Date= 2015-08-16

olduser

Note: for demonstration purpose, I printed the output using echo command, you can use your other tools to send sms using your local mobile/usb modem using GAMMU, or http base sms gateway using curl. i wrote many examples on it in previous posts.

 


 

Regard’s
Syed Jahanzaib

 


Filed under: Linux Related, Radius Manager

Enabling Authentication Logs in Freeradius

$
0
0

logs-error

Sometimes in freeradius base billing system, user is unable to authenticate with the system. To quickly investigate the issue, its better to enable freeradius authentication logs to see if its the user end id password issue or something else.

To enable Free- Radius LOGS to get additional information on users authentication ,

Edit /usr/local/etc/raddb/radiusd.conf

nano /usr/local/etc/raddb/radiusd.conf

and modify following

auth = no
auth_badpass = no
auth_goodpass = no

to following

auth = yes
auth_badpass = yes
auth_goodpass = yes

Save and Exit.

Now restart radius service by

service radiusd restart

Check Logs by

tail -f /usr/local/var/log/radius/radius.log

and you will AUTH logs for Good and Bad Login Attempts, It helps a lot in troubleshooting troubled users.

Thu Aug  6 14:52:06 2015 : Auth: Login OK: [usernameX/username] (from client CCR-GW port 15747979 cli xx:D1:11:64:B8:39)
Thu Aug  6 14:52:07 2015 : Auth: Login OK: [usernameX/username] (from client CCR-GW port 15747975 cli xx:44:76:72:A7:9C)
Thu Aug  6 14:52:08 2015 : Auth: Login OK: [usernameX/username] (from client CCR-GW port 15747978 cli xx:44:76:72:9E:9C)

Thu Aug  6 14:58:48 2015 : Auth: Login incorrect: [usernameY<via Auth-Type = mschap>] (from client pppoe2 port 16056177 cli xx:DE:27:2F:23:95)
Thu Aug  6 14:58:49 2015 : Auth: Login incorrect: [usernameZ/<via Auth-Type = mschap>] (from client pppoe1 port 15819569 cli xx:F3:C1:AD:70:17)

 

Regard’s

Syed Jahanzaib

 

 


Filed under: Linux Related, Radius Manager

Passing PHP variables to Shell Script with CAPTCHA code [Example renew account via web]

$
0
0


For my personnel archive purpose only:

All of these tests were made in lab and later on tested on production network as well and worked perfectly. BUT before deploying it in production, one must ensure security , specially try to host it on https server, MUST add captcha in form to prevent BOTS attack, + one should consider BASH security and trimming + some functions to match with real live environment. all can be done easily if you have some knowledge on html/php/bash.


 

Scenario:

A simple portal page is required where user can input there user name and refill code in order to renew there internet account on billing system [in this example radius manager is being used]. then this html page will pass the user name and card number variable to php page which will execute an shell script to trigger renewal action based on the supplied variables. The shell script will check for following

  • Check for Valid Users name in Billing
  • Check for Valid Card number in billing refill card database
  • Check if card is used or not
  • Check the user current package and compare it with the card value
  • If all OK, renew the user account for next 30 days (or whatever actions is required)
  • Output the result to browser

 


 

Following file will present FORM where user can enter there user name and pin code/refill code.

input.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Refill your account ! </title>
</head>
<body>
<h1>Refill your account using scratch code:</h1>
<form method="post" action="function.php">
User Name: <br />
<input type="text" name="USERNAME" size="35" />
<br />
Card No: <br />
<input type="text" name="CARDNO" size="35" />
<br /> <br />
<input type="submit" value="Submit:" />
<br />
</form>
</body>
</html>

Following file will execute the SHELL script with the supplied username and pincode variable and echo there result in the browser.

function.php

<?php
$USERNAME = $_POST[‘USERNAME’];
$CARDNO = $_POST[‘CARDNO’];

if(empty($USERNAME ) || empty($CARDNO )) {
echo “<h2>You must fill in all fields</h2>\n” ;
die (“Click Back to start again.”);
}
echo “<h2>You have entered the following information:</h2>”;
echo “<pre>Customer name\t=\t$USERNAME <br></pre> “;
echo “<pre>Card No\t\t=\t$CARDNO</pre>”;

echo “<h2>BILLING RESPONSE</h2>”;
echo “======================”;
$var = shell_exec(“TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO”);
echo “<pre>$var</pre>”;
?>



BASH Shell script which will be executed by the function.php file

Contents of /var/www/html/renew.sh

{lab testing version, working ok, it may contain lot of junk or it can be trimmed, it’s upto you to make it look pro}

#!/bin/bash
#set -x
# SCRIPT TO RENEW USER ACCOUNT IN RADIUS MANAGER VIA WEB PORTAL
SQLUSER=”root”
SQLPASS=”zaib1234″
echo $1 $2 > /tmp/user-card
USR=`cat /tmp/user-card | awk {‘ print $1 ‘}`
CARD=`cat /tmp/user-card | awk {‘ print $2 ‘}`
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

#LOOK FOR EMPTY CARD NO IF ENTERED , EXIT
if [ “$1” == “” ]; then
echo -e “ERROR: ENTER USER NAME WITH CARD NUMBER PLEASE!”
exit 0
fi

#LOOK FOR VALID USER IN RADIUS
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = ‘$USR’;”`
if [ “$USRVALID” == “” ]; then
echo -e “ERROR: USER NOT FOUND IN BILLING SYSTEM!!”
exit 0
fi

#LOOK FOR EMPTY CARD NO IF ENTERED , EXIT
if [ “$2” == “” ]; then
echo -e “ERROR: PLEASE ENTER CARD NUMBER!!”
exit 0
fi

# LOOK FOR USED CARDS
CARDSTATUS=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT SQL_CALC_FOUND_ROWS cardnum, used, revoked, expiration, value, date, owner FROM rm_cards WHERE cardtype = ‘1’ AND cardnum = ‘$2’  ORDER BY cardnum ASC LIMIT 0, 50;” |  awk {‘print $8}’`
if [ -n “$CARDSTATUS” ]; then
echo -e “CARD IS ALREADY USED”
exit 0
fi

######################
# ACCOUNT EXPIRY CHECK
######################

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’`
SRVEXPIRYFULLD=`mysql -u$SQLUSER -p$SQLPASS -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:.*//’`
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”.”`
CARDPRICE=`mysql -u$SQLUSER -p$SQLPASS -e “use radius;  SELECT value FROM rm_cards WHERE cardnum = $CARD;” |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))
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = ‘$1’;” |awk ‘FNR == 2 {print $1,$2,$3}’;`

# LOOK FOR VALID REFILL CARD CODE IN RADIUS CARDS LIST
CARDVALIDATION=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT value, expiration FROM rm_cards WHERE cardnum = ‘$CARD’ AND used = ‘0000-00-00 00:00:00’;”`
if [ “$CARDVALIDATION” == “” ]; then
echo -e “ERROR: INVALID CARD NUMBER!”
exit 0
else

# IF CARD VALUE IS LESS THEN CURRENT PACKAGE PRICE THEN PRINT ERROR AND GOTO END
if [ $CARDPRICE -lt $SRVPRICE ]
then
echo -e “ERROR: CARD PRICE IS NOT SUFFICIENT TO REFRESH $PKGNAME SERVICE”
exit 0
else

# IF CARD VALUE IS EQUAL OR HIGHER  THEN CURRENT PACKAGE PRICE THEN OK
if [ $CARDPRICE -eq $SRVPRICE ]
then
echo
fi

########### ACCOUNT STATUS EXPIRED TODAY ACTION ############
if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
echo “Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE”
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

# 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 scratch code by SMS’ 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’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

########### ACCOUNT STATUS EXPIRED IN PAST ACTION ############

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo “ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE”
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

# 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 scratch code by SMS’;”

# ADD SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e “use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), ‘n/a’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

# Update QUOTA for the USER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET comblimit = ‘$PKGQUOTAB’ WHERE username = ‘$USR’;”

else
########### ACCOUNT STATUS OK! ACTION ############

echo -e “User Billing Info:”
echo “Account STATUS= OK!”

NEXTEXPIRYADD=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; select DATE_ADD(expiration, INTERVAL 31 DAY) as x from rm_users where username= ‘$USR’;” |awk ‘FNR == 2’`

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo Owner = $USERFLNAME
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

NEXTEXPIRYADD=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; select DATE_ADD(expiration, INTERVAL 31 DAY) as x from rm_users where username= ‘$USR’;” |awk ‘FNR == 2’`

# 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 scratch code by SMS’ 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’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

fi
fi
fi

########### ACCOUNT STATUS EXPIRED TODAY ACTION ############
if [ $PKGQUOTA -eq 0 ]
then
echo -e “Total Quota Allowed = No Quota”
else
echo -e “Total Quota Allowed = $PKGQUOTAB GB”
fi
echo -e “Done/Note: Card Number $CARD is marked as used in DB to prevent re-usege”


 

RESULTS:

1- enter details


 

If the script found that the user name not valid in the billing , spit the error

0- user not found


 

If the script found that the card number is not available in the billing , spit the error

2- invalid number


 

If the script found that the card number entered is already used , spit the error

3- card already used


 

If the script found both fields blank, spit the error

4- you must fill in all fields


 

If the script found user name and card matches, then proceed to renew the account

5- if all ok renew the account

You can also take different actions like send Email / SMS to ADMIN, and user both or any other action.


 


 


 


 


 

re-captcha

ADDING CAPTCHA SECURITY IN FORM

To add captcha security in html form, (which should be must in my opinion for security reasons)

Download secureimage and unzip in your web folder like /var/www/html/secureimage

mkdir /temp

cd /temp

wget https://www.phpcaptcha.org/latest.tar.gz

tar zxvf latest.tar.gz

mv securimage/ /var/www/html/

Now edit the html form to add the captcha facility

TEST.HTML [Red highlighted are our code for captcha]

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Refill your account ! </title>
</head>
<body>
<h1>Refill your account using scratch code:</h1>
<form method=”post” action=”test.php”>
User Name: <br />
<input type=”text” name=”USERNAME” size=”35″ />
<br />
Card No: <br />
<input type=”text” name=”CARDNO” size=”35″ />
<br /> <br />
<input type=”submit” value=”Submit:” />
<br />
</body>
<img id=”captcha” src=”/securimage/securimage_show.php” alt=”CAPTCHA Image” />
<input type=”text” name=”captcha_code” size=”10″ maxlength=”6″ />
<a href=”#” onclick=”document.getElementById(‘captcha’).src = ‘/securimage/securimage_show.php?’ + Math.random(); return false”>[ Different Image ]</a>
</form>
</html>

TEST.PHP [Red highlighted are our code for captcha]

<?php
include_once $_SERVER[‘DOCUMENT_ROOT’] . ‘/securimage/securimage.php’;
$securimage = new Securimage();
if ($securimage->check($_POST[‘captcha_code’]) == false) {
  echo “The CAPTCHA security code entered was incorrect. Make Sure You are HUMAN  zaib!<br /><br />”;
  echo “Please go <a href=’javascript:history.go(-1)’>back</a> and try again.”;
  exit;
}
$USERNAME = $_POST[‘USERNAME’];
$CARDNO = $_POST[‘CARDNO’];
if(empty($USERNAME ) || empty($CARDNO )) {
echo “<h2>You must fill in all fields</h2>\n” ;
die (“Click Back to start again.”);
}
echo “<h2>You have entered the following information: zaib</h2>”;
echo “<pre>Customer name\t=\t$USERNAME <br></pre> “;
echo “<pre>Card No\t\t=\t$CARDNO</pre>”;
echo “<h2>BILLING RESPONSE</h2>”;
echo “======================”;
$var = shell_exec(“TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO”);
echo “<pre>$var</pre>”;
?>

Now result would be as follow

captcha

captcha-wrong


Regard’s
Syed JAHANZAIB


Filed under: Linux Related, Radius Manager

Re-seller Daily Sales Activity Report Via Email in Billing System

$
0
0

This post is my personnel notes (for future retrieval or reference) on a script that can be used to query billing system (in this example Radius Manager) and gather data for all re-seller’s yesterday sales activity and summarize it in a file and email it to Administrator. It comes handy to get idea which dealer made how much sale with number of activated users, sale amount, balance and summarize it in the end for admin view.

As showed in the image below …

 

1

 

2

1

 


 

SCRIPT

dealer_renewal_yesterday.sh

  • mkdir /temp
  • touch /temp/dealer_renewal_yesterday.sh
  • chmod +x /temp/dealer_renewal_yesterday.sh
  • nano /temp/dealer_renewal_yesterday.sh

Paste the following data [but do make sure you modify the data like id password or other before deploying it.]


# Script to query all re-seller's account for yesterday's sale and there balances.
# and at end, email the results to admin in html format .
# last updated: 25/08/2015
#!/bin/bash
#set -x
clear
# MYSQL USER ID PASSWORD
SQLUSER="root"
SQLPASS="YOUR_SQLPASS"

# DATE RELATED STUFF
TODAY=`date +"%Y-%m-%d"`
YESTERDAY=`date +"%Y-%m-%d" -d '-1 days'`
CURDATE=`date`

# EMAIL RELATED STUFF
TO1="aacable @ hotmail . com"
GMAILID="YOURGMAIL_ID@gmail.com"
GMAILPASS="YOURGMAIL_PASS"
CONTENT_TYPE="text/html"

# LOG FILES
FILE="/tmp/dealer_renewal_today.html"
FINALFILE="/tmp/dealer_renewal_today_final.html"
CSHORT="YOUR_COMPANY_NAME"
COMPANY="$CSHORT_Pvt_Ltd.<br>This System is powered by Syed_Jahanzaib aacable @ hotmail.com"
BODY_TITLE="<h1>Report&nbsp;For&nbsp;Dealer&nbsp;Account&nbsp;asof&nbsp;$YESTERDAY</h1>"


> $FILE
> $FINALFILE

echo "<pre>" > $FILE
echo "<b>$BODY_TITLE</b>" >> $FILE
echo "<b>DEALER&nbsp;            User's_Activated             Used_Amount             &Tab;Balance</b><br>" >> $FILE

# QUERY MANAGERS FROM RM_MANAGERS TABLE
mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; select managername from rm_managers;" | while read dealer
do
num=$[$num+1]
DEALER=`echo $dealer | awk '{print $1}'`

# GATHER DATA OF ACTIVE USERS, USED AMOUNT, CURRENT BALANCE, (MOBILE NUMBER IF SMS IS REQUIRED TO SEND)
ACTIVEUSERSNO=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.managername, rm_invoices.username, rm_invoices.date, rm_invoices.expiration, rm_invoices.service, rm_invoices.amount, rm_invoices.price FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$YESTERDAY' AND date <= '$TODAY' AND (paymode = '0'  OR paymode = '2' ) AND (invgroup = '0'  OR invgroup = '1' ) AND invnum != '' AND rm_invoices.managername = '$DEALER' ORDER BY id LIMIT 0, 500;" | sed '/credited/d' | wc -l`
USEDAMOUNT=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.price, rm_invoices.id, rm_invoices.invnum, rm_invoices.managername, rm_invoices.username, rm_invoices.date, rm_invoices.bytesdl, rm_invoices.bytesul, rm_invoices.bytescomb, rm_invoices.downlimit, rm_invoices.uplimit, rm_invoices.comblimit, rm_invoices.time, rm_invoices.uptimelimit, rm_invoices.days, rm_invoices.expiration, rm_invoices.comment, rm_invoices.service, rm_invoices.amount, rm_invoices.paid, rm_invoices.paymentopt, rm_invoices.paymode, rm_invoices.tax, rm_invoices.balance, rm_invoices.invgroup FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$YESTERDAY' AND date <= '$TODAY' AND (paymode = '0'  OR paymode = '2' ) AND (invgroup = '0'  OR invgroup = '1' )  AND invnum != '' AND rm_invoices.managername = '$DEALER'  ORDER BY id  LIMIT 0, 500;" | sed '/credited/d' | awk '{ sum+=$1} END {print sum}'`
BALANCE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; select balance from rm_managers WHERE managername = '$DEALER';" | sed '/credited/d' |cut -f1 -d"."`
MOBILE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; select mobile from rm_managers WHERE managername = '$DEALER';"`
SRV=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.service FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$YESTERDAY' AND date <= '$TODAY'  AND  rm_invoices.managername = '$DEALER' AND (paymode = '0'  OR paymode = '2' ) AND (invgroup = '0' ) AND invnum != ''  ORDER BY id LIMIT 0, 50;" | sed '/credited/d' | awk '{print $1}' | sort | uniq -c`




#LOOK FOR ZERO VALUE AMOUNT AND REPLACE IT WITH 0 , IF FOUND
if [ ! -n "$USEDAMOUNT" ]; then
#if [ "USEDAMOUNT  == "" ]; then
USEDAMOUNT="X"

# PRINT ALL GATHERED DATA INTO FILE
echo "<b>$DEALER</b>  $ACTIVEUSERSNO  $USEDAMOUNT  &Tab;$BALANCE
------------------------------------------------------------------------"  >> $FILE
else

# PRINT ALL GATHERED DATA INTO FILE
echo "<b>$DEALER</b>  $ACTIVEUSERSNO  $USEDAMOUNT  &Tab;$BALANCE
<br>
Details&nbsp;of&nbsp;Services&nbsp;Activated:<br>Qty&Tab;Service&nbsp;Name<br>
$SRV
<br>------------------------------------------------------------------------" >> $FILE

fi
done

# MAKE COLUMNS SO THAT IT GETs EASIER TO READS
sed -e 's/\t//g' $FILE |  column -t | sed 's/                         //g' | sed 's/    User/User/g'  > $FINALFILE

# GATHER DATA OF ACTIVE USERS, USED AMOUNT, CURRENT BALANCE, (MOBILE NUMBER IF SMS IS REQUIRED TO SEND)
TOTNO=`mysql -uroot -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.service FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$YESTERDAY' AND date <= '$TODAY'  AND (paymode = '0'  OR paymode = '2' ) AND (invgroup = '0' ) AND invnum != ''  ORDER BY id LIMIT 0, 50;" | sed '/credited/d' | awk '{print $1}' | wc -l`
SALES=`mysql -uroot -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.price FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$YESTERDAY' AND date <= '$TODAY'  AND (paymode = '0'  OR paymode = '2' ) AND (invgroup = '0' ) AND invnum != ''  ORDER BY id LIMIT 0, 50;" | awk '{ sum+=$1} END {print sum}'`
echo "Total Users Activated/Renewed on $YESTERDAY     = <b>$TOTNO</b>" >> $FINALFILE
echo "Total SALES Done on $YESTERDAY                  = <b>$SALES</b>" >> $FINALFILE
echo "<br><b>$COMPANY</b>" >> $FINALFILE
echo "Generated on $CURDATE" >> $FINALFILE
echo "</pre>" >> $FINALFILE

##Finally send email with all the data gathered USING SEND_EMAIL TOOL
/temp/sendEmail-v1.56/sendEmail -t $TO1 -u "INFO: $CSHORT DEALERS DAILY BILLING INFO for $YESTERDAY" -o tls=yes -s smtp.gmail.com:587 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$FINALFILE  -o message-content-type=$CONTENT_TYPE

# Print and copy files as sales.html into www folder so any1 can view from webbrowser
cat $FINALFILE
cp $FINALFILE /var/www/sales.html

 

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 [Life is really easy on ubuntu but with some glitches)

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

TEST SENDING EMAIL

Try to send email using command line: Example

/temp/sendEmail-v1.56/sendEmail -t TO_YOURMAIL@hotmail.com -u "Test Email" -s smtp.gmail.com:587 -xu YOURMGAILID@gmail.com -xp YOURGMAILPASSWORD -f  YOURMGAILIDgmail.com -o tls=yes

If you get message something like “sendEmail[xxxx]: Email was sent successfully!”, then you are good to GO LIVE !


 

Regard’s

Syed Jahanzaib


Filed under: Linux Related, Radius Manager

Prevent your mobile SIM getting blocked by Mobile Operator dueto bulk SMS Sending

$
0
0

sim

From ISP perspective, sending notifications for different events like expiry alerts, quota warning alerts, service disruption alert, welcome messages, password recovery via sms, etc etc to users is generally a good idea and becoming essential part of services. To send SMS in a proper way, its recommended get 3rd party SMS gateway services so that SMS goes by your company name and there should be no legal issue. but for smaller networks with lesser number of users, hiring 3rd party services is not financially suitable.

For a smaller network you can simply add any GSM Modem (example huawei or Teltonika) and use any local mobile operator SIM to send / receive SMS from your billing system because in our country SMS packages are dirt cheap. Ufone provides 100,000 SMS package in just 8$ per year, other operator’s packages are also cheap.  You can install KANNEL sms gateway in your linux system and use it to send SMS in automated way using your billing or any other customized method. BUT the issue is if you send bulk SMS in single go, there are strong chances that your SIM may get blocked by the operator because there are some official and un official restrictions imposed by either Operator or Telecom authorities like some sources states that

SIM gets blocked If you cross 200 SMS limit in 15 minutes and some mobile operator blocks SIM if you send 500 sms in 1 hour.

Ref: http://www.web.pk/2014/pta-devised-a-policy-to-stop-bulk-sms/

 

Solution:

[Suitable for SOHO]

If you are using KANNEL, and sending SMS using BASH scripts, add delay by using “sleep 20” (20 seconds delay) in the loop section so that there should be at least 10 or 20 seconds delay in between each sms sending. After adding 20 seconds delay to the code, only 3 SMS will go out per minute. You can adjust and fine tune this delay as per your requirements.
Example:

https://aacable.wordpress.com/2015/06/18/freeradiusmysql-account-expiry-sms-notification-script-using-itelservices-net-bulk-sms-gateway/

 

OR if you are using Radius Manager , then edit its sms gateway API php file and add the sleep delay as showed in the image below …

api-code

Now try to send Bulk SMS using RM ACP Panel, and you will see the delay in logs as well. : )~

delay-20-sec


 

Note:

In KANNEL there is an option ‘throughput‘ via which per sms sending can be controlled but for somehow it didn’t worked for ever. Therefore I used delay codes in the scripts or at the processing of submitting code.
I posted this issue at various forums but yet couldn’t found any solution on howto to add DELAY for outgoing sms  in KANNEL configuration. If any one knows the working solution. Kindly do let me know :)
Also share your experiences on how your SIM got blocked, what are other operators SMS sending limits? PTA limits etc.


 

Some Reference URLS for KANNEL

https://aacable.wordpress.com/2012/11/26/howto-configure-your-local-http-gateway-using-kannel-on-ubuntu/
https://aacable.wordpress.com/2015/06/18/freeradiusmysql-account-expiry-sms-notification-script-using-itelservices-net-bulk-sms-gateway/
https://aacable.wordpress.com/2012/11/26/dmasoftlab-radius-manager-sms-notification-configuration/
https://aacable.wordpress.com/tag/send-sms-to-users/

 

 

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

Sharing Ideas … Get User Account Info via SMS in Radius Manager

$
0
0

userinfo

usereinfo

Changelog:

  • Removed bug , when user have not used any data or account is new, script returns NULL errors
  • Added Online / Offline Status

1- TASK

The task was to provide user a method to inquire his/her account information via sending SMS in specific format to the Billing system.

In this example, we are using DMASOFTLAB Radius Manager as our billing system, and KANNEL along-with the playSMS is already configured and in working condition. kannel+playSMS configuration details have already been described briefly with examples in my previous posts.

We have created an script on the billing system which fetches the user account status and other information from the MYSQL database and print them as per our defined format.

This is just for demonstration purpose. the script have lot of junk data and should be modified before production deployment. I am just sharing some thoughts and ideas only :)

Script is as follows FYR. Hope it may help someone :$

cat userinfo.sh

#!/bin/bash
# Script to check Radius Manager Status , Expiry Date, Service Plan, Data Used
# Syed Jahanzaib
# aacable @ hotmail.com
# https://aacable.wordpress.com
# Modified on 3rd June, 2015

# MYSQL USER NAME AND PASSOWRD Variables
SQLUSER="root"
SQLPASS="zaib1234"
CURRENCY="PKR"

# Check User Validation, if not found exit with error , else continue
echo
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT * FROM radius.rm_users WHERE rm_users.username = '$1';"`
if [ "$USRVALID" == "" ]; then
echo -e "USER NOT FOUND !"
else

######################
# ACCOUNT EXPIRY CHECK
######################

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 = '$1';" |awk 'FNR == 2'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2' | sed 's/00:.*//' | sed -e 's/-//g'`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$1';"  |awk 'FNR == 2 {print $1,$2}'`

if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
        echo "Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE"

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
        echo "ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE"

else
echo -e "Radius Manager User Information Sample:"
echo "Account STATUS= OK!"

###############
# Check Account Expiry Date
EXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
#SRVLIMIT=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT comblimit FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`

#Get ACcounting Data for the Current Month Only
DOWNDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $1}'`

# Check for NULL DATA in download section of user
if [ "$DOWNDATA" == "NULL" ]
then
#       echo "NOT USED NO DOWN DATA FOUND"

#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
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"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2,$3}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = Not Used"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
else

UPDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $2}'`
TOTCOMBINED=`echo "($DOWNDATA+$UPDATA)/(1024)/(1024)" |bc`
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
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"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = $TOTCOMBINED MB"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
# Check User Current Online Status
ONLINE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT framedipaddress FROM radacct WHERE AcctStopTime IS NULL AND UserName = '$1';"`
if [ "$ONLINE" == "" ]; then
echo -e "Current Online Status = OFFLINE"
else
echo -e "Current Online Status = ONLINE"
fi
fi
fi
fi

2- playSMS SECTION

Now we have to add COMMAND in playSMS which will actually receive the sms and will act accordingly if found the keyword info

userinfo-playsms-=command


 3- TEST PHASE

You can test by executing the script or send sms , as per your choice.

Both methods results are as follows …

 

by CLI

userinfo-cli

by SMS

userinfo


 Another Version of GETUSERINFO with VLAN connected users numbers

Another Version of GETUSERINFO with more details like current ONLINE STATUS, and QUOTA assigned, used and left counters.

As showed in the below image …

userinf-2


root@rm:/var/lib/playsms/sms_command/1# cat userinfo.sh
#!/bin/bash
# Script to check Radius Manager Status , Expiry Date, Service Plan, Data Used
# Syed Jahanzaib
# aacable @ hotmail.com
# https://aacable.wordpress.com
# Modified on 9th June, 2015

# MYSQL USER NAME AND PASSWORD Variables
SQLUSER="root"
SQLPASS="sqlapssword"
SQLHOST="localhost"
SQLPORT="3306"
CURRENCY="PKR"

# Check User Validation, if not found exit with error , else continue
echo
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT * FROM radius.rm_users WHERE rm_users.username = '$1';"`
if [ "$USRVALID" == "" ]; then
echo -e "USER NOT FOUND !"
else

######################
# ACCOUNT EXPIRY CHECK
######################

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 -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2' | sed 's/00:.*//' | sed -e 's/-//g'`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$1';"  |awk 'FNR == 2 {print $1,$2}'`

if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
echo "Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE"

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo "ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE"

else
echo -e "Radius Manager User Information Sample:"
echo "Account STATUS= OK!"

###############
# Check Account Expiry Date
EXPIRY=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
#SRVLIMIT=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT comblimit FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`

#Get ACcounting Data for the Current Month Only
DOWNDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $1}'`

# Check for NULL DATA in download section of user
if [ "$DOWNDATA" == "NULL" ]
then
#       echo "NOT USED NO DOWN DATA FOUND"

#UPDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0$
CURRENCY="PKR"
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2,$3}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Data Used in $ALPHAMONTHYEAR = Not Used"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
#echo -e "Service Quota Limit = $SRVLIMITMB MB"
#echo -e "Downloaded Data = $DOWNDATAUSED - MB"
#echo -e "Uploaded Data = $UPDATAUP - MB"

else

UPDATA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0) FROM (   SELECT 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 radacct.username LIKE '$1' AND radacct.acctstarttime > '2015-$CMONTH%' AND radacct.framedipaddress LIKE '%' AND   radacct.callingstationid LIKE '%'    GROUP BY radacct.radacctid ) AS tmp;" |awk 'FNR == 2 {print $2}'`
TOTCOMBINED=`echo "($DOWNDATA+$UPDATA)/(1024)/(1024)" |bc`
TOTCOMBINED2=`echo "($TOTCOMBINED)/(1024)" |bc`
#SRVLIMITMB=`echo "($SRVLIMIT)/(1024)/(1024)" |bc`
#DOWNDATAUSED=`echo "($DOWNDATA)/(1024)/(1024)" |bc`
#UPDATAUP=`echo "($UPDATA)/(1024)/(1024)" |bc`
#Print Service ID for SPECIFIC_USER via CLI
SRVID=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1}'`
#Print SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`
# Print Package Name of current service via CLI
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# Print Service Download Limit QUOTA - TOTAL
QUOTA=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT trafficunitcomb FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';" |awk 'FNR == 2'`

# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST --port=$SQLPORT  -e "use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = '$1';" |awk 'FNR == 2 {print $1,$2}';`
# Now spit out (echo) all the data gathered by above junk commands
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Total Quota Allowed = $QUOTA MB"
echo -e "Total Data Used in $ALPHAMONTHYEAR = $TOTCOMBINED MB"
QUOTALEFT=`echo "( $QUOTA)-($TOTCOMBINED)" |bc`
echo -e "Total Quota LEFT = $QUOTALEFT MB"
echo -e "Expiration Date: $EXPIRY"
echo -e "Last Logout date was $LOGOFFDATE"
# Check User Current Online Status
ONLINE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT framedipaddress FROM radacct WHERE AcctStopTime IS NULL AND UserName = '$1';"`
if [ "$ONLINE" == "" ]; then
echo -e "Current Online Status = OFFLINE"
else
echo -e "Current Online Status = ONLINE"
fi
fi
fi
fi

 

Regard’s
SYED JAHANZAIB

 


Filed under: Linux Related, Radius Manager
Viewing all 78 articles
Browse latest View live