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

Rough Notes on Sending Email Alert Upon Service(s) Failure in Linux

$
0
0

1

[Not for all as its just a messy type of temporary work] This script was made for an operator who was facing strange problem that in random timings , the mysql or some times radiusd service stopped automatically, unfortunately the error was not sorted out as it occurs in awkward timings when no one is at NOC, so I made an workaround in the form of this script so that we can diagnose the issue later in details and in the meanwhile manually startup of services should not be required. The script was scheduled to run after every 10 minutes.

Note: This is not a solution, Just a workaround for very small period of time.

This script will check one or more services status, if found stopped, it will try to re-start them, and then check there status again and output there status in email.

In this example I took MYSQL and RADIUS services.

Sections:

  1. Create Required Scripts
  2. Download sendEmail tool to send email alerts
  3. Check Service status
  4. Another version of script [spicework] with prevention of repeated email in case of scheduler

 

1- Create Required Scripts

Create New  script checkstatus.sh which will be check the required services status and will output there result in text file which will be later used to send email (only if services found stopped)

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

Now add following contents in it

#!/bin/bash
SRV1="radiusd"
SRV2="mysqld"
SRV2D="mysql"
pid1=`pidof $SRV1`
pid2=`pidof $SRV2`
CURDATE=`date`

# Delete existing mail file
rm -fr  /temp/radiusstatus

# Check for SRV1 - RADIUSD - If not running then add its entry to local file for mail
if [ "$pid1" == "" ]; then
echo -e "$SRV1 service is NOT running, Trying to start . . ."
echo -e "$CURDATE $SRV1 service is NOT running, Trying to start . . ." >> /temp/radiusstatus
var1=$SRV1
service $SRV1 restart

# If SRV1 is running then Ignore and check for next service
else
echo $SRV1 service is Running OK , no further action required, EXITING. Script by Syed Jahanzaib
fi

# Check for SRV2 - MYSQL - If not running then add its entry to local file for mail
if [ "$pid2" == "" ]; then
echo -e "$SRV2D service is NOT running, Trying to start . . ."
echo -e "$CURDATE $SRV2D service is NOT running, Trying to start . . ." >> /temp/radiusstatus
var2=$SRV2
service $SRV2D restart

# If SRV2 is running then Ignore and check for next service
else
echo $SRV2 service is Running OK , no further action required, EXITING. Script by Syed Jahanzaib
fi

# Emal the results to admin if file exists
if [ ! -f /temp/radiusstatus ]
then
echo -e "$SRV1 and $SRV2D Services seems to be running ..."
else
echo -e "ALERT ... Services seems to be stopped, check email "

# Check Services status after starting them by calling external script
echo -e "=========================================" >> /temp/radiusstatus
echo -e "Current Status After running this script" >> /temp/radiusstatus
/temp/checkservice.sh $SRV1 >> /temp/radiusstatus
/temp/checkservice.sh $SRV2 >> /temp/radiusstatus

#Finally send email with all the data gathered
/temp/sendEmail-v1.56/sendEmail -t aacable@hotmail.com -u "$CURDATE / Billing Alert: $var1 $var2 Services found stopped and restarted now" -o tls=yes -s smtp.gmail.com:587 -xu YOURGMAIL_ID@gmail.com -xp YOURGMAILPASSWORD -f YOUTGMAIL_ID@gmail.com -o message-file=/temp/radiusstatus  -o message-content-type=text
fi

Save and Exit.


 

Now create another script checkservice.sh which will be called by above parent script to get the final status of services.

touch /temp/checkservice.sh
chmod +x /temp/checkservice.sh
nano /temp/checkservice.sh

Now add following contents in it
#!/bin/bash
PID=`pidof $1`
if [ `pgrep $1` ]
then
echo "$1 = OK   with pid $PID"
else
echo "$1 = NOT RUNNING"
fi

Save & Exit.


 

 

2- Download sendEmail tool to send email alerts

Install sendEmail Tool

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

ADD SUPPORTING LIBRARY

for ubuntu

apt-get -y install libio-socket-ssl-perl libnet-ssleay-perl perl

for centos

yum -y install perl perl-Crypt-SSLeay perl-IO-Socket-SSL

TESTING SEND EMAIL

Try to send email using command line: Example

/temp/sendEmail-v1.56/sendEmail -t 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 !


 

3- Check Service status

Now run the script like (make sure mysql and radiusd services are running)

/temp/checkstatus.sh

and you will see following result if servies are already running

3- ok

and if any service found to be stopped, it will try to start it and will send you the result.
(If one service found stopped it will only try to start that service, if both services found stopped it will try to start them both)

now for test stop the mysql or radiusd service and run the script again, this time you will see the result as follows

1- statu

and at email you will see the following result

2- result

You can then schedule the service to run after every xx minutes in CRON

crontab -l

# Run after every 10 minutes , Check for stopped services of mysql and radius
*/10 * * * * /temp/checksrv.sh

4- Another version of script [spicework] with prevention of repeated email in case of scheduler

http://unix.stackexchange.com/questions/218117/howto-prevent-service-down-repeated-email-sent-alerts-via-bash

#!/bin/bash
if pgrep "mysql" > /dev/null
then
    echo "MYSQL Running"
    rm -f /var/run/.mysql_mail_sent
else
    echo "mysqld ALERT Stopped"
    if [ ! -f /var/run/.mysql_mail_sent ]; then
echo -e "Send your mysql mail here"
        date > /var/run/.mysql_mail_sent
    fi
fi
if pgrep "radiusd" > /dev/null
then
    echo "radiusd Running"
    rm -f /var/run/.radiusd_mail_sent
else
    echo "radiusd ALERT Stopped"
    if [ ! -f /var/run/.radiusd_mail_sent ]; then
echo -e "Send your radiusd mail here"
        date > /var/run/.radiusd_mail_sent
    fi
fi

 

To DO Task:

Add check to prevent re-sending of email alerts if service have permanent failure or cannot be started in any case, the script will keep sending the email :D , so a check is required. Will add it later in some free time.

 

Regard’s
Syed Jahanzaib

 

 

 


Filed under: Linux Related

playSMS Send SMS via Script/CLI using webservices token

$
0
0

playSMS_logo_full

If you want to send SMS via playSMS using bash script or CLI, use the WEB SERVICES options in playSMS to facilitate this function. Its very useful in many scenarios.

Example:

I wanted to schedule a bash script which should run daily twice , this script collects various information of different servers, routers and then summarize it and send to admin via SMS. I could do it with GAMMU or other sms tools too, but the issue was that the server already have KANNEL with gsm modem configured and (in general standard) Kannel dont accept message with special characters, spaced, and strange formats that this script output, (with urlencoding possible but i dont want to do it) or I had to use sed awk and other tools to proper format them which was overhead work. and I wanted to utilized KANNEL or playSMS.

Mr. Anton from playSMS suggested to use web-services of playSMS and it worked beautifully :)

This is how it was done.


 

1- Enable WEB SERVICES & GENERATE TOKEN

Goto My Account > User Configuration

Select YES from drop down menu for “Enable webservices” and “Renew webservices token

Click on SAVE.

As showed in the following image below …

 

1- token


 

Now on same page you will now see the TOKEN number as showed in the following image below …

2 token

Copy / note down this this number, It will serve as a kind of password to let us send sms via php script.


 

2- Create & schedule  PHP script to execute your shell script

Now we have to create a PHP script which will use the above TOKEN to let us run the bash script and send it’s output to admin mobile number :)

mkdir /temp
touch /temp/dailysms.php
chmod +x /temp/dailysms.php
nano /temp/dailysms.php

now paste the following date , but be sure to modify the token number as per your own setup, and the script which you want to execute via php.

#!/usr/bin/php -q
# Script provided by mr.anton
# https://forum.playsms.org/t/schedule-message-to-run-sms-command/194/2
# https://aacable.wordpress.com
# Dated: 30th July, 2015
# Syed Jahanzaib

<?php

/**
 * cli2sms.php by Anton Raharja (antonrd@gmail.com)
 * Example script to get data from shell script and send it as SMS via playSMS
 * You need to have a configured and working playSMS
 * In this example playSMS is accessible from http://localhost/playsms
 * Don't forget to chmod +x cli2sms.php to use it from Linux shell
 *
 * You may modify this script to suit your needs
 *
 * Example usage:
 * - get stat data (eg: uptime) and send it periodically (using cron) to admin's mobile phones
 * - https://aacable.wordpress.com/2015/07/30/playsms-send-sms-via-scriptcli-using-webservices-token/
 */

// suppress error message
error_reporting(0);

// playSMS username/account for sending SMS
$username = 'admin';

// Webservices token for above username
$token = '1194df9e20d06c3790f0c6fef49f174a';

// playSMS Webservices URL
$playsms_ws = 'http://localhost/playsms/index.php?app=ws';

// destination numbers, comma seperated or use #groupcode for sending to group
// $destinations = '#devteam,+6200123123123,+6200456456456';
// $destinations = '+6200123123123,+6200456456456'; # for multiple recipients</pre>
<pre>$destinations = '03333021909';</pre>
<pre>
// get message to send from another shell script or Linux command, for example 'uptime'
// $message = trim(shell_exec('uptime'));
$message = trim(shell_exec('/temp/dailysms.sh'));</pre>
<pre>
// send via playSMS HTTP API
if ($message) {
    $ws = $playsms_ws . '&u=' . $username . '&h=' . $token . '&op=pv';
    $ws .= '&to=' . urlencode($destinations) . '&msg='.urlencode($message) . '&nofooter=1';
    $ret = @file_get_contents($ws);

    // echo $ret;
    echo "OK: message sent" . PHP_EOL;
} else {
    echo "ERROR: message is empty" . PHP_EOL;
}

// end of script

 

 


TEST

Now test by running the php file we just created above.

/temp/dailysms.php

and you should see something like below if every thing goes smoothly as planned

root@radius:/temp# ./dailysms.php

OK: message sent

 

and you will soon receive the SMS on your Mobile.

3- mobile


 

Regard’s

Syed Jahanzaib


Filed under: Linux Related

Enabling Authentication Logs in Freeradius

$
0
0

logs-error

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

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

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

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

and modify following

auth = no
auth_badpass = no
auth_goodpass = no

to following

auth = yes
auth_badpass = yes
auth_goodpass = yes

Save and Exit.

Now restart radius service by

service radiusd restart

Check Logs by

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

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

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

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

 

Regard’s

Syed Jahanzaib

 

 


Filed under: Linux Related, Radius Manager

CENTOS: Sending Email using SENDMAIL, Relay via GMAIL

$
0
0

gmail-logo

 

on request.

To send Email from Linux (Centos) shell using simple mail commands, you need to setup sendmail and use G-MAIL as relay (comes in handy). This was also required in radius manager setup where radius system sends various alerts to user like expiry alerts, quota alerts and my own customized alerting events.

First install required items.

yum -y install sendmail mailutils mailx sendmail-bin sendmail-cf cyrus-sasl-plain

Now issue following command to create Gmail authentication file in a folder in which you will add Gmail user name and password.

mkdir -m 700 /etc/mail/authinfo/

cd /etc/mail/authinfo/

Next we need to create an authentication file with following contents. You can name it as you like.
In this example I have configured it gmail-idpass:

Create file

nano gmail-idpass

and add following

AuthInfo: "U:root" "I:YOURGMAILID@GMAIL.COM" "P:YOURGMAILPASS"

[Note: Replace the above with your gmail id pass]

Save and Exit.

In the next step we will need to create a hash map for the above authentication file:

 makemap hash gmail-idpass < gmail-idpass 

Configure your sendmail

Now add bellow lines into your /etc/mail/sendmail.mc configuration file. Make sure you add them at end, but right above first “MAILER” definition line:

Example your file may look like this before editing (last few lines)


dnl MASQUERADE_DOMAIN(localhost)dnl
dnl MASQUERADE_DOMAIN(localhost.localdomain)dnl
dnl MASQUERADE_DOMAIN(mydomainalias.com)dnl
dnl MASQUERADE_DOMAIN(mydomain.lan)dnl

MAILER(smtp)dnl
MAILER(procmail)dnl
dnl MAILER(cyrusv2)dnl

You need to add the following lines above MAILER(smtp)dnl line

nano /etc/mail/sendmail.mc 

now paste following

# Adding config for gmail #
define(`SMART_HOST',`[smtp.gmail.com]')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/authinfo/gmail-idpass.db')dnl
# End config for gmail #

Save and exit.

Now your sendmail.mc file will look a like as following after editing (last few lines)


dnl MASQUERADE_DOMAIN(localhost)dnl
dnl MASQUERADE_DOMAIN(localhost.localdomain)dnl
dnl MASQUERADE_DOMAIN(mydomainalias.com)dnl
dnl MASQUERADE_DOMAIN(mydomain.lan)dnl

# Adding config for gmail #
define(`SMART_HOST',`[smtp.gmail.com]')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/authinfo/gmail-idpass.db')dnl
# End config for gmail #

MAILER(smtp)dnl
MAILER(procmail)dnl
dnl MAILER(cyrusv2)dnl

Now we need to re-build sendmail’s configuration. Run following command to do so.

 make -C /etc/mail 

Reload sendmail service:

 /etc/init.d/sendmail reload 

TEST VIA SENDING MAIL FROM SHELL

 

Now you can send email from your command line using mail command:


echo  "Mail Body - Test Message from CENTOS Shell by zaib" | mail -s "Subjct is Mail Sending from CLI" -r  yourgmailid  to-address@hotmail.com

This will send email to aacable @ hotmail.com

TO check its status via Logs, you can view file

tail -f /var/log/mailllog

and you may see something following on successfully sent message


Aug  6 08:51:10 radius-master sendmail[2800]: t76FpAGJ002800: from=yourgmailid@gmail.com, size=379, class=0, nrcpts=1, msgid=<55c3826e.HFMzaRe3xPHSfUV4%yourgmailid@gmail.com>, relay=root@localhost
Aug  6 08:51:11 radius-master sendmail[2801]: t76FpAS5002801: from=<yourgmailid@gmail.com>, size=527, class=0, nrcpts=1, msgid=<55c3826e.HFMzaRe3xPHSfUV4%yourgmailid@gmail.com>, proto=ESMTP, daemon=MTA, relay=localhost [127.0.0.1]
Aug  6 08:51:11 radius-master sendmail[2800]: t76FpAGJ002800: to=to-address@hotmail.com, ctladdr=yourgmailid@gmail.com (0/0), delay=00:00:01, xdelay=00:00:01, mailer=relay, pri=30379, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (t76FpAS5002801 Message accepted for delivery)

Aug  6 08:51:12 radius-master sendmail[2803]: STARTTLS=client, relay=gmail-smtp-msa.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=ECDHE-RSA-AES128-GCM-SHA256, bits=128/128
Aug  6 08:51:13 radius-master sendmail[2803]: t76FpAS5002801: to=<to-address@hotmail.com>, delay=00:00:03, xdelay=00:00:02, mailer=relay, pri=120527, relay=gmail-smtp-msa.l.google.com. [64.233.167.108], dsn=2.0.0, stat=Sent (OK 1438920803 by17sm6409593wib.18 - gsmtp)


 

You can also mail any command output like this

uptime | mail -s “UPTIME status for your server” -r  yourgmailid@gmail.com  to-address@hotmail.com

1


 

Done.

TIP: For radius manager mail function, as far as i remember, you dont need to modify any setting, rm will use localhost as mail sending feature which will afterwards relayed by sendmail using gmail.

 

Regard’s
Syed Jz


Filed under: Linux 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 Sales Activity Report Via Email in Billing System

$
0
0

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

As showed in the image below …

2

 

1

 


 

SCRIPT

dealer_renewal_yesterday.sh

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

fi
done


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

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


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

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

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

cat $FINALFILE


 

Install sendEmail Tool

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

ADD SUPPORTING LIBRARY

For UBUNTU [Life is really easy on ubuntu but with some glitches)

apt-get -y install libio-socket-ssl-perl libnet-ssleay-perl perl

For CENTOS

yum -y install perl perl-Crypt-SSLeay perl-IO-Socket-SSL

TEST SENDING EMAIL

Try to send email using command line: Example

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

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


 

Regard’s

Syed Jahanzaib


Filed under: Linux Related, Radius Manager

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


جزاک اللہ

سید جہانزیب


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 if you cross 200 or 100 SMS limit in 15 minutes then sim get blocked, and some mobile operator blocks SIM if you continuous send xxx number of msgs in x minutes.

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

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
# http://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
Viewing all 409 articles
Browse latest View live