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

Using SMS CLI option in playSMS to enhance security for SMS base renewal

$
0
0

cli

TASK:

Operator requirement was to have a facility via which he can renew user account by simply sending sms to the radius system with user account name + admin password and above all only his mobile number should be authorized for this action. So basically two levels of securities are  required. One is admin password, second is sender CLI , something like mac address, and this is really strong because spoofing mobile numbers is not easily possible.

This method was also required because sometimes admin is out of station and opening billing page in mobile is not an easy task dueto to complex billing pages, navigation lot of pages in order to simple renew user account, and it requires good internet connectivity as well too. What if internet facility is not available in remote part, then SMS comes really handy to perform few or basic level of task.

This post is one of my ‘Sharing Ideas’  series which are practically implementable very easily and i have done it at few networks too. I know there are always many ways to achieve the same task. I just picked the easiest one. This code can be trimmed as it contains junks as it was made quickly in the lab. You can achieve the same task with some PHP code decently but that’s not my area

 


 

 

SOLUTION: A simple Script !

The following bash script will do the following.

  1. Upon receiving of SMS , it will first verify the SENDER SMS , if not found in /temp/adminmobile.txt , then it will return error and exit, otherwise continue to next step
  2. It will check for the Valid admin password , if not matched with /temp/password.txt, then it will return error and exit, otherwise continue to next step
  3. It will then check for valid user in radius mysql users table, if not found then it will exit, otherwise continue to next step
  4. If all conditions matches, it will simply renew the account by adding 31 days to the account and add entries in SYSLOG events, and it will also add full invoice in the ADMIN account. It will also return the FULL reply with the actions taken to the sender.

TIP: As you can see I have used simple text file to store the admin mobile number and simple password, but its recommended to use mysql table to store the said info for better reasons.


 

 

playSMS Section:

  • Login to PlaySMS
  • Goto Features / Manage Command / Add Sms Command
  • Create Command as showed in the image.

playsms-renewal commandPay attention to the SMSSENDER. by default playsms will add comma in between commandparm and smssender, so we will use SED to separate them : ).
SAVE the Command.

Now moving to script section


 

SCRIPT SECTION

Create script with any name (as mentioned in the playSMS section) and paste the date.
Just make sure you change user info like mysql id / password / text file names and location for admin mobile and admin password.

  • mkdir /temp
  • touch /temp/adminmobile.txt
  • touch /temp/password.txt

[Now add the password and mobile number of Admin. mobile number must be in following format  923333021909]

Now create the script in /var/lib/playsms/sms_commands/1

  • touch /var/lib/playsms/sms_commands/1/adrenew.sh
  • chmod +x /var/lib/playsms/sms_commands/1/adrenew.sh
  • nano touch /var/lib/playsms/sms_commands/1/adrenew.sh

[paste the following data and modify it as required]


# Script to renew account via sms with password and admin mobile CLI security
# Designed by Syed Jahanzaib for Test Purposes for a network
# 25th September, 2015
# aacable at hotmail dot com
# http://aacable.wordpress.com
# Script Starts Now

#!/bin/bash
SQLUSER="root"
SQLPASS="YOUR_SQL_PASSWORD"
echo $1 | sed 's/[+]/ /g' > /tmp/adminrenew

# Password file for storing Admin Password, better to use mysql query to fetch the password
PASS=`cat /tmp/adminrenew | awk {' print $1 '}`
USR=`cat /tmp/adminrenew | awk {' print $2 '}`

# File to store Admin Mobiel Number to match with the sender number
SENDER=`cat /tmp/adminrenew | awk {' print $3 '}`
NEXTEXPIRYADD=$(date +"%Y-%m-%d" -d "+31 days")

# LOOK FOR AUTHORIZED MOBILE NUMBER AND MATCH IT WITH LOCAL FILE
ADMINMOBILE=`cat /temp/adminmobile.txt`
if [ "$SENDER"  != "$ADMINMOBILE" ]; then
echo -e "ERROR: You number is not authorized to send SMS to this sytem! Jz"
exit 0
fi

# LOOK FOR VALID PASSWORD IN LOCALFILE
PASSVALID=`cat /temp/password.txt`
if [ "$PASS"  != "$PASSVALID" ]; then
echo -e "ERROR: Incorrect Admin Password!"
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!"
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"."`

#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))


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

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Package = $PKGNAME
echo Service Price at Billing = $SRVPRICE 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 SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), '$SENDER', 'galaxy', 'Account Renewed', '$USR', '$USR renewd - $PKGNAME');"

# Add rough DATA in INVOICE for billing purpose
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, date, bytesdl, bytesul, bytescomb, downlimit, uplimit, comblimit, time, uptimelimit, days, expiration, capdl, capul, captotal, captime, capdate, service, comment, transid, amount, invnum, address, city, zip, country, state, fullname, taxid, paymentopt, paymode, invtype, paid, price, tax, remark, balance, gwtransid, phone, mobile, vatpercent ) VALUES ('admin-$SENDER', '$USR', NOW(), '0', '0', '0', '0', '0', '0', '0', '0', '31', '$NEXTEXPIRYADD', '0', '0', '0', '0', '1', '$PKGNAME', '', '$TODAY', '1', '$TODAY', '', '', '', '', '', 'admin SMS renewed ', '', DATE_ADD(CURDATE(), INTERVAL '14' DAY), '0', '0', '$TODAY', '$SRVPRICE', '0.000000', '', '0.00', '', '', '03333021909', '0.00' );"

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

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo "Account Status: EXPIRED on $SRVEXPIRYFULL! Last LOGOUT date: $LOGOFFDATE"
NEXTEXPIRYADD=$(date +"%Y-%m-%d" -d "+31 days")


# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Package = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE 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 SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), '$SENDER', 'galaxy', '$USR', '$USR renewd - $PKGNAME');"

# Add rough DATA in INVOICE for billing purpose
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, date, bytesdl, bytesul, bytescomb, downlimit, uplimit, comblimit, time, uptimelimit, days, expiration, capdl, capul, captotal, captime, capdate, service, comment, transid, amount, invnum, address, city, zip, country, state, fullname, taxid, paymentopt, paymode, invtype, paid, price, tax, remark, balance, gwtransid, phone, mobile, vatpercent ) VALUES ('admin-$SENDER', '$USR', NOW(), '0', '0', '0', '0', '0', '0', '0', '0', '31', '$NEXTEXPIRYADD', '0', '0', '0', '0', '1', '$PKGNAME', '', '$TODAY', '1', '$TODAY', '', '', '', '', '', 'admin SMS renewed ', '', DATE_ADD(CURDATE(), INTERVAL '14' DAY), '0', '0', '$TODAY', '$SRVPRICE', '0.000000', '', '0.00', '', '', '03333021909', '0.00' );"

# 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 User Package = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE 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 = 'Last renewed by SMS $SENDER'  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(), '$SENDER', 'galaxy', 'Account Renewed', '$USR renewd - $PKGNAME');"

# Add rough DATA in INVOICE for billing purpose
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, date, bytesdl, bytesul, bytescomb, downlimit, uplimit, comblimit, time, uptimelimit, days, expiration, capdl, capul, captotal, captime, capdate, service, comment, transid, amount, invnum, address, city, zip, country, state, fullname, taxid, paymentopt, paymode, invtype, paid, price, tax, remark, balance, gwtransid, phone, mobile, vatpercent ) VALUES ('admin-$SENDER', '$USR', NOW(), '0', '0', '0', '0', '0', '0', '0', '0', '31', '$NEXTEXPIRYADD', '0', '0', '0', '0', '1', '$PKGNAME', '', '$TODAY', '1', '$TODAY', '', '', '', '', '', 'admin SMS renewed ', '', DATE_ADD(CURDATE(), INTERVAL '14' DAY), '0', '0', '$TODAY', '$SRVPRICE', '0.000000', '', '0.00', '', '', '03333021909', '0.00' );"

fi

# Script ENDs here
# Thankoooo . zaib


 

TEST AND RESULTS

Now send sms in following format to the radius/playSMS attached system.

adrenew YOURPASS USERNAME

and you will receive reply accordingly as showed in the image below …

2015-09-26 05.16.45


 

:)~~

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Mikrotik Related

Sending SMS in URDU/ARABIC or other language via KANNEL

$
0
0

u[OS = Ubuntu]

It is very easy to send SMS in URDU or ARABIC fonts using KANNEL as your gateway using &charset=UTF-8&coding=1  (in some cases its &charset=UTF-8&coding=2) code.

Just add the following in your /etc/kannel.conf file under SMSC section

 alt-charset= "UTF-8" 

 

 

Save & restart kannel service

service kannel stop
killall -9 bearerbox
service kannel start

 

EXAMPLES:


 

To send SMS in URDU via browser / URL via KANNEL

http://KANNEBOXIP/cgi-bin/sendsms?username=kannel&password=KANNELPASSWORD&to=03333021909&charset=UTF-8&coding=1&text=سلام+علیکم+آپ+KANNEL+میں+بہت+آسانی+سے+اردو+فونٹس+میں+ایس+ایم+ایس+بھیج+سکتے+ہیں.+مثال+اکاؤنٹ+ختم+ہونے+کی+معلومات،+مرحبا+پیغامات+وغیرہ+وغیرہ+شکریہ+سید+جہانزیب

Result Example:

urdu

You can get the urdu/arabic font by translating it via translate.google.com and copy paste the translated text.


 

To send SMS in URDU using Local FILE via KANNEL

Use any UTF converter tool /notepad /word etc, OR if you dont have one,  do it online via Converter TEXT to encoded

Paste your URDU text and hit Enter it will give you UTF8 encoded data,As showed here

utf8

Copy that data and paste it in any local file, example /temp/urdu.txt

Now use the below command from the Linux terminal to send this file contents via kannel in URDU ; )


curl "http://KANNELBOXIP:13013/cgi-bin/sendsms?username=kannel&password=KANNELPASS&to=03333021909&charset=UTF-8&coding=1" -G --data-urlencode text@/temp/urdu.txt

Result Example:file


 

Note: If you still receive SMS with ??? signs , then try with

http://KANNEBOXIP/cgi-bin/sendsms?username=kannel&password=KANNELPASSWORD&to=03333021909&charset=UTF-8&coding=2&text=سلام+علیکم+آپ+KANNEL+میں+بہت+آسانی+سے+اردو+فونٹس+میں+ایس+ایم+ایس+بھیج+سکتے+ہیں.+مثال+اکاؤنٹ+ختم+ہونے+کی+معلومات،+مرحبا+پیغامات+وغیرہ+وغیرہ+شکریہ+سید+جہانزیب

جزاک اللہ

سید جہانزیب


Filed under: Linux Related

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

[For Reference] Quick Script for Mikrotik Daily Info via SMS or Email !

$
0
0

keep calm n coding

mikrotik status updated script via sms

Quick Note:

Scenario#1:

DUAL DSL wan links are connected with mikrotik [modems are in bridge mode], Configured as PCC along with the pppoe server. USB modem is attached with the Mikrotik via USB port. The OP need an script which can daily send sms or email specific information to admin cell, or whenever admin require on urgent basis via sending sms to mikrotik and it can return back the info to the admin cell.

 

Dirty Solution:

Following script will collect information from Mikrotik system such as active pppoe users, CPU load, dsl links status etc and send this information to admin via SMS or Email either via scheduler or as receiver command on mikrotik. [I am already using much more advance version of this script in other networks in linux system as BASH is the best ground to support scripting but since linux was not available at this spot, i had to use Mikrotik only with usb modem attached]  it can be set as receive command too so that admin can send sms to mikrotik and mikrotik will reply back the current info to the admin mobile. Sometimes its very useful for remote admins.

# SENDING SMS TO ADMINS FOR DAILY MORNING ALERT
# Script Designed by SYED JAHANZAIB
# aacable at hotmail dot com / http://aacable.wordpress.com
# Morning Hours / 8th Oct, 2015

# Setting various variables / jz
:local date;
:local time;
:local PPP ([/ppp active print count-only])
:local UPTIME [/system resource get uptime]
:local CPU [/system resource get cpu-load]
:set date [/system clock get date];
:set time [/system clock get time];
:global FTPIP 192.168.0.50

# Following variables are configured via other scripts which scheduled to run after very 1 minutes to update internet/media sharing server status and set these variables
# But you can run your own script here to make variable after successful or failed ping results
# Ref: https://aacable.wordpress.com/2014/06/12/mikrotik-wan-monitoring-script-with-multiple-host-check/

:local DSL1 [/system script environment get [/system script environment find name="DSL1netstatus"] value];
:local DSL2 [/system script environment get [/system script environment find name="DSL2netstatus"] value];

# Local FTP Sharing Server or any other remote host, should be set via netwatch or local script inside this script
#:local FTP [/tool netwatch get number=0 status]
# Using one liner code to get FTP ping status and store it in variable, you can use same for above dsl status as well by
# forcing routes via specific gateway
:global FTP;
:if ([/ping $FTPIP count=1] = 0) do {:put ":set FTP value=DOWN"} else={:set FTP value=UP}

# Admin SMS Number Config
:local cell1 "03333021909"

# Gmail Config
:global SYSID ([/system identity get name])
:global adminmail1 aacable@hotmail.com
:global gmailid GMAILID@gmail.com
:global gmailpwd GMAILPASSWORD
:global gmailip
:set gmailip [:resolve "smtp.gmail.com"];

# Print LOG
:log warning "INFO: Daily info for NETWORK @ $date $time\nActive PPPOE Users = $PPP\nUptime is $UPTIME\nCPU Load = $CPU\nDSL1 = $DSL1\nDSL2 = $DSL2\nFTP = $FTP\n\nPowered by J."
:log warning "Sending DAILY MORNING ALERT SMS on $cell1 ... by J."

# Sending SMS
/tool sms send port=usb3 phone-number=$cell1 message="INFO: Daily info for NETWORK @ $date $time\nActive PPPOE Users = $PPP\nUptime = $UPTIME\nCPU Load = $CPU\nDSL1 = $DSL1\nDSL2 = $DSL2\nFTP = $FTP\n\nPowered by J." channel=0

# Sending EMAIL - Use it if if required
#/tool e-mail send to=$adminmail1 password=$gmailpwd subject="INFO: Daily info for @ $date $time" body="Active PPPOE Users = $PPP\nUptime = $UPTIME\nCPU Load = $CPU\nDSL1 = $DSL1\nDSL2 = $DSL2\nFTP = $FTP\n\nPowered by J." from=$gmailid server=$gmailip start-tls=yes

 

Sample Image of SMS:

debug

sms


 

Enable Mikrotik to Receive SMS and run script

Use following command to enable SMS receiving on mikrotik.

#:delay 60
/tool sms set keep-max-sms=10 port=usb3 receive-enabled=yes secret=12345 channel 0
#:delay 3
#/tool sms set receive-enabled=no
#:delay 3
#/tool sms set receive-enabled=yes

From your mobile you can send following message to run script on remote mikrotik.

:cmd 12345 script test

 

Explanation:

  • :cmd to let mikrotik know that its command
  • 12345 is secret which you configured in /tool > sms,kind of password / authentication
  • script to let mikrotik know that its script related command  and
  • test is script name you want to run.

More references for mikrotik base sms are available at https://aacable.wordpress.com/tag/mikrotik-sms/

 


Another Beta Version:


# SENDING SMS TO ADMINS FOR DAILY MORNING ALERT ALERT

# Syed Jahanzaib

# Remove 'not required' items

# Your Network Name, change it here
:local NETWORK "ZzZzZz"

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

# Gather Data from Routerboard
:local PPP  ([/ppp active print count-only])
:local UPTIME [/system resource get uptime]
:local CPU [/system resource get cpu-load]
:local VOLT [/sys health get voltage]
:local TEMPR [/sys health get temperature]
:local CPUTEMP [/sys health get cpu-temperature]
:local PWRC [/sys health get power-consumption]
:local FAN1 [/sys health get fan1-speed]
:local FAN2 [/sys health get fan2-speed]
:local DSL1 [/system script environment get [/system script environment find name="DSL1netstatus"] value];
:local DSL2 [/system script environment get [/system script environment find name="DSL2netstatus"] value];

# Get Local Media sharing server status
:global FTP;
:if ([/ping 10.00.100 count=1] = 0) do {:put ":set FTP value=DOWN"} else={:set FTP value=UP}

# Modem Related
:local PORT usb3
:local CHANNEL 0

# Admin Mobile Number
:local cell1 "03333021909"

# Message to be send , which gather data from variables / zaib
:local MSG "INFO: Daily info for
$NETWORK  at $date $time
Active PPPOE Users  = $PPP
Uptime = $UPTIME
DSL1 = $DSL1
DSL2 = $DSL2
CPU Load = $CPU
FTP = $FTP
Voltage
$VOLT
CPU Temperature
$CPUTEMP
Power Consumption
$PWRC
Board Temperature
$TEMPR
FAN1 Speed
$FAN1
FAN2 Speed
$FAN2
Powered by J."

# Finally Send SMS with all gathered DATA for CCR_1036
/tool sms send port=$PORT channel=0 phone-number=$cell1 message="$MSG"

 

Regard’s
Syed Jahanzaib!


Filed under: Mikrotik Related

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

Resolving “Trust Relation between this workstation and the PDC”

$
0
0

Yesterday I converted one of our Physical Windows 2008 base SAP QAS server to ESXI 5.x Virtual Guest for some R&D purposes. It took around 30+ hours for the conversion using vconverter 6 [as old converters have no support UEFI BIOS. When I powered on the newly converted vm guest machine I received the following error upon login

 

trust-error

[I also received same error in year 2014 when our lotus domino server was migrated to new IBM Xseries 3650 M4 series and after every thing got settled i received this error upon final login, what a terrible time that was]

As a quick remedy I tried to RESET the computer account of this PC via AD management but no use.
Finally I used old NETDOM method and it worked instantly.

This is how I solved this problem.

Login with local computer admin account

Open COMMAND prompt

and Issue following command

netdom resetpwd /s:server /ud:domain\User /pd:*

 

Example if you have following setup

AD Server Name : SERVER1
Domain Name : mydomain.local
User Name : jahanzaib

then use following

netdom resetpwd /s:server1 /ud:mydomain.local\jahanzaib /pd:*

It will ask you to enter new password, simply enter password and enter. [prompt will not let u see the typing so careful when typing password]

After then simply log off and login with your domain id and it will work Insha Allah.

Regard’s

Syed Jahanzaib


Filed under: Microsoft Related

Event ID 7000 The Diagnostic Service Host service failed to start !

$
0
0

7000 diagnostic service host error

The Diagnostic Service Host service failed to start due to the following error:
A privilege that the service requires to function properly does not exist in the service account configuration. You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration.

Today at my company, every domain user was receiving above error in  there Event logs / SYSTEM section.

To sort this issue i did following

  1. Login to Domain Controller PC
  2. Open Group policy editor (or run gpedit.msc from RUN) and edit default domain policy (or any other custom policy you may have other then default)
  3. Goto Computer or USER  Configuration -> Policies -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignment -> Profile system performance

There you may see only ADMINISTRATOR user added by default, now add following users

LOCAL SERVICE
NT Service\WdiServiceHost

Now open CMD and issue following command to force GPUDPATE.

gpupdate /force


 

 

At client end, clear the logs, and reboot system. After rebooting check Event Viewer and you wont see the error again. [I waited about 15 minutes before rebooting client]

 

Regard’s
Syed Jahanzaib


Filed under: Microsoft Related

Monitoring multiple WAN links in PCC using BLACK-HOLE route approach !

$
0
0

bh

Scenario:

Dual pppoe-client wan links are configured in mikrotik with PCC load balancing.

Task:

To monitor both (ow more) wan links via some fixed routes and email in case any goes down or take other action as required.

Solution:

You must be aware that to achieve any task, there are multiple ways to do so, Select whatever is best and whatever works for you (offcourse without affecting any other functionality). I tried various solutions to monitor pppoe-wan clients, but most of them didn’t worked as I wanted. So I used blackhole route approach and it worked 100%.

Example:

[This example is just for demonstration purpose only. In the real production environment you MUST use multiple host monitoring , because it is very possible that if you monitor single host, and for some reason ISP blocks it, or the owner of the host close it for maintenance then what happens? YES you will get false alarm even if the internet is working fine. To avoid such false alarms ,You must use multiple host to monitor each wan link I wrote multiple wan monitor script in some previous post, search it.)

For WAN-1 link we will monitor 4.2.2.1  [DNS Server]
For WAN-2 link we will monitor 208.67.222.123 [Open DNS server IP]

 

/ip route
add comment="WAN-1  /  FORCED ROUTE FOR LINK MONITORING / ZAIB" disabled=no distance=1 dst-address=4.2.2.1/32 gateway=pppoe-out1 scope=30 target-scope=10

add comment="WAN-2  /  FORCED ROUTE FOR LINK MONITORING / ZAIB" disabled=no distance=1 dst-address=208.67.222.123/32 gateway=pppoe-out2 scope=30 target-scope=10

PROBLEM:

The problem is that as soon as one WAN (pppoe-out1 disconnects for any reason like line dead etc, the PING will then look in main table and whatever route it found (example pppoe-out2) it will pass the traffic from that available wan link, and this is BAD for our monitoring script because we wanted to FORCE specific route to always pass via specific link only.

For this reason we will duplicate above routes, BUT this time we will use type ‘blackhole‘ and create higher distance value so that when default route FOR SPECIFIC MONITORED HOST goes down, then next route with higher distance value will be enabled automatically and will send packets to black-hole resulting in timeout which we will be using in net watch monitoring scripts.

 

add comment="WAN-1  blackhole /  FORCED ROUTE FOR LINK MONITORING / ZAIB" disabled=no distance=2 dst-address=4.2.2.1/32 type=blackhole

add comment="WAN-2  blackhole /  FORCED ROUTE FOR LINK MONITORING / ZAIB" disabled=no distance=2 dst-address=208.67.222.123/32 type=blackhole

So as soon as WAN1 goes down, the ping to 4.2.2.1 will go to BLACKHOLE / timeout dueto above rules. same for wan2.

 


Example script to monitor wan link and email or take other action

Complete script to monitor wan1 is as follows. Just for reference purposes.


# Syed Jahanzaib / aacable @ hotmail.com
# https://aacable.wordpress.com
# WAN Monitor script (for single host) and email if down/up
# Kindly configure tools/Email first to send email alert
:local i 0;
:local F 0;
:local date;
:local time;
:global DSL1netstatus;
:global DSL1netLastChange;
:local cell1 "03333021909"

:local adminmail1 "YOUR MAIL ADDRESS"
:local gmailid "YOURGMAILID@gmail.com"
:local gmailpass "YOURGMAILPASS"

# Check WAN1 GATEWAY to be monitored (Currently we are monitoring internet host)
:global wan1host1 4.2.2.1

# Gmail SMTP Address
:global gmailsmtp
:set gmailsmtp [:resolve "smtp.gmail.com"];

# Ping Internet Host 5 times,
:for i from=1 to=10 do={
if ([/ping $wan1host1 count=1]=0) do={:set F ($F + 1)}
:delay 1;
};

# If no response (5=10 out of 10 Ping fails for each item, Times out, then LOG down status and take action
:if (($F=10)) do={
:if (($DSL1netstatus="UP")) do={
:set DSL1netstatus "DOWN";

# Also add status in global variables to be used as tracking
:set date [/system clock get date];
:set time [/system clock get time];
:set DSL1netLastChange ($time . " " . $date);


##################################################
####### FOR DOWN STATUS, CHANGE THE RULES ########
##################################################
# If the link is down, then LOG info and warning in Mikrotik LOG window [Zaib]
:log error "WAN1 Gateway Not Responding. Please Check DSL1 Connectivity..."


# "Emailing the DOWN status. . . "
/tool e-mail send to="$adminmail1" password=$gmailpass subject="$[/system clock get date] $[/system clock get time] -- ALERT: PTCL DSL-1 is DOWN" from=$gmailid server=$gmailsmtp tls=yes body="$[/system clock get date] $[/system clock get time] : ALERT: PTCL DSL-1 is DOWN"
#/tool sms send port=usb3 phone-number=$cell4  message="INFO: xxxxx Network DSL-1 is DOWN ... / by Jz."  channel=0

##################################################
####### FOR UP STATUS, CHANGE THE RULES ########
##################################################
# If ping is ok 5/5 reply received, then LOG UP and take action as required

} else={:set DSL1netstatus "DOWN";}
} else={
:if (($DSL1netstatus="DOWN")) do={
:set DSL1netstatus "UP";
# If link is UP, then LOG info and warning in Mikrotik LOG window [Zaib]
log warning "WAN1 Gateway RESTORED ..."

# "Emailing the UP  status. . . "
/tool e-mail send to="$adminmail1" password=$gmailpass subject="$[/system clock get date] $[/system clock get time] -- INFO: PTCL DSL-1 is UP Now." from=$gmailid server=$gmailsmtp tls=yes body="$[/system clock get date] $[/system clock get time] : ALERT: PTCL DSL-1 is UP Now."
#/tool sms send port=usb3 phone-number=$cell4  message="INFO: xxxxx Network DSL-1 is UP ... / by Jz."  channel=0
:set date [/system clock get date];
:set time [/system clock get time];
:set DSL1netLastChange ($time . " " . $date);

} else={:set DSL1netstatus "UP";}
}


 

EMAIL ALERT

 

alerts

SMS ALERT

sms_alert

LOG

WAN_DOWN_ALERTS_LOGS

 

You can perform other customized actions on DOWN or UP  too :)

 

Regard’s
SYED JAHANZAIB


Filed under: Mikrotik Related

Mikrotik User Manager False Active Session Removal Scripts

$
0
0

duplicate

Mikrotik ‘User Manager‘ is a free and builtin package of mikrotik which provides basic level of radius / billing capabilities. Its good for smaller networks but form its introduction till the latest version, it always contains few bugs that can be sometimes annoying for the admin and surely not suitable for large production environment like ISP’s. One little example is FALSE active sessions in userman where user actually not active any more in the Mikrotik connected session but the userman shows it active thus preventing user from re-connecting.

This usually happens when users lost connectivity [specially wifi users] or disconnected from the mikrotik but userman still keep it in its active session therefore the user gets denied when he try to re-connect. so when the admin manually remove its Active session from the userman web interface, user then able to connect.

This is no mean a solution, but you can say as a workaround only a script was posted in mikrotik forums, therefore re-posting with some mods it so that it may help others as well. Just for reference purposes.

Schedule it to run according to your router load. on the load of around 150+ users with low end router, I schedule it to run after every 5 minutes as this script does take some times to calculate each user so take a note of it. adjust value accordingly.

 


# Script Source : Mikrotik Forums
# This script remove false active sessions in User Manager v5 or above
# I only tested it with ver 6.32.1 and it worked very well in a active network. [Jahanzaib]

# Script Starts Here.
# Setting Timeout in Seconds
# Timeout in Seconds, when session update is older -> session closed
:local Timeout 60

#------------------------------------------
:local LastSessionUpdate;
:local SessionTimeout;
:foreach i in=[/tool user-manager session find where active=yes] do={

# When was the last Update of the session-informations
:set LastSessionUpdate [/tool user-manager session get $i till-time]

# SessionTimeout is a value that tells me how many seconds ago the last update of this session was
:set SessionTimeout ([system clock get time] - [:pick $LastSessionUpdate ([:find $LastSessionUpdate " "]+1) [:len $LastSessionUpdate]]-[/system clock get gmt-offset])

# if last update is more then Timeout seconds ago then close session and log it
:if ($SessionTimeout > $Timeout) do={
/tool user-manager session remove  numbers=$i
:log warning (" Removed false active session by Zaib - Username is  " . [/tool user-manager session get $i user]);
}
}

userman_+false


Filed under: Mikrotik Related

Using SMS CLI option in playSMS to enhance security for SMS base renewal

$
0
0

cli

TASK:

Operator requirement was to have a facility via which he can renew user account by simply sending sms to the radius system with user account name + admin password and above all only his mobile number should be authorized for this action. So basically two levels of securities are  required. One is admin password, second is sender CLI , something like mac address, and this is really strong because spoofing mobile numbers is not easily possible.

This method was also required because sometimes admin is out of station and opening billing page in mobile is not an easy task dueto to complex billing pages, navigation lot of pages in order to simple renew user account, and it requires good internet connectivity as well too. What if internet facility is not available in remote part, then SMS comes really handy to perform few or basic level of task.

This post is one of my ‘Sharing Ideas’  series which are practically implementable very easily and i have done it at few networks too. I know there are always many ways to achieve the same task. I just picked the easiest one. This code can be trimmed as it contains junks as it was made quickly in the lab. You can achieve the same task with some PHP code decently but that’s not my area

 


 

 

SOLUTION: A simple Script !

The following bash script will do the following.

  1. Upon receiving of SMS , it will first verify the SENDER SMS , if not found in /temp/adminmobile.txt , then it will return error and exit, otherwise continue to next step
  2. It will check for the Valid admin password , if not matched with /temp/password.txt, then it will return error and exit, otherwise continue to next step
  3. It will then check for valid user in radius mysql users table, if not found then it will exit, otherwise continue to next step
  4. If all conditions matches, it will simply renew the account by adding 31 days to the account and add entries in SYSLOG events, and it will also add full invoice in the ADMIN account. It will also return the FULL reply with the actions taken to the sender.

TIP: As you can see I have used simple text file to store the admin mobile number and simple password, but its recommended to use mysql table to store the said info for better reasons.


 

 

playSMS Section:

  • Login to PlaySMS
  • Goto Features / Manage Command / Add Sms Command
  • Create Command as showed in the image.

playsms-renewal commandPay attention to the SMSSENDER. by default playsms will add comma in between commandparm and smssender, so we will use SED to separate them : ).
SAVE the Command.

Now moving to script section


 

SCRIPT SECTION

Create script with any name (as mentioned in the playSMS section) and paste the date.
Just make sure you change user info like mysql id / password / text file names and location for admin mobile and admin password.

  • mkdir /temp
  • touch /temp/adminmobile.txt
  • touch /temp/password.txt

[Now add the password and mobile number of Admin. mobile number must be in following format  923333021909]

Now create the script in /var/lib/playsms/sms_commands/1

  • touch /var/lib/playsms/sms_commands/1/adrenew.sh
  • chmod +x /var/lib/playsms/sms_commands/1/adrenew.sh
  • nano touch /var/lib/playsms/sms_commands/1/adrenew.sh

[paste the following data and modify it as required]


# Script to renew account via sms with password and admin mobile CLI security
# Designed by Syed Jahanzaib for Test Purposes for a network
# 25th September, 2015
# aacable at hotmail dot com
# https://aacable.wordpress.com
# Script Starts Now

#!/bin/bash
SQLUSER="root"
SQLPASS="YOUR_SQL_PASSWORD"
echo $1 | sed 's/[+]/ /g' > /tmp/adminrenew

# Password file for storing Admin Password, better to use mysql query to fetch the password
PASS=`cat /tmp/adminrenew | awk {' print $1 '}`
USR=`cat /tmp/adminrenew | awk {' print $2 '}`

# File to store Admin Mobiel Number to match with the sender number
SENDER=`cat /tmp/adminrenew | awk {' print $3 '}`
NEXTEXPIRYADD=$(date +"%Y-%m-%d" -d "+31 days")

# LOOK FOR AUTHORIZED MOBILE NUMBER AND MATCH IT WITH LOCAL FILE
ADMINMOBILE=`cat /temp/adminmobile.txt`
if [ "$SENDER"  != "$ADMINMOBILE" ]; then
echo -e "ERROR: You number is not authorized to send SMS to this sytem! Jz"
exit 0
fi

# LOOK FOR VALID PASSWORD IN LOCALFILE
PASSVALID=`cat /temp/password.txt`
if [ "$PASS"  != "$PASSVALID" ]; then
echo -e "ERROR: Incorrect Admin Password!"
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!"
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"."`

#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))


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

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Package = $PKGNAME
echo Service Price at Billing = $SRVPRICE 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 SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), '$SENDER', 'galaxy', 'Account Renewed', '$USR', '$USR renewd - $PKGNAME');"

# Add rough DATA in INVOICE for billing purpose
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, date, bytesdl, bytesul, bytescomb, downlimit, uplimit, comblimit, time, uptimelimit, days, expiration, capdl, capul, captotal, captime, capdate, service, comment, transid, amount, invnum, address, city, zip, country, state, fullname, taxid, paymentopt, paymode, invtype, paid, price, tax, remark, balance, gwtransid, phone, mobile, vatpercent ) VALUES ('admin-$SENDER', '$USR', NOW(), '0', '0', '0', '0', '0', '0', '0', '0', '31', '$NEXTEXPIRYADD', '0', '0', '0', '0', '1', '$PKGNAME', '', '$TODAY', '1', '$TODAY', '', '', '', '', '', 'admin SMS renewed ', '', DATE_ADD(CURDATE(), INTERVAL '14' DAY), '0', '0', '$TODAY', '$SRVPRICE', '0.000000', '', '0.00', '', '', '03333021909', '0.00' );"

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

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo "Account Status: EXPIRED on $SRVEXPIRYFULL! Last LOGOUT date: $LOGOFFDATE"
NEXTEXPIRYADD=$(date +"%Y-%m-%d" -d "+31 days")


# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Package = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE 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 SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), '$SENDER', 'galaxy', '$USR', '$USR renewd - $PKGNAME');"

# Add rough DATA in INVOICE for billing purpose
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, date, bytesdl, bytesul, bytescomb, downlimit, uplimit, comblimit, time, uptimelimit, days, expiration, capdl, capul, captotal, captime, capdate, service, comment, transid, amount, invnum, address, city, zip, country, state, fullname, taxid, paymentopt, paymode, invtype, paid, price, tax, remark, balance, gwtransid, phone, mobile, vatpercent ) VALUES ('admin-$SENDER', '$USR', NOW(), '0', '0', '0', '0', '0', '0', '0', '0', '31', '$NEXTEXPIRYADD', '0', '0', '0', '0', '1', '$PKGNAME', '', '$TODAY', '1', '$TODAY', '', '', '', '', '', 'admin SMS renewed ', '', DATE_ADD(CURDATE(), INTERVAL '14' DAY), '0', '0', '$TODAY', '$SRVPRICE', '0.000000', '', '0.00', '', '', '03333021909', '0.00' );"

# 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 User Package = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE 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 = 'Last renewed by SMS $SENDER'  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(), '$SENDER', 'galaxy', 'Account Renewed', '$USR renewd - $PKGNAME');"

# Add rough DATA in INVOICE for billing purpose
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_invoices (managername, username, date, bytesdl, bytesul, bytescomb, downlimit, uplimit, comblimit, time, uptimelimit, days, expiration, capdl, capul, captotal, captime, capdate, service, comment, transid, amount, invnum, address, city, zip, country, state, fullname, taxid, paymentopt, paymode, invtype, paid, price, tax, remark, balance, gwtransid, phone, mobile, vatpercent ) VALUES ('admin-$SENDER', '$USR', NOW(), '0', '0', '0', '0', '0', '0', '0', '0', '31', '$NEXTEXPIRYADD', '0', '0', '0', '0', '1', '$PKGNAME', '', '$TODAY', '1', '$TODAY', '', '', '', '', '', 'admin SMS renewed ', '', DATE_ADD(CURDATE(), INTERVAL '14' DAY), '0', '0', '$TODAY', '$SRVPRICE', '0.000000', '', '0.00', '', '', '03333021909', '0.00' );"

fi

# Script ENDs here
# Thankoooo . zaib


 

TEST AND RESULTS

Now send sms in following format to the radius/playSMS attached system.

adrenew YOURPASS USERNAME

and you will receive reply accordingly as showed in the image below …

2015-09-26 05.16.45


 

:)~~

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Mikrotik Related

Sending SMS in URDU/ARABIC or other language via KANNEL

$
0
0

u[OS = Ubuntu]

It is very easy to send SMS in URDU or ARABIC fonts using KANNEL as your gateway using &charset=UTF-8&coding=1  (in some cases its &charset=UTF-8&coding=2) code.

Just add the following in your /etc/kannel.conf file under SMSC section

 alt-charset= "UTF-8" 

 

 

Save & restart kannel service

service kannel stop
killall -9 bearerbox
service kannel start

 

EXAMPLES:


 

To send SMS in URDU via browser / URL via KANNEL

http://KANNEBOXIP/cgi-bin/sendsms?username=kannel&password=KANNELPASSWORD&to=03333021909&charset=UTF-8&coding=1&text=سلام+علیکم+آپ+KANNEL+میں+بہت+آسانی+سے+اردو+فونٹس+میں+ایس+ایم+ایس+بھیج+سکتے+ہیں.+مثال+اکاؤنٹ+ختم+ہونے+کی+معلومات،+مرحبا+پیغامات+وغیرہ+وغیرہ+شکریہ+سید+جہانزیب

Result Example:

urdu

You can get the urdu/arabic font by translating it via translate.google.com and copy paste the translated text.


 

To send SMS in URDU using Local FILE via KANNEL

Use any UTF converter tool /notepad /word etc, OR if you dont have one,  do it online via Converter TEXT to encoded

Paste your URDU text and hit Enter it will give you UTF8 encoded data,As showed here

utf8

Copy that data and paste it in any local file, example /temp/urdu.txt

Now use the below command from the Linux terminal to send this file contents via kannel in URDU ; )


curl "http://KANNELBOXIP:13013/cgi-bin/sendsms?username=kannel&password=KANNELPASS&to=03333021909&charset=UTF-8&coding=1" -G --data-urlencode text@/temp/urdu.txt

Result Example:file


 

Note: If you still receive SMS with ??? signs , then try with

http://KANNEBOXIP/cgi-bin/sendsms?username=kannel&password=KANNELPASSWORD&to=03333021909&charset=UTF-8&coding=2&text=سلام+علیکم+آپ+KANNEL+میں+بہت+آسانی+سے+اردو+فونٹس+میں+ایس+ایم+ایس+بھیج+سکتے+ہیں.+مثال+اکاؤنٹ+ختم+ہونے+کی+معلومات،+مرحبا+پیغامات+وغیرہ+وغیرہ+شکریہ+سید+جہانزیب

جزاک اللہ

سید جہانزیب


Filed under: Linux Related

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

[For Reference] Quick Script for Mikrotik Daily Info via SMS or Email !

$
0
0

keep calm n coding

mikrotik status updated script via sms

Quick Note:

Scenario#1:

DUAL DSL wan links are connected with mikrotik [modems are in bridge mode], Configured as PCC along with the pppoe server. USB modem is attached with the Mikrotik via USB port. The OP need an script which can daily send sms or email specific information to admin cell, or whenever admin require on urgent basis via sending sms to mikrotik and it can return back the info to the admin cell.

 

Dirty Solution:

Following script will collect information from Mikrotik system such as active pppoe users, CPU load, dsl links status etc and send this information to admin via SMS or Email either via scheduler or as receiver command on mikrotik. [I am already using much more advance version of this script in other networks in linux system as BASH is the best ground to support scripting but since linux was not available at this spot, i had to use Mikrotik only with usb modem attached]  it can be set as receive command too so that admin can send sms to mikrotik and mikrotik will reply back the current info to the admin mobile. Sometimes its very useful for remote admins.

# SENDING SMS TO ADMINS FOR DAILY MORNING ALERT
# Script Designed by SYED JAHANZAIB
# aacable at hotmail dot com / https://aacable.wordpress.com
# Morning Hours / 8th Oct, 2015

# Setting various variables / jz
:local date;
:local time;
:local PPP ([/ppp active print count-only])
:local UPTIME [/system resource get uptime]
:local CPU [/system resource get cpu-load]
:set date [/system clock get date];
:set time [/system clock get time];
:global FTPIP 192.168.0.50

# Following variables are configured via other scripts which scheduled to run after very 1 minutes to update internet/media sharing server status and set these variables
# But you can run your own script here to make variable after successful or failed ping results
# Ref: https://aacable.wordpress.com/2014/06/12/mikrotik-wan-monitoring-script-with-multiple-host-check/

:local DSL1 [/system script environment get [/system script environment find name="DSL1netstatus"] value];
:local DSL2 [/system script environment get [/system script environment find name="DSL2netstatus"] value];

# Local FTP Sharing Server or any other remote host, should be set via netwatch or local script inside this script
#:local FTP [/tool netwatch get number=0 status]
# Using one liner code to get FTP ping status and store it in variable, you can use same for above dsl status as well by
# forcing routes via specific gateway
:global FTP;
:if ([/ping $FTPIP count=1] = 0) do {:put ":set FTP value=DOWN"} else={:set FTP value=UP}

# Admin SMS Number Config
:local cell1 "03333021909"

# Gmail Config
:global SYSID ([/system identity get name])
:global adminmail1 aacable@hotmail.com
:global gmailid GMAILID@gmail.com
:global gmailpwd GMAILPASSWORD
:global gmailip
:set gmailip [:resolve "smtp.gmail.com"];

# Print LOG
:log warning "INFO: Daily info for NETWORK @ $date $time\nActive PPPOE Users = $PPP\nUptime is $UPTIME\nCPU Load = $CPU\nDSL1 = $DSL1\nDSL2 = $DSL2\nFTP = $FTP\n\nPowered by J."
:log warning "Sending DAILY MORNING ALERT SMS on $cell1 ... by J."

# Sending SMS
/tool sms send port=usb3 phone-number=$cell1 message="INFO: Daily info for NETWORK @ $date $time\nActive PPPOE Users = $PPP\nUptime = $UPTIME\nCPU Load = $CPU\nDSL1 = $DSL1\nDSL2 = $DSL2\nFTP = $FTP\n\nPowered by J." channel=0

# Sending EMAIL - Use it if if required
#/tool e-mail send to=$adminmail1 password=$gmailpwd subject="INFO: Daily info for @ $date $time" body="Active PPPOE Users = $PPP\nUptime = $UPTIME\nCPU Load = $CPU\nDSL1 = $DSL1\nDSL2 = $DSL2\nFTP = $FTP\n\nPowered by J." from=$gmailid server=$gmailip start-tls=yes

 

Sample Image of SMS:

debug

sms


 

Enable Mikrotik to Receive SMS and run script

Use following command to enable SMS receiving on mikrotik.

#:delay 60
/tool sms set keep-max-sms=10 port=usb3 receive-enabled=yes secret=12345 channel 0
#:delay 3
#/tool sms set receive-enabled=no
#:delay 3
#/tool sms set receive-enabled=yes

From your mobile you can send following message to run script on remote mikrotik.

:cmd 12345 script test

 

Explanation:

  • :cmd to let mikrotik know that its command
  • 12345 is secret which you configured in /tool > sms,kind of password / authentication
  • script to let mikrotik know that its script related command  and
  • test is script name you want to run.

More references for mikrotik base sms are available at https://aacable.wordpress.com/tag/mikrotik-sms/

 


Another Beta Version:


# SENDING SMS TO ADMINS FOR DAILY MORNING ALERT ALERT

# Syed Jahanzaib

# Remove 'not required' items

# Your Network Name, change it here
:local NETWORK "ZzZzZz"

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

# Gather Data from Routerboard
:local PPP  ([/ppp active print count-only])
:local UPTIME [/system resource get uptime]
:local CPU [/system resource get cpu-load]
:local VOLT [/sys health get voltage]
:local TEMPR [/sys health get temperature]
:local CPUTEMP [/sys health get cpu-temperature]
:local PWRC [/sys health get power-consumption]
:local FAN1 [/sys health get fan1-speed]
:local FAN2 [/sys health get fan2-speed]
:local DSL1 [/system script environment get [/system script environment find name="DSL1netstatus"] value];
:local DSL2 [/system script environment get [/system script environment find name="DSL2netstatus"] value];

# Get Local Media sharing server status
:global FTP;
:if ([/ping 10.00.100 count=1] = 0) do {:put ":set FTP value=DOWN"} else={:set FTP value=UP}

# Modem Related
:local PORT usb3
:local CHANNEL 0

# Admin Mobile Number
:local cell1 "03333021909"

# Message to be send , which gather data from variables / zaib
:local MSG "INFO: Daily info for
$NETWORK  at $date $time
Active PPPOE Users  = $PPP
Uptime = $UPTIME
DSL1 = $DSL1
DSL2 = $DSL2
CPU Load = $CPU
FTP = $FTP
Voltage
$VOLT
CPU Temperature
$CPUTEMP
Power Consumption
$PWRC
Board Temperature
$TEMPR
FAN1 Speed
$FAN1
FAN2 Speed
$FAN2
Powered by J."

# Finally Send SMS with all gathered DATA for CCR_1036
/tool sms send port=$PORT channel=0 phone-number=$cell1 message="$MSG"

 

Regard’s
Syed Jahanzaib!


Filed under: Mikrotik Related

Adding External NTP Server in Domain Controller / Short Notes

$
0
0

SHORT NOTES FOR PERSONNEL REFERENCE ONLY


Command to check time on remote Windows PC.

all commands should be executed using administrative privileged account.

net time \\REMOTEPC

 

Adding external NTP server on DC

# Set NTP on DC / on server

w32tm /config /manualpeerlist:"59.106.180.168,0x1 62.201.215.14,0x1 "

w32tm /config /reliable:yes

net stop w32time && net start w32time

 

Command for client side windows , to force update time from DC

I added this file in GP so that every computer on reboot is forced to update time via server

# For client
net time \\DC_SERVER /set /y

 

Using PSTOOLS to execute command on remote PC.

# run command on remote computer.
PsExec.exe \\$1 -u DOMAIN\ADMIN -p PASS cmd "/c net time \\DC_SERVER /set /y"

 

Force client update from your admin PC forcefully.

I sued following script / batch file [named setrtime.bat] to manually update time on remote pc via remote, and show before/after time.

@echo off
cls
echo Current time of %1
echo -------------------------
net time \\%1
echo -------------------------
PsExec.exe \\%1 -u DOMAIN\ADMIN -p PASS cmd "/c net time \\DC_SERVER /set /y"
echo -------------------------
echo Current time of %1 AFTER CHANGING
net time \\%1

now use it like

netrtime.bat REMOTEPCNAME


Filed under: Microsoft Related

Prioritize SpeedTest.Net Results via Mikrotik Queue

$
0
0

speedtest


As implemented it yesterday , an old trick, NOTHING NEW really.

(Although I personally don’t see any reason why to prioritize such speed.test.net results, to fake whom, client or yourself ? lol)

Following is an simple demonstration on howto prioritize speedtest.net speed test.
Scenario: Client is allowed to get 512k , but when he will access speedtest.net to check the speed, he will able to see 2mb , (every user will be able to check it on 2mb limit , individually per ip basis) while his normal download/browsing will remain under 512k queue limit as showed in the picture above.

ROS CODE, Tested with 5.x and 6.x versions:


# Mark speedtest in Layer7 firewall
/ip firewall layer7-protocol
add name=speedtest regexp="^.+(speedtest).*\\\$"

# Marking SPEEDTEST.NET in mangle section using L7
/ip firewall mangle
add action=mark-connection chain=forward comment=SPEEDTEST layer7-protocol=speedtest new-connection-mark=speedtest_conn
add action=mark-connection chain=prerouting new-connection-mark=speedtest_conn protocol=tcp src-port=8080
add action=mark-packet chain=prerouting connection-mark=speedtest_conn new-packet-mark=speedtest_pkt passthrough=no
add action=mark-connection chain=postrouting dst-port=8080 new-connection-mark=speedtest_conn protocol=tcp
add action=mark-packet chain=postrouting connection-mark=speedtest_conn new-packet-mark=speedtest_pkt passthrough=no

# ADD PCQ so that i can be applied on per ip bases later in simple queue / zaib
/queue type
add kind=pcq name=download-2mb pcq-burst-rate=0 pcq-burst-threshold=0 pcq-burst-time=10s pcq-classifier=dst-address pcq-dst-address-mask=32 pcq-dst-address6-mask=64 pcq-limit=50 pcq-rate=2048k \
    pcq-src-address-mask=32 pcq-src-address6-mask=64 pcq-total-limit=2000
add kind=pcq name=upload-2mb pcq-burst-rate=0 pcq-burst-threshold=0 pcq-burst-time=10s pcq-classifier=src-address pcq-dst-address-mask=32 pcq-dst-address6-mask=64 pcq-limit=50 pcq-rate=2048k \
    pcq-src-address-mask=32 pcq-src-address6-mask=64 pcq-total-limit=2000

# Add simple QUEUE to limit speedtest.net 2mb PER USER
/queue simple
add burst-limit=0/0 burst-threshold=0/0 burst-time=0s/0s comment="Limit every Users at 2mb using PCQ. for speedtest only marked by mangle / zaib" direction=both disabled=no interface=all limit-at=0/0 max-limit=0/0 name=\
    "SpeedTest.Net 2Mb per use via g PCQ / zaib" packet-marks=speedtest_pkt parent=none priority=8 queue=upload-2mb/download-2mb target-addresses=192.168.5.0/24 total-queue=default-small

# Add simple QUEUE to limit user PC individually for rest of traffic, static or dynamic up to your network.
add burst-limit=0/0 burst-threshold=0/0 burst-time=0s/0s direction=both disabled=no interface=all limit-at=512k/512k max-limit=512k/512k name="Zaib Desktop 512k A llowed - 192.168.5.2" packet-marks="" \
    parent=none priority=8 queue=default-small/default-small target-addresses=192.168.5.2/32 total-queue=default-small
 

Move the speedtest.net queue on top! Ordering is very important in mikrotik, as rules are processed order wise , zero to bottom

Note: It can further be adjusted in PCQ, QUEUE TREE, etc etc as per network designed.


client


Regard’s
Jz


Filed under: Uncategorized

IBM Lotus Notes: Inbox Emails disappears when sort by DATE

$
0
0

Today one of our company user faced strange issue in his lotus notes clients {8.5.3 FP6}.

When they just open the Inbox without any sorting, there is no problem and all mail shown. Once they try to sort the mails by ‘Date‘,  all emails in inbox view disappears.

After trying various things like refresh/replace design etc, we finally managed to sort the issue by running UPDALL on that specific db.

From the Domino Server Console  , Issue following command


load updall -R mail/USERDB.nsf

( -R : Rebuild All used views)

Fixed !

Jz!

 


Filed under: IBM Related, Uncategorized

DMASOFTLAB Radius Manager SMS/Email Alert for already expired account!

$
0
0

sms_alert

Task:

In Radius manager billing system, it is required to send users SMS/Email informing them that his/her internet account has been expired today, using local KANNEL sms gateway via bash / curl. The only difference between this and other expiry alerts is that this script will send alert to user (usually) right after his account expires only.

 


 

OS:
Linux / Ubuntu 12.4.5 /32bit

Billing System:
DMASOFTLAB Radius Manager 4.1.5

SMS Info:
Kannel 4.x with Teltonika Serial/COM G10 Modem with ‘Ufone’ operator SIM and yearly SMS bundle package.

Teltonika ModemCOM-G10 Serial / Com used to send / receive SMS using KANNEL as SMS Gateway

 


 

Solution:

Make this script and schedule it to run daily in night.

mkdir /temp/
touch /temp/sms2expiredusers.sh
nano /temp/sms2expiredusers.sh

(& copy paste following, make sure to change the info as mentioned in variables)

#!/bin/bash
# # set -x
# BASH base SMS script to inform users that there internet account been expired in Radius Manager today.
# 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 / aacable at hotmail dot com / https://aacable.wordpress.com
# CREATED on : 17th November, 2015 / 10:am

# Modify following data before execution
SQLUSER="root"
SQLPASS="SQLPASS"
# Kannel Server IP, if its local leave it as it is
KURL="http://127.0.0.1:13013"
KID="kannel"
KPASS="kannel"
TMP="/tmp/expiredusers.sms"
DAYS="00"
COMPANY="YOUR COMPANY NAME"

### DO-NOT EDIT BELOW THIS LINE ####

#Remove temp files created by earlier execution of this script
rm -fr /tmp/*.sms
> $TMP

mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; select username,firstname,lastname,mobile,expiration from rm_users where expiration = CURRENT_DATE() - INTERVAL $DAYS DAY;" > $TMP

# Apply Count Loop Formula to read each users (from column 1 in tmp file) data and fit individualy later in sms
num=0
cat $TMP  |awk 'NF > 1' | while read users
do
num=$[$num+1]

USR=`echo $users |awk '{print $1}'`
FNAME=`echo $users |awk '{print $2}'`
LNAME=`echo $users |awk '{print $3}'`
mobile=`echo $users | awk '{print $4}'`
exp=`echo $users | awk '{print $5}'`


######################
# ACCOUNT EXPIRY CHECK and some JUNK data transported from other scripts i made earlier.
######################

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'`
SRVID=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = '$USR';"`
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |cut -f1 -d"."`

#LOOK FOR USER ACTUAL SERVICE NAME
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names  -e "use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = '$SRVID';"`


########### ACCOUNT STATUS EXPIRED TODAY ACTION / SEND SMS OR EMAIL ############

# PRINT FETCHED VALUES into files, which we will use later to send sms using url encoded command of kannel
echo "$COMPANY ALERT:

Dear Mr. $FNAME $LNAME, Your internet account ID [$USR] with Package of [$PKGNAME] has expired on $exp.
Please pay your dues to renew your account.

For furhter information & support you may reach us at our Helpline.

$COMPANY
Powered by Jz" > /tmp/$USR.sms

# PRINT FETCHED VALUES into files,  ECHO JUST FOR SCREEN BASE INFO / ZAIB
echo "$COMPANY ALERT:
Dear Mr. $FNAME $LNAME, Your internet account ID [$USR] with Package of [$PKGNAME] has expired on $exp.
Please pay your dues to renew your account.

For furhter information & support you may reach us at our Helpline.

$COMPANY
Powered by Syed.Jahanzaib"

# SEND SMS via KANNEL to USERS about epxired account.
curl "$KURL/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$mobile" -G --data-urlencode text@/tmp/$USR.sms

echo "Sleeping for 20 seconds to add delay in sms sending, to prevent your mobile SIM being blocked due to flooded sms"
sleep 20
done

Schedule it in cron ,
# Radius Manager expiry notification for today’s expired account Script

crontab -e
# add add following or as required.
@daily  /temp/sms2expiredusers.sh

Note: Some more testing need to be done, will do later and update this post.

Regard’s
Syed Jahanzaib


Filed under: Radius Manager

Changeip.com DDNS Bash Script for Linux

$
0
0

changeipzaib-linux-choice

Posting for personnel reference:

Following script was made to update ddns record at changeip.com from Linux base pc using bash. I found script on net as well, but didn’t worked the way i wanted, So I made one myself. Simple yet effective!

#!/bin/bash
# Changeip.com Script for Linux base systems using bash
# Created to suite local need in specific case. Well tested with CENTOS 6.x n UBUNTU 12.x
# Syed . Jahanzaib . aacable at hotmail dot com
# October , 2015
# Uncomment below to view debug log
# set -x

# Various variables, make sure to change the changeip.com credentials and hostname as required.
CIPUSER=yourchangeip_account@xxx.xxx
CIPPASS=PASSWORD
CIPHOST=changeip_password
URL="https://nic.changeip.com/nic/update?ip"
# Temp files and log file to record updates if required
EXTIP="/tmp/externalip.txt"
NEWIP="/tmp/newip.txt"
LOG="/var/log/changeip.log"
DATE=`date`

# If external ip text file not found, then create one
if [ ! -e "$EXTIP" ] ; then
touch "$EXTIP"
fi

# Download current LIVE ip from intenret to match with old ip
wget -q -O /tmp/newip.txt http://ip.changeip.com:8245
a=`cat $EXTIP`
b=`cat $NEWIP  | cut -f 2 -d "=" | cut -f 1 -d "-" -s | grep -m 1 ^`
if [[ $a != "$b" ]]
then

# changeip update now
curl "$URL=$b&u=$CIPUSER&p=$CIPPASS&hostname=$CIPHOST"

# Update New WAN IP in OLD File
echo $b > $EXTIP
echo

# Print OLD vs New Comparision for REVIEW
echo Old IP = $a
echo New IP = $b
echo Update Time = $DATE
echo Update Done.

# Print OLD vs New Comparision for REVIEW in LOG FILE for later review
echo "*********************************************"  >> $LOG
echo New IP FOUND > $LOG
echo Old IP = $a >> $LOG
echo New IP found at $DATE and IP is = $b >> $LOG

# IF OLD and NEW ip are same, then no need to update, just EXIT
else
echo $DATE / No need to change IP. DDNS BASH Script / Powered by Syed Jahanzaib
fi

# END

Filed under: Linux Related

Quick Note: Limit interface total bandwidth by Queue Tree

$
0
0

1

Requirement:

Limit interface total bandwidth , Lets say we want to limit ether1 interface (wan or whatever) to total 1 mb for upload / download.

Use following.


/ip firewall mangle
add action=mark-packet chain=prerouting comment="Mark Packets for Upload on WAN interface / jz" in-interface=ether1 new-packet-mark=upload
add action=mark-packet chain=postrouting comment="Mark Packets for Download on WAN interface / jz" new-packet-mark=download out-interface=ether1

/queue tree

add comment="Limit Total Traffic to 1mb in Queue Tree / Jz" disabled=yes max-limit=1M name=total-traffic parent=global queue=default
add comment="Limit upload Packets marked by mangle / Jz" disabled=yes name=upload packet-mark=upload parent=total-traffic queue=default
add comment="Limit download Packets marked by mangle / Jz" disabled=yes name=download packet-mark=download parent=total-traffic queue=default


 

You can use it to distribute specific amount of bandwidth to specific subnet or number of users. Example if you have 10 mb of bandwidth link and you want to distribute 5 mb to specific number of users. Lot of otehr queuing trick you can do.

Regard’s
Syed Jahanzaib


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