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

Table ‘conntrack.tabidx’ doesn’t exist

$
0
0

mysql

Short reference:

While accessing RM users section , received “Table ‘conntrack.tabidx‘ doesn’t exist” error.
As showed in the image below …

 

1

This is how I fixed it.

On your RM box, create a file in which we will add table information.

touch conntrack.sql
nano conntrack.sql

Paste the following table

-- phpMyAdmin SQL Dump
-- version 2.11.0
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 03, 2008 at 11:57 AM
-- Server version: 5.0.18
-- PHP Version: 5.1.2

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `conntrack`
--

-- --------------------------------------------------------

--
-- Table structure for table `tabidx`
--

DROP TABLE IF EXISTS `tabidx`;
CREATE TABLE IF NOT EXISTS `tabidx` (
`date` date NOT NULL,
PRIMARY KEY  (`date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

 

 

SAVE and exit.

Now use the following command to import table into mysql database ‘conntrack

mysql -h localhost -u root -pYOURPASS radius < conntrack.sql

 


 

FYI,

The table code have been extracted from radius manager installation archive.  Example:
/radiusmanager-4.x.x/sql/rconntrack.sql

You can import any missing table from above file and import it in mysql.


 

 

Regard’s
Syed_Jahanzaib


Filed under: Linux Related

Mikrotik: WAN Data Monitoring via Scripting

$
0
0

As requested by few , specially from PK who are using PTCL DSL links and on few packages, PTCL have embossed Quota limit of 300GB (or likewise) and if the user exceed this limit, some penalty or extra charges are added in the monthly bill which is in some cases creates extra financial burden for DCN. Following are few scripts which can help you in this particular case that if the link crosses specific percentage of Quota limit, the link can be disabled, or second link (if available) can be activated or whatever operator chooses can be done by modifying the script action.

[The script idea was taken from the Mikrotik forum but those scripts didn’t performed well, therefore I modified and re-created few sections in some parts ]

Hope it will help you. Leave your comments …

Regard’s
Syed Jahanzaib



 

Scenario:

Two DSL Links , Primary DSL (ether1) have 4mb link with 50 GB data limit, where as secondary (or backup) link (ether2) have 2mbps with no data limit. Our requirement is to use Primary DSL Link which have higher bandwidth capacity and if the 50GB quota is reached to 90%, it should give warning (or email or disable Primary Link interface which have distance value of 1 and ENABLE Secondary Link which have distance value of 2 to auto take over)

Primary DSL = ether1
Secondary DSL = ether2

 


Scripts Description: [Tested with Mikrotik 6.27 Only]

In this example I have created 3 Scripts.

Benefit of using scripting method is that it can save values in a text file, so even if a route reboots, the script can retrieve last recorded data form the text file , that’s the biggest advantage for DCN ;) YKWIM

1- monitor_data

This script will get gather data from the interface stats and add it to text file which will be later read by second script which does the required action based on the counters in this file

2- check_useage

This script will read values from the text file created by above script, (monitor_data) and act accordingly to either ignore if the data usage is below specific value, and to perform what action if the data usage is above specific value.

3- check_date

This script will check in which the data value should be set to ZERO, usually start of month. So that counters can be reset.

 


 

1- MONITOR_DATA    [To get interface usage data]

Set this script in scheduler to run every hour. (collecting data every hour is reasonable IMHO]

# MONITOR_DATA Script (to get interface usage in file)
# First Part of WAN Data Quota Monitoring System
# Syed Jahanzaib / aacable@hotmail.com
# https://aacable.wordpress.com

# Set WAN interface you want to monitor
:local INT ether1

# Gather Interface RX bytes
:local counter [/interface get $INT rx-byte]

# Set Counter DATA value gathered by Interface RX bytes and add  TX bytes to get combined value
:set $counter ($counter + [/interface get $INT tx-byte])

:local traffic

# If previous data file not found, then create new one
:if ([:len [/file find where name=wandatauseage.txt]] < 1 ) do={
/file print file=wandatauseage.txt where name=wandatauseage.txt;
# Add some delay, for slow or high load routers
/delay delay-time=2;

# Adding Traffic Value in the file

/file set wandatauseage.txt contents="0";
};
:local before value=[/file get wandatauseage.txt contents]

:if ($counter > $before) do={
/file set wandatauseage.txt contents=$counter
} else= {
:set $traffic ($counter+$before)
/file set wandatauseage.txt contents=$traffic
};

 


2- check_usage    [To read data usage from file, and act accordingly]

Set this script in scheduler to run every hour or two.

# CHECK_USAGE > CHECK DATA USAGE Script (to read from file and act accordingly)
# Second Part of WAN Data Quota Monitoring System
# Syed Jahanzaib / aacable@hotmail.com
# https://aacable.wordpress.com</pre>
local traffic ([/file get wandatauseage.txt contents] / 1024 / 1024 / 1024)

# Set the WAN Interface Quota limit in GB
:local limit 50
:local percent ($traffic*100 / $limit)

# Set the percentage as required
:if ($percent >= 90) do={
:log warning "WAN INTERFACE Quota Exceeded 90% of $limit GB / zaib"

# OR Take specific action, either disable interface, change route, email , punch the fun-bags ; ) YKWIM ; ) etc etc
# Example Email like , but first make sure you have configured your email client properly
# /tool e-mail send to=YOUR_EMAIL_ADDRESS subject="WAN Traffic Quota warning: $percent% reached at $[/system clock get date], $[/system clock get time]" body="The traffic amount is $traffic GB \r\nThis is $percent% of the monthly limit\r\nQuota Monitor by Z"

}

Example if the quota reaches to its limit.

 

log_warning.

Example of EMAIL if the quota reaches to its limit.

 

email-war


 

3- check-date    [To reset counters in text file, if its 1st of the month]

Set this script in scheduler to run every daily in night at 1:00am, and if it found date to 1st of the month, it will reset the data counter file to zero.

# CHECK_DATE > CHECK DATE and RESET Counters on specific date ...
# Third Part of WAN Data Quota Monitoring System
# Syed Jahanzaib / aacable@hotmail.com
# https://aacable.wordpress.com

if  ([:pick [/system clock get date] ([:find [/system clock get date] "/" ] + 1) 6 ] = "01") do={/file set wandatauseage.txt contents="0"}

 


 

 

 

ME


Filed under: Mikrotik Related

Extending Linux Partition in VMWARE ESXI

$
0
0

Reference Guide to extend partition size in Linux hosted on vmware

TASK: Linux (Centos) is hosted in Vmware  , Current size of disk is 10 GB, and we want to expand it to 15 GB.

First turn off the guess linux OS. and take its properties and extend the disk as showed in the image below…

 

1

2

Click on EXPAND and it will take some time to complete the operation …

.

once its completed, power ON the guest Linux.


 

 

Add a new partition with the free space of the virtual disk.

fdisk  /dev/sda

press n            < To add new partition
press p            < Select type PRIMARY
press 3            < Type number for new part…
(when it will ask for sectors numbers/values, pres Enter twice for default values)
press t            < To change partition type value
press 3           < Select partition number
press 8e         < Type 8e
press w          <type ‘w’ to write changes to disk

at end you will see following message…

The partition table has been altered!

As showed in the image below …

fdisk-gui

REBOOT THE GUEST OS NOW …

reboot


 

after reboot completes, Now, create a new physical volume from the new partition, issue following command two times

pvcreate /dev/sda3
pvcreate /dev/sda3

  Physical volume "/dev/sda3" successfully created

 

 

Then extend the existing volume group, you may want to use vgdisplay to list and identify the volume groups you have.

vgdisplay

vgdisplay
--- Volume group ---
VG Name               vg_radius
System ID
Format                lvm2
Metadata Areas        1
Metadata Sequence No  3
VG Access             read/write
VG Status             resizable
MAX LV                0
Cur LV                2
Open LV               2
Max PV                0
Cur PV                1
Act PV                1
VG Size               9.51 GiB
PE Size               4.00 MiB
Total PE              2434
Alloc PE / Size       2434 / 9.51 GiB
Free  PE / Size       0 / 0
VG UUID               MzawqN-X33a-e5AY-QxE4-WFHV-r5mh-IM4MuT

4

.

Now look at VG NAME value, note it down… (Your might be different)

vgextend vg_radius /dev/sda3

 Volume group "vg_radius" successfully extended

 

Now, extend the logical volume, again, use vgdisplay to list and identify the logical volumes you have.

lvextend /dev/vg_radius/lv_root  /dev/sda3

 Extending logical volume lv_root to 13.50 GiB
Logical volume lv_root successfully resized

 

And finally, resize the filesystem in the logical volume

resize2fs /dev/vg_radius/lv_root

 resize2fs 1.41.12 (17-May-2010)
Filesystem at /dev/vg_radius/lv_root is mounted on /; on-line resizing required
old desc_blocks = 1, new_desc_blocks = 1
Performing an on-line resize of /dev/vg_radius/lv_root to 3539968 (4k) blocks.
The filesystem on /dev/vg_radius/lv_root is now 3539968 blocks long.


 

Now check the new DISK SIZE in Action !!! ; ) ALHAMDOLILLAH

df -h

 Filesystem                     Size  Used Avail Use% Mounted on
/dev/mapper/vg_radius-lv_root   14G  897M   12G   7% /
tmpfs                          504M     0  504M   0% /dev/shm
/dev/sda1                      485M   31M  430M   7% /boot

 

after-size-increases-

 


 

 

Regard’s
Syed Jahanzaib


Filed under: Linux Related

Windows 7 WEATHER GADGET ‘not working’ workaround!

$
0
0

From past few days, clients reported that Weather gadget stopped working with error “cannot connect to service …

gadgets-not-working

 


 

 

 

After doing some googling, it was revealed that dueto some security concerns Microsoft have discontinued it.  BUT  you can still Enable by following simple steps.

  1. Go to “C:\Users\USERNAME\AppData\Local\Microsoft\Windows Live\Services\Cache”
  2. Edit “Config.xml” by Right Click / EDIT
  3. Now donot change any thing & simply save it (CTRL+S or FILE -> Save) [without doing any modification]
  4. After 1-2 MINUTES, Restart the Gadget!

 

 

It will work Insha Allah !!!!

 

gadgets-working


 

 

Regard’s
Syed Jahanzaib


Filed under: Microsoft Related

Playing with the Mikrotik’s PCC

$
0
0

GT_50mbx2


dual-wan-pcclb


Following post is an reference guide or scrapbook, which have working codes for following.

  1. Dual WAN PCC with 2 DSL modems [configured in bridge mode] and dialing is done via mikrotik
  2. Port forwarding various ports [as required] from the internet to local web server
  3. PPPoE Server

Note: I ahve used SOURCE BASE classifier in this example, to avoid common load balancing problems like https links breakup, buffering issues stuck problem etc etc : )

Just to remind this is not a copy paste version. its not complete export version. I modified the data for reference. Read them carefully for better understanding. You can pick any section of your choice or as required. I will add more sections later …


NETWORK DETAiLS :

Mikrotik LAN Interface name = Local
Mikrotik WAN 1 interface name = WAN1
Mikrotik WAN 2 interface name = WAN2

Mikrotik LAN IP Address = 192.168.0.1
WEB Server on LAN side = 192.168.0.10

Mikrotik IP POOL for LAN DHCP = 10.0.0.1/8
Mikrotik IP POOL for PPPoE Users = 172.16.0.0/16

Let’s Start ….

kick




# Syed Jahanzaib / aacable@hotmail.com
# https://aacable.wordpress.com
# Adding IP pool for dhcp and pppoe

/ip pool
add name=pppoe-pool ranges=172.16.0.1-172.16.1.255
add name=dhcp_pool ranges=10.0.0.1-10.0.0.255

# ADD dhcp server

/ip dhcp-server
add address-pool=dhcp_pool authoritative=after-2sec-delay bootp-support=static disabled=no interface=Local lease-time=6h name="ZAIB DHCP SERVER"
/ip dhcp-server config
set store-leases-disk=5m
/ip dhcp-server network
add address=10.0.0.0/8 comment="zaib DHCP SERVER" dhcp-option="" dns-server=192.168.0.1,8.8.8.8 gateway="" ntp-server="" wins-server=""

# Adding dsl pppoe client connections, make sure your dsl modems are in bridge mode.

/interface pppoe-client
add ac-name="" add-default-route=yes allow=pap,chap,mschap1,mschap2 dial-on-demand=no disabled=no interface=WAN1 max-mru=1480 max-mtu=1480 mrru=disabled name=pppoe-out1 password=ISP_DSL_PASSWORD profile=default \
service-name="" use-peer-dns=no user=ISP_DSL_USERNAME
add ac-name="" add-default-route=yes allow=pap,chap,mschap1,mschap2 dial-on-demand=no disabled=no interface=WAN2 max-mru=1480 max-mtu=1480 mrru=disabled name=pppoe-out2 password=ISP_DSL_PASSWORD profile=default \
service-name="" use-peer-dns=no user=ISP_DSL_USERNAME

# Adding PPPoE Default Profile

/ppp profile
add change-tcp-mss=default dns-server=192.168.0.1,8.8.8.8 local-address=192.168.0.1 name=pppoe-profile only-one=yes rate-limit=512k/512k remote-address=pppoe-pool use-compression=default use-encryption=no \
use-mpls=default use-vj-compression=default

# Adding PPPOE Server
/interface pppoe-server server
add authentication=pap default-profile=pppoe-profile disabled=no interface=Local keepalive-timeout=10 max-mru=1480 max-mtu=1480 max-sessions=0 mrru=disabled one-session-per-host=no service-name=service1

# Create address list and add your users pppoe pool and web server ip addresses in this list, later we will use this list as ACL to allow specific users internet access
/ip firewall address-list
add address=172.16.0.1-172.16.1.255 comment="Allowed Users to Use Internet" disabled=no list="allowed users"
add address=192.168.0.10 comment="Allowed Users to Use Internet" disabled=no list="allowed users"

# Now start Mangling /ip firewall mangle

############################################ &gt; Zaib
#  PORT FORWARDING RELATED MANGLE SECTION STARTS
############################################

# This section is related to packet marking for Marking connections/packets arrived at WAN1 link
add action=mark-connection chain=input comment="Mark Connection - IN wan1,OUT wan1 Syed.Jahanzaib" disabled=no in-interface=pppoe-out1 new-connection-mark=pppoe_out1_conn passthrough=yes
add action=mark-routing chain=output comment="Mark Routing - IN wan1,OUT wan1" connection-mark=pppoe_out1_conn disabled=no new-routing-mark=pppoe_out1_traffic passthrough=no

# This section is related to packet marking for Marking connections/packets arrived at WAN2 link
add action=mark-connection chain=input comment="Mark Connection - IN wan2, OUT wan2" disabled=no in-interface=pppoe-out2 new-connection-mark=pppoe_out2_conn passthrough=yes
add action=mark-routing chain=output comment="Mark Routing -  IN wan2,OUT wan2" connection-mark=pppoe_out2_conn disabled=no new-routing-mark=pppoe_out2_traffic passthrough=no

add action=mark-connection chain=forward comment="Mark Connection for new conn - Packet Forward wan1, out wan1" connection-state=new disabled=no in-interface=pppoe-out1 new-connection-mark=pppoe_out1_pfw \
passthrough=no
add action=mark-routing chain=prerouting comment="Mark Packets for new conn - Packet Forward wan1, out wan1" connection-mark=pppoe_out1_pfw disabled=no in-interface=Local new-routing-mark=\
pppoe_out1_traffic passthrough=no

add action=mark-connection chain=forward comment="Mark Connection for new conn - Packet Forward  wan2, out wan2" connection-state=new disabled=no in-interface=pppoe-out2 new-connection-mark=pppoe_out2_pfw \
passthrough=no
add action=mark-routing chain=prerouting comment="Mark Routing for new conn - Packet Forward  wan2, out wan2" connection-mark=pppoe_out2_pfw disabled=no in-interface=Local new-routing-mark=\
pppoe_out2_traffic passthrough=no

########################
#  GENERAL PCC SECTION
########################

# This section is related to packet marking for general PCC
add action=accept chain=prerouting disabled=no in-interface=pppoe-out1
add action=accept chain=prerouting disabled=no in-interface=pppoe-out2

# Classifier for dual WAN links
add action=mark-connection chain=prerouting disabled=no dst-address-type=!local new-connection-mark=wan1_conn passthrough=yes per-connection-classifier=src-address:2/0 src-address-list="allowed users"
add action=mark-connection chain=prerouting disabled=no dst-address-type=!local new-connection-mark=wan2_conn passthrough=yes per-connection-classifier=src-address:2/1 src-address-list="allowed users"

add action=mark-routing chain=prerouting connection-mark=wan1_conn disabled=no new-routing-mark=to_wan1 passthrough=yes src-address-list="allowed users"
add action=mark-routing chain=prerouting connection-mark=wan2_conn disabled=no new-routing-mark=to_wan2 passthrough=yes src-address-list="allowed users"

##########################################################
#  NAT / DST-NAT / MASQUERADE SECTION / PORT FORWARD
##########################################################

/ip firewall nat

###  Route WEB Port from wan links to local web server IP/PORT
add action=dst-nat chain=dstnat comment="Route WEB Server Port 80 from INTERNET LINK1" disabled=no dst-port=80 in-interface=pppoe-out1 protocol=tcp to-addresses=192.168.0.10 to-ports=80
add action=dst-nat chain=dstnat comment="Route WEB Server Port 80 from INTERNET LINK2" disabled=no dst-port=80 in-interface=pppoe-out2 protocol=tcp to-addresses=192.168.0.10 to-ports=80

### Allow internet access/masquerade to allowed users list only (ACL)
add action=masquerade chain=srcnat disabled=no out-interface=pppoe-out1 src-address-list="allowed users"
add action=masquerade chain=srcnat disabled=no out-interface=pppoe-out2 src-address-list="allowed users"

##################################################
#  ROUTE SECTION FOR PCC AND PORT FORWARD PACKETS
##################################################
# Add routes for general PCC
/ip route
add check-gateway=ping disabled=no distance=1 dst-address=0.0.0.0/0 gateway=pppoe-out1 routing-mark=to_wan1 scope=30 target-scope=10
add check-gateway=ping disabled=no distance=2 dst-address=0.0.0.0/0 gateway=pppoe-out2 routing-mark=to_wan2 scope=30 target-scope=10

# Add routes for IN/OUT port forwarding packets
add disabled=no distance=1 dst-address=0.0.0.0/0 gateway=pppoe-out1 routing-mark=pppoe_out1_traffic scope=30 target-scope=10
add disabled=no distance=1 dst-address=0.0.0.0/0 gateway=pppoe-out2 routing-mark=pppoe_out2_traffic scope=30 target-scope=10

Regard’s
Syed Jahanzaib


Filed under: Mikrotik Related

Howto display combined values of two interfaces in single MRTG graph

$
0
0

mrtgmrtg-for-combo-wan

 


 

 

If you want to view combined value for two or more interfaces in single mrtg graph, here is the simple way to go…
[thanks to MRTG which supports simple math formulas as well :)  ]

Example:

On your router you have two wan interfaces (You’re not limited to just two) with the names of WAN1 and WAN2 (in load balancing mode or whatever) and you want to display single graph which should displays combined value for both interfaces so that you can have an idea how much WAN bandwidth is consuming (good to make average historical based graphs) , use following cfg

 


# combinedwan.cfg
Target[192.168.0.1_combowan]: #WAN1:publicsnmp@192.168.0.1: + #WAN2:publicsnmp@192.168.0.1:
MaxBytes[192.168.0.1_combowan]: 12500000
Title[192.168.0.1_combowan]: Traffic Analysis for BOTH DSL WAN Links WAN1+WAN2 -- MikroTik
PageTop[192.168.0.1_combowan]: <h1>Traffic Analysis for BOTH DSL WAN Links WAN1+WAN2  -- MikroTik</h1>
<div id="sysdetails">
<table>
<tr>
<td>System:</td>
<td>MikroTik Routerboard with Load Balacning</td>
</tr>
<tr>
<td>Maintainer:</td>
<td>aacable@hotmail.com</td>
</tr>
<tr>
<td>Description:</td>
<td>WAN1 + WAN2 Combined</td>
</tr>
<tr>
<td>ifType:</td>
<td>ethernetCsmacd (6)</td>
</tr>
<tr>
<td>ifName:</td>
<td>WAN1+WAN2</td>
</tr>
<tr>
<td>Max Speed:</td>
<td>100 Mbits/s</td>
</tr>
<tr>
<td>Ip: DYNAMIC</td>
<td>No Ip (No DNS name)</td>
</tr>
</table>
</div>

 


 

Note: Change the Interfaces names, SNMP string and IP according to your network setup. You can get interface numbers/names from the individual mrtg.cfg / router.cfg entries. cfgmaker can help you in this regard example

cfgmaker snmp@192.168.0.1 > router.cfg

 

Happy Graphing :)

Regard’s

Syed Jahanzaib

 


Filed under: Linux Related, Mikrotik Related

Short Notes Series: Adding VPN (PPTP) Dialer in Linux

$
0
0

 

vpn-animationAssalam Va Alaykum,

Following are short notes on How I added VPN [pptp] client in Linux [initially in centos, later I will add commands for Ubuntu as well] to a mikrotik base pptp vpn server. Mikrotik is using default profile for vpn users. Something like this

Mikrotik Section:

PPP Default Profile …

mt2

 

PPP Default Profile Protocols Section …

mt-ppp-default-profile

& PPP USER …

mt-3

Ok now moving to linux to add vpn client


 

Adding PPTP VPN Client in CENTOS 6

First install PPTP client.

yum install pptp -y

Now add the username and password inside /etc/ppp/chap-secrets file

Note: I used NANO editor as its easier, but you can use any other editor like VI or other

nano /etc/ppp/chap-secrets

Now add your USER ID and PASSWORD in following scheme …

# Secrets for authentication using CHAP
# client        server           secret                 IP addresses
test              PPTP           testpass                       *

In above example, my vpn user name is test, and password is testpass.

Save & Exit.

Now create a VPN Dialer configuration file under /etc/ppp/peers directory called testvpn  using any text editor

nano /etc/ppp/peers/testvpn

and use following format


pty "pptp 1.1.1.1 --nolaunchpppd"
lock
noauth
nobsdcomp
nodeflate
name test
remotename PPTP
require-mppe-128
#file /etc/ppp/options.pptp
ipparam testvpn

In above Example. Make sure to change following items

1.1.1.1 > with your target vpn server IP address or name
name test > Replace TEST with your supplied vpn dialer user name

Save & Exit.

 


 

Test Dialer Connectivity …

To dial , use following command from terminal …

pppd call testvpn

In second terminal, open messages log file so you can see the log info (and error messages if any, useful in troubleshooting) …

tail -f /var/log/messages

Upon successful logon,  the messages log shoul show you something as following …

Apr 13 06:43:39 radius pppd[1441]: pppd 2.4.5 started by root, uid 0
Apr 13 06:43:39 radius pppd[1441]: Using interface ppp0
Apr 13 06:43:39 radius pppd[1441]: Connect: ppp0 <--> /dev/pts/2
Apr 13 06:43:39 radius pptp[1442]: anon log[main:pptp.c:314]: The synchronous pptp option is NOT activated
Apr 13 06:43:39 radius pptp[1450]: anon log[ctrlp_rep:pptp_ctrl.c:251]: Sent control packet type is 1 'Start-Control-Connection-Request'
Apr 13 06:43:39 radius pptp[1450]: anon log[ctrlp_disp:pptp_ctrl.c:739]: Received Start Control Connection Reply
Apr 13 06:43:39 radius pptp[1450]: anon log[ctrlp_disp:pptp_ctrl.c:773]: Client connection established.
Apr 13 06:43:40 radius pptp[1450]: anon log[ctrlp_rep:pptp_ctrl.c:251]: Sent control packet type is 7 'Outgoing-Call-Request'
Apr 13 06:43:40 radius pptp[1450]: anon log[ctrlp_disp:pptp_ctrl.c:858]: Received Outgoing Call Reply.
Apr 13 06:43:40 radius pptp[1450]: anon log[ctrlp_disp:pptp_ctrl.c:897]: Outgoing call established (call ID 0, peer's call ID 921).
Apr 13 06:43:40 radius pppd[1441]: CHAP authentication succeeded
Apr 13 06:43:40 radius pppd[1441]: MPPE 128-bit stateless compression enabled
Apr 13 06:43:41 radius pppd[1441]: local  IP address 172.16.0.249
Apr 13 06:43:41 radius pppd[1441]: remote IP address 172.16.0.1

 

You can also check vpn interface via

ip a | grep ppp

Result:

[root@radius ~]# ip a | grep ppp
13: ppp0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1456 qdisc pfifo_fast state UNKNOWN qlen 3
link/ppp
inet 172.16.0.249 peer 172.16.0.1/32 scope global ppp0

Try pinging a system in the VPN network and you should get response from other side :)


 

 

ADDING ROUTE via pptp dialer to access remote / target destination

Khunjerab - Pass Route / Beautiful PAKISTAN :) / zaib

Khunjerab – Pass Route / Beautiful PAKISTAN :) / zaib

 

NOTE: This will not add any ROUTE information in routing table, you can add it manually or in ifup/down file, As I didn’t required any default gateway but I added just one static route to access specific server only, example:

> Edit or create following file /etc/ppp/ip-up.local

& add following entries

#!/bin/bash
route add -net 2.0.0.0/8 dev ppp0

Now assign it executable rights
chmod +x /etc/ppp/ip-up.local

Note: change 2.0.0.0/8 to match your remote target subnet you want to access via your linux pc. This is recommended method as it works on AUTO :)

 

Or if its just for one session , use following command

route add -net 192.168.10.0 netmask 255.255.255.0 gw 172.16.0.1 dev ppp0 

192.168.10.0 is the remote office server subnet, and 172.16.0.1 is the virtual gateway this pc should use to access remote site.

Or if all traffic should route via this , use (not tested yet)

route add default gw 172.16.0.1 ppp0

Howto Stop Dialer

To Stop dialer, you can simply kill it with

killall pppd

 


 

Howto add AUTO RE-CONNECT / RE-DIAL option

Note: To make it auto re-connect (redial) you can add following directives in your vpn configuration file (example /etc/ppp/peers/testvpn) to make it auto reconnect.

maxfail 0
persist

maxfail 0 and persist is for the connection to reconnect and retry forever.

You can also use script and schedule it to keep check on the dialer connectivity and perform specific action like inform you  via email, or whatever you like it to trigger. If interested in script base approach, there is already a good guide for this purposes here :)

http://www.jamescoyle.net/how-to/968-script-to-automatically-detect-and-restart-linux-pptp-client


 


.

Regard’s
Syed Jahanzaib


Filed under: Linux Related

Fun With SMS Management System [playSMS]

$
0
0
This post is a drafted version, You may miss many details in it. I will sanitize it and add more details with CHANGE-LOG later …

1


 

 

Recently I installed playsms at a network [where Radius manager along with Kannel was already configured to send sms notificatiosn to subscribers] and after seeing playSMS  amazing features , I thought to share some basics of it.

I found that many guides available on the internet for installing playSMS are either for older versions or with much manual methods which can be sometimes confusing for the beginners, therefore I decided to write an easier version of installation guide of playSMS.

 

kick

 

So what is playSMS ?

playSMS_logo_full

playSMS is a Free and Open Source web base SMS management software. designed by Mr. Anton Raharja at http://playsms.org.

Its main job is to handle outgoing and incoming SMS, single or bulk SMS. You can call it ‘SMS Gateway’ . A flexible Web-based mobile portal system that it can be made to fit to various services such as an SMS gateway, bulk SMS provider, personal messaging system, corporate and group communication tools

Since its open-source application therefore you can adjust it to suite your need, modify it as per your requirements and it can fit with other gateways as well like Kannel (which I have used in radius box). It can receive sms and act accordingly, you can create POLL, Quiz, subscription to any list/package via SMS. SMS 2 Email, Refresh user account via sms using scratch card like wi-tribe or some other ISP’s offers, or mobile companies like send sms to specific number with the specific text and scratch number, inquire system detail , execute specific command, etc etc.

Feature Highlights of playSMS [official]

  • Multiple database engine supported (through PHP PEAR DB)
  • Send SMS to single mobile phone
  • Send SMS broadcasted to a group of mobile phones, or SMS bulk
  • Support sending text, flash and unicode messages
  • Capable of handling large amount of SMS (user reported 500k SMS monthly)
  • Receive private SMS to Inbox and forward it to email (mobile2web) and user’s mobile phone
  • Forward single SMS from mobile to a group of mobile phones
  • Provides SMS to email and email to SMS by polling mailbox
  • SMS autoreply, for easy autoreplying formatted incoming SMS
  • SMS board, forward received SMS to email, export output in JSON and a few other formats
  • SMS command, execute server side shell script using SMS
  • SMS custom, forward incoming SMS to custom apps, locally or hosted on external URL
  • SMS poll, manage polling system using SMS, export output in graph, JSON and other formats
  • SMS quiz, serve quizzes on SMS
  • SMS subscribe, manage user subscribes to a service using SMS
  • SMS sync to utilize SMSSync app from http://smssync.ushahidi.com
  • Create your own features, tools, themes and gateway modules as a plugin
  • Supports Gammu, Gnokii, Kannel, SMS Server Tools, Msgtoolbox, Uplink, Nexmo, Twilio, Infobip and Clickatell
  • Supports multiple active SMSC
  • Supports simulation gateway for testing incoming and outgoing SMS
  • Route outgoing SMS by prefix
  • Route outgoing SMS per user
  • Webservices for sending SMS, retrieving delivery reports, checking credits and more
  • Long SMS support, length of text is configurable
  • Rate SMS by destination prefix
  • SMS credit system per user
  • Multiple SMSC activated and rout-able
  • Timezone settings
  • Multi-language user interface (English, French, Bahasa Indonesia, Russian and a few others)
  • Easily add new language for user interface
  • Web-based interface
  • Android client app

I used playSMS in conjunction with Kannel. So you should configure Kannel first and make sure you can send sms via kannel. You can follow my guide to install KANNEL first.

https://aacable.wordpress.com/2012/11/26/howto-configure-your-local-http-gateway-using-kannel-on-ubuntu/

 


Since its a long post with various section, I will update various section accordingly.

Sections:

 

  1. Hardware / Software used for this guide
  2. Kannel.Conf Sample for playSMS
  3. playSMS Install Instructions for Ubuntu OS
  4. Configuration of playSMS via admin panel
  5. Configure GATEWAY section to enable playsms send/receive sms
  6. Sending Test Message
  7. TROUBLESHOOTING VIA  LOGS
  8. Creating User Account with CREDITS base system, and send / receive in User Inbox / a type of SMS PABX :D
  9. Creating COMMAND to be executed via SMS
  10. Creating SMS base POLL system
  11. Scheduling SMS to be send at specific time to person or group   [added on 11th May, 2014]
  12. Add SMS base QUIZ System    [added on 11th May, 2014]

 

1- Hardware / Software used for this guide

  • OS = Ubuntu 12.04.5 LTS , 32bit
  • Hardware = Teltonika Modem USB/E12 UM1400 [This is best modem I have ever used, so stable :)
    Later replaced it with Huawei usb modem as huawe modems are way too cheap & easily available]

 

 

2- Kannel.Conf Sample for playSMS

As I mentioned in the beginning, I used KANNEL as gateway for playSMS, so you should configure KANNEL first and make sure you can send sms with it. Once successful, then you can add/replace following SMS_SERVICE section in /etc/kannel.conf to make playSMS handle the received SMS.

/etc/kannel/kannel.conf , modify only SMS-SERVICE section

group = sms-service
keyword = default
get-url = "http://localhost/playsms/index.php?app=call&cat=gateway&plugin=kannel&access=geturl&t=%t&q=%q&a=%a&Q=%Q"
accept-x-kannel-headers = true
max-messages = 1000
concatenation = true
catch-all = true
text = "Galaxy ROBOT by Zaib"
omit-empty = true

 

 

3- PLAYSMS [ver 1.0-rc9] Install Instructions for UBUNTU OS.

As usual first update Ubuntu , then install require packages.

apt-get update

apt-get install apache2 mysql-server php5 php5-cli php5-mysql php5-cgi php-pear php-gettext libapache2-mod-php5 apache2-mpm-prefork php-db make gcc lynx wget curl

Now you need to create MYSQL database for playsms. You can create it either via login to your mysql console , or issue direct command to create it as showed in the example below …

mysql -u root -pROOTPASS -e "create database playsms";
mysql -u root -pROOTPASS -e "grant usage on *.* to playsms@localhost identified by 'playsms';"

Change credentials as required.


 

Installing playSMS …

First download the playsms package, and unrar it

mkdir /temp
cd /temp
wget https://github.com/antonraharja/playSMS/archive/1.0-rc9.tar.gz
ls
tar zxvf 1.0-rc9.tar.gz
cd playSMS-1.0-rc9/
cp install.conf.dist install.conf

Now edit install.conf and change the info as required, like db name, mysql id password. The installer script uses this file to pick values and install the package accordingly. So make sure all directives are defined properly before firing up the actuall installation script.
Also make sure you change the PATH to match your linux distribution, like in ubuntu the path of www is /var/www

1

Once you done editing info, press b to continue & it will continue to install the playsms.

once all done verify that you can see the playsms in process

root@radius:/temp/playSMS-1.0-rc9# ps aux |grep playsms
root      4568  0.6  0.3  51032 15844 pts/1    S    10:58   0:26 /usr/bin/php -q /usr/local/bin/playsmsd schedule
root      4570  0.7  0.3  51032 15876 pts/1    S    10:58   0:30 /usr/bin/php -q /usr/local/bin/playsmsd dlrssmsd
root      4572  0.6  0.3  51816 16496 pts/1    S    10:58   0:27 /usr/bin/php -q /usr/local/bin/playsmsd recvsmsd
root      4574  0.5  0.3  51032 15412 pts/1    S    10:58   0:23 /usr/bin/php -q /usr/local/bin/playsmsd sendsmsd
root     20560  0.0  0.0   4388   824 pts/0    S+   12:06   0:00 grep --color=auto playsms

root@radius:/temp/playSMS-1.0-rc9#

If you see playSMS running, basic installation part is done, now moving to Configuration part…


 

4- Configuration of playSMS via admin panel …

Now login to playSMS web admin panel by

http://yourip/smsplay

Use default id password which is

id = admin
password = admin

2


5- Configure GATEWAY section to enable playsms send/receive sms

After successful login we have to first configure GATEWAY pointing to KANNEL to send receive sms using kannel as our main gateway. You can skip kannel or use other gateway too depend on your choice, but since I was already using kannel because of Radius Manager, so I simply used it because of its versatility and highly customization.

Goto Settings / Manage gateway and SMSC
As showed in the image below …

3


 

Now in the List of gateways, click on edit button (wheel) next to KANNEL.
As showed in the image below …

4

Now at Manage Kannel window adjust the parameters according to your old kannel configuration. pay attention to username password & proper ports.
As showed in the image below …

5Now save it.

 

Open Manage Gateway page again and click on + sign to add KANNEL as your gw.
As showed in the image below …

6


 

 

Now goto Settings / Main Configuration and select KANNEL as your Default SMSC
As showed in the image below …

7Save it.


 

6- SENDING TEST MESSAGE

Ok its time to hit the road.  for some test.

Goto My account / Compose Message and send msg to any number.
As showed in the image below …

8

and you should receive it on your handset.
As showed in the image below …

9


7- TROUBLESHOOTING VIA  LOGS

You can inspect logs in following folders (for playSMS)

tail -f /var/log/playsms/playsms.log

Successful sms sent result should be something like this

YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L2 sendsms # start uid:1 sender_id:[1234] smsc:[]
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L3 sendsms # maxlen:459 footerlen:7 footer:[ @admin] msglen:57 message:[test msg from zaib to mobile using playsms with kannel :)]
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L2 sendsms_queue_create # saving queue_code:8cf227742d7d5dab570f7ed4532cf936 src:1234 scheduled:2015-05-08 12:28:32
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L2 sendsms_queue_create # saved queue_code:8cf227742d7d5dab570f7ed4532cf936 id:14
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L3 sendsms_manipulate_prefix # before prefix manipulation:[03333021909]
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L3 sendsms_manipulate_prefix # after prefix manipulation:[03333021909]
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L3 simplerate_hook_rate_getbyprefix # rate not found to:03333021909 default_rate:0
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:64 unicode:0 to:03333021909 enable_credit_unicode:0 count:1 rate: charge:0
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L2 sendsms # dst:1 sms_count:1 total_charges:0
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L2 sendsms_queue_push # saving queue_code:8cf227742d7d5dab570f7ed4532cf936 dst:03333021909
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L2 sendsms_queue_push # saved queue_code:8cf227742d7d5dab570f7ed4532cf936 smslog_id:14
YOUR_IP YOUR_IP 2015-05-08 12:28:32 PID554c659fcb40d admin L2 sendsms # end queue_code:8cf227742d7d5dab570f7ed4532cf936 queue_count:1 sms_count:1 failed_queue:0 failed_sms:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsmsd # start processing queue_code:8cf227742d7d5dab570f7ed4532cf936 sms_count:1 scheduled:2015-05-08 12:28:32 uid:1 gpid:0 sender_id:1234
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsmsd # sending queue_code:8cf227742d7d5dab570f7ed4532cf936 smslog_id:14 to:03333021909 sms_count:1 counter:1
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 sendsms_intercept # msgtemplate modified sms_sender:[1234] sms_footer:[@admin] sms_to:[03333021909] sms_msg:[test msg from zaib to mobile using playsms with kannel :)] uid:[1] gpid:[0] sms_type:[text] unicode:[0] queue_code:[8cf227742d7d5dab570f7ed4532cf936] smsc:[]
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 outgoing_hook_sendsms_intercept # no SMSC found uid:1 parent_uid:0 from:1234 to:03333021909
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsms_process # start
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 simplerate_hook_rate_getbyprefix # rate not found to:03333021909 default_rate:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:64 unicode:0 to:03333021909 enable_credit_unicode:0 count:1 rate: charge:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 simplerate__cansend # allowed user uid:1 sms_to:03333021909 credit:0.000 count:1 rate: charge:0 balance:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsms # saving smslog_id:14 u:1 g:0 gw:kannel smsc:kannel s:1234 d:03333021909 type:text unicode:0 status:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsms_process # saved smslog_id:14 id:14
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 sendsms # final smslog_id:14 gw:kannel smsc:kannel message:test msg from zaib to mobile using playsms with kannel :) @admin len:64
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 kannel_hook_sendsms # enter smsc:kannel smslog_id:14 uid:1 to:03333021909
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 kannel_hook_sendsms # URL: http://localhost:13013/cgi-bin/sendsms?username=kannel&password=KANNELPASSWORD&from=1234&to=03333021909&dlr-mask=31&dlr-url=http%3A%2F%2Fclick.onmypc.net%3A1235%2Fplaysms%2Findex.php%3Fapp%3Dcall%26cat%3Dgateway%26plugin%3Dkannel%26access%3Ddlr%26type%3D%25d%26smslog_id%3D14%26uid%3D1&account=admin&text=test+msg+from+zaib+to+mobile+using+playsms+with+kannel+%3A%29+%40admin
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 kannel__outgoing # smslog_id:14 response:0: Accepted for delivery
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 dlr # isdlrd:1 smslog_id:14 p_status:0 uid:1
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 kannel__outgoing # end smslog_id:14 p_status:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 simplerate__deduct # enter smslog_id:14
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 simplerate_hook_rate_getbyprefix # rate not found to:03333021909 default_rate:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:64 unicode:0 to:03333021909 enable_credit_unicode:0 count:1 rate: charge:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 credit_hook_rate_setusercredit # no changes uid:1 balance:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 simplerate__deduct # user uid:1 parent_uid: smslog_id:14 msglen:64 count:1 rate: charge:0 credit:0.000 balance:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 simplebilling__post # saving smslog_id:14 rate: credit:0.000 count:1 charge:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 simplebilling__post # saved smslog_id:14 id:14
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 simplerate__deduct # deduct successful uid:1 parent_uid: smslog_id:14
- - 2015-05-08 12:28:32 PID554c65a055703 - L3 simplerate__deduct # credit_lowest_limit:0 balance:0 charge:0
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsms_process # end
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsmsd # result queue_code:8cf227742d7d5dab570f7ed4532cf936 to:03333021909 flag:1 smslog_id:14
- - 2015-05-08 12:28:32 PID554c507a0ec86 - L3 dlrd # id:14 smslog_id:14 p_status:0 uid:1
- - 2015-05-08 12:28:32 PID554c65a055703 - L2 sendsmsd # finish processing queue_code:8cf227742d7d5dab570f7ed4532cf936 uid:1 sender_id:1234 sms_count:1

[Be aware that I used Log Level 3 [debug mode to get more info] which is configurable in /var/www/playsms/config.php ]


 

8- Creating User Account with CREDITS base system, and send / receive in User Inbox / a type of SMS PABX :D

Using playSMS, we can create user accounts and add credits in it, so when user sends sms, balance would deduct from his account automatically , and once his balance finishes, he wont be able to send sms. User will be assigned with an ID and Password, He can send SMS via web panel, also he can receive SMS (the other party must reply to or send sms with @username in his sms in order to receive it in specific user inbox).

 

Enable SMS Routing to INBOX in playSMS

  • First enable Route incoming SMS
  • Goto  Settings / Route Incoming SMS
  • Select YES in Scan incoming SMS for @username and Scan incoming SMS for #groupcode
  • and SAVE.

 

10

 

Create User Account 

Now we will create a test user account and will add credits in it too.

  • Goto Settings / Manage Account > User
  • Click on + sign to add user

Add the details as required and click on SAVE.
As showed in the image below …

11

User Account Creation Done.

ADDING CREDITS in user Account

To add credits in user account,

  • Goto Settings / Manage Credit
  • Click on + sign
  • Select User
  • Add amount and Save

24

 

 

Now logout from admin ID, or use another browser to login to playSMS panel with the newly created account and send an test sms  to any number. After sending sms, you will see that your balance will be deducted (I added 10rs as a balance, and set per sms cost 5rs, so after sending my remaining balance is 5 rs only

12

Howto receive SMS in user INBOX ?

You have to inform the sender that they have to add @username in there sms , otherwise SMS will receive in SANDBOX, not user inbox.

Example for sender format

@test Ok I have received the sms” and send it to playSMS mobile number.
As showed in the image below …

14

Now the user test can goto My Account / Inbox and there he can see the received SMS.
As showed in the image below …

13

You can also setup SMS 2 EMAIL, SMS Forwarding to USER Mobile , etc etc , Its amazing that free open source tool can provide you this much Power of FREEDOM :)

 


 

9- Creating SMS base POLL system

You can create SMS poll system in playSMS, a kind of voting system as well so user can send sms to playSMS mobile number with his choice , and his entry will be made in the poll and will be visible via web page or likewise.

For example network operator wants to know how user feel about his network services. Follow this.

Goto Features / Manage Poll

Click on Add SMS poll

Now Add details, like

15 - Add Poll

.

Now Go back to MANAGE POLL , you will see Orange box on your newly created poll, which means its not activated yet, So simply click on the orange box to make it ACTIVE.

16

After Activation you will see something like below …

17

 

Casting VOTE to POLL

Now to cast vote, send SMS (with different choices multiple time for test) from user to playSMS number.

poll 1

19

 

Now to view POLL TEST result, goto Features / Manage POLL, there you will an EYE icon next to your POLL, click on it and you will be brought to POLL details.
As showed in the image below …

21

 


 

10- Creating COMMAND to be executed via SMS

You can create COMMAND base system and can execute script on the playSMS server, and it can reply you back with the result. For example If we want to inquire the UPTIME details via SMS.

  • Goto Features / Manage Command
  • Click on ADD SMS COMMAND
  • in SMS command keyword, add the catching word which playSMS will detect and consider it as COMMAND sms, and will run the command.
  • in SMS command exec, type the name of script (example status.sh) which will be executed , Make sure your scripts are in following folder

/var/lib/playsms/sms_command/1

  • Click on Make Return as Reply
  • Click on SAVE

As showed in the image below …

22

Now at playSMS server console , goto /var/lib/playsms/sms_command/1 and create simple script like.

  • touch status.sh
  • chmod + status.sh
  • nano status.sh
  • and add following command in it

uptime

Save & exit. And also run this command to verify if its working on console fine.

Now send sms to playSMS server like

run status.sh

and you will be replied back shortly from playSMS with the uptime status.
As showed in the image below …

23- command


11- Scheduling SMS to be send at specific time to person or group

playSMS have a very good feature to schedule SMS to be sent later or specific time, like a reminder too. It’s very useful for duffers like me who have week memory :D

To schedule a message,

Goto My Account / Schedule Message
and click on Add SMS Schedule

25- schdume msg

.

26- sch msgs msg

27- sch activate

First click on MANAGE (File Icon) and add the destination number and time

add-schuedl-etime

Click on SAVE and click on BACK, MAKE SURE TO click click on STATUS button (which is by default ORANGE means disabled, click it on to make GREEN, ACTIVE, This is important.

and here you can see the activity of playSMS in logs at that specific time.


- - 2015-05-11 09:04:59 PID554f7dbb44982 - L2 schedule_hook_playsmsd # sendsms uid:1 schedule_id:1 id:1 rule:0 schedule:[2014-05-11 09:06:00] scheduled:[2015-05-11 09:04:59]
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L2 sendsms # start uid:1 sender_id:[1234] smsc:[]
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L3 sendsms # maxlen:452 footerlen:7 footer:[ @admin] msglen:82 message:[Wife_Birthday, Don't forget to bring Gift or You will regret it for a long time :P]
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L2 sendsms_queue_create # saving queue_code:f2dd9833fb12f33283b424571d58c885 src:1234 scheduled:2015-05-11 09:04:59
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L2 sendsms_queue_create # saved queue_code:f2dd9833fb12f33283b424571d58c885 id:35
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L3 sendsms_manipulate_prefix # before prefix manipulation:[03333021909]
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L3 sendsms_manipulate_prefix # after prefix manipulation:[03333021909]
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L3 simplerate_hook_rate_getbyprefix # rate not found to:03333021909 default_rate:5
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:89 unicode: to:03333021909 enable_credit_unicode:0 count:1 rate:5 charge:5
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L2 sendsms # dst:1 sms_count:1 total_charges:5
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L2 sendsms_queue_push # saving queue_code:f2dd9833fb12f33283b424571d58c885 dst:03333021909
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L2 sendsms_queue_push # saved queue_code:f2dd9833fb12f33283b424571d58c885 smslog_id:29
- - 2015-05-11 09:04:59 PID554f7dbb44982 admin L2 sendsms # end queue_code:f2dd9833fb12f33283b424571d58c885 queue_count:1 sms_count:1 failed_queue:0 failed_sms:0
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsmsd # start processing queue_code:f2dd9833fb12f33283b424571d58c885 sms_count:1 scheduled:2015-05-11 09:04:59 uid:1 gpid:0 sender_id:1234
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsmsd # sending queue_code:f2dd9833fb12f33283b424571d58c885 smslog_id:29 to:03333021909 sms_count:1 counter:1
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 sendsms_intercept # msgtemplate modified sms_sender:[1234] sms_footer:[@admin] sms_to:[03333021909] sms_msg:[Wife_Birthday, Don't forget to bring Gift or You will regret it for a long time :P] uid:[1] gpid:[0] sms_type:[text] unicode:[0] queue_code:[f2dd9833fb12f33283b424571d58c885] smsc:[]
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 outgoing_hook_sendsms_intercept # no SMSC found uid:1 parent_uid:0 from:1234 to:03333021909
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsms_process # start
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 simplerate_hook_rate_getbyprefix # rate not found to:03333021909 default_rate:5
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:89 unicode:0 to:03333021909 enable_credit_unicode:0 count:1 rate:5 charge:5
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 simplerate__cansend # allowed user uid:1 sms_to:03333021909 credit:55500.000 count:1 rate:5 charge:5 balance:55495
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsms # saving smslog_id:29 u:1 g:0 gw:kannel smsc:kannel s:1234 d:03333021909 type:text unicode:0 status:0
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsms_process # saved smslog_id:29 id:29
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 sendsms # final smslog_id:29 gw:kannel smsc:kannel message:Wife_Birthday, Don't forget to bring Gift or You will regret it for a long time :P @admin len:90
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 kannel_hook_sendsms # enter smsc:kannel smslog_id:29 uid:1 to:03333021909
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 kannel_hook_sendsms # URL: http://localhost:13013/cgi-bin/sendsms?username=kannel&password=KANNEL_PASSWORD&from=1234&to=03333021909&dlr-mask=31&dlr-url=http%3A%2F%2Fclick.onmypc.net%3A1235%2Fplaysms%2Findex.php%3Fapp%3Dcall%26cat%3Dgateway%26plugin%3Dkannel%26access%3Ddlr%26type%3D%25d%26smslog_id%3D29%26uid%3D1&account=admin&text=Wife_Birthday%2C+Don%27t+forget+to+bring+Gift+or+You+will+regret+it+for+a+long+time+%3AP+%40admin
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 kannel__outgoing # smslog_id:29 response:0: Accepted for delivery
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 dlr # isdlrd:1 smslog_id:29 p_status:0 uid:1
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 kannel__outgoing # end smslog_id:29 p_status:0
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 simplerate__deduct # enter smslog_id:29
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 simplerate_hook_rate_getbyprefix # rate not found to:03333021909 default_rate:5
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:89 unicode:0 to:03333021909 enable_credit_unicode:0 count:1 rate:5 charge:5
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 credit_hook_rate_setusercredit # saving uid:1 balance:55495
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 credit_hook_rate_setusercredit # saved uid:1 balance:55495
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 simplerate__deduct # user uid:1 parent_uid: smslog_id:29 msglen:89 count:1 rate:5 charge:5 credit:55500.000 balance:55495
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 simplebilling__post # saving smslog_id:29 rate:5 credit:55500.000 count:1 charge:5
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 simplebilling__post # saved smslog_id:29 id:28
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 simplerate__deduct # deduct successful uid:1 parent_uid: smslog_id:29
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L3 simplerate__deduct # credit_lowest_limit:0 balance:55495 charge:5
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsms_process # end
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsmsd # result queue_code:f2dd9833fb12f33283b424571d58c885 to:03333021909 flag:1 smslog_id:29
- - 2015-05-11 09:05:00 PID55502a6c2d5bc - L2 sendsmsd # finish processing queue_code:f2dd9833fb12f33283b424571d58c885 uid:1 sender_id:1234 sms_count:1
- - 2015-05-11 09:05:00 PID554f7dbb4db5f - L3 dlrd # id:29 smslog_id:29 p_status:0 uid:1

 

 

and reminder will be sent precisely :)

wbd

 

 


12- Add SMS base QUIZ System

  1. To add QUIZ
  2. Goto Features, Manage Quiz
  3. Click on ADD SMS QUIZ, and follow screenshot.

quiz-1

Click on SAVE , and then click on BACK, again make sure you click on STATUS icon to make it active otherwise it will remain dead body.

Now send SMS with the keyword and answer like as showed in the image below …

quiz-3


 

I will write more later …

If this guide helps you in any way, don’t forget to give credit :~)

 

Regard’s
Syed Jahanzaib


Filed under: Linux Related

Sharing Ideas … Mikrotik with Kannel/playSMS

$
0
0

Just to share an old idea gathered in year 2008 …

Scenario:

Mikrotik is configured with User Manager.

playSMS with Kannel is already configured and working in separate box (Ubuntu)

 

Task:

  1. Renew expired users via sending Username and SCRATCH CODE to playSMS (Ubuntu Server)
  2. Renew expired users via sending SCRATCH CODE & verify the code with the user profile [later]

 

Requirements:

  1. Mikrotik with User Manager . SSH must be enabled  (with public key to enable linux ssh connectivity to mikrotik without Password)
    Follow this guide
    https://aacable.wordpress.com/2011/11/25/howto-login-on-remote-mikrotik-linux-without-password-to-execute-commands/
  2. Linux OS with USB GSM modem (Like Ubuntu or other with playSMS & Kannel configured)
    Follow this guide
    https://aacable.wordpress.com/2015/05/08/fun-with-sms-management-system-playsms/

 

Remember, I took User Manager as an example and uses some low and un secure scripting method. The goal was to show you the capabilities and things we can do by combining various apps and cross platform OS to get our results. This is no way a perfect example, but I am sure it will give you some idea how things can be started : )

You can take this example , and you can generate you scratch card codes and store it in MYSQL DB and FREERADIUS, therefore you can then pull CODE from specific DB and act accordingly after receiving SMS. I am sharing just some thoughts : )

 

 


 

1- Renew expired users via sending SMS to playSMS (Ubuntu Server)

This one is a very basic task. It does not involve any code to profile match check.
In this method user send sms with his Username and the scratch CODE. Once the server will receive the sms, it will first check the USERNAME at mikrotik, if it found valid username, it will then check the CODE in local text files (in this example I created 3 files, 512k.txt 1mb.txt and 4mb.txt , script will check all of three files (infact *.txt files) and if it found the CODE, it will then ssh to mikrotik and re-activate the user account with the given code profile. if the code belongs to 512k, it will re-activate user with 512k profile, and if the code is from 1mb pacakge, it will re-activate the account with 1mb profile.

SMS with following format

REN zaib 123

Explanation:

REN is a keyword which SMS server will catch and consider it as renew command.
zaib is user id
123 is password


 

 

Pseudo Code:

Server receive SMS with username and code

Server will SSH into mikrotik and look for username

If valid username found then it proceed further, otherwise issue error INVALID USERNAME and EXIT

If valid username found, then script will pick the second variable (code) and will look for this variable in /temp/*.txt , if it found the CODE then proceed further, otherwise issue error INVALID CARD NUMBER

If valid CODE is found in text files, then script will SSH to mikrotik and will re-activate the user account according to the package (which was fetched from the text file) and also print LOG in the window. You can also create other functions too like Remove the SCRATCH code once used, email admin or user, etc etc

Here is the example:

First create text files with the Scratch codes

example

cat /temp/512k.txt

123

cat /temp/1mb.txt

555

cat /temp/4mb.txt

999

Make Command on playSMS Server

As showed in the image below … or read my previous guide on howto make custom commands in playSMS

https://aacable.wordpress.com/2015/05/08/fun-with-sms-management-system-playsms/

playsms_command


 

 

Create SCRIPT on SMS Server which will be executed after receiving SMS

 

Create following SCRIPT on SMS Server.

cat /temp/test.sh


#!/bin/bash
#set -x

##########################################
# Script to renew User Manager account via received SMS
# Version 1.0b
########################################

# Strip user name and code because playsms will consider both variables as one, therefore we have to strip it in file
echo $1 > /tmp/user-card
USR=`cat /tmp/user-card | awk {' print $1 '}`
CARD=`cat /tmp/user-card | awk {' print $2 '}`

# Login to Mikrotik with SSH and look for validity of username

validuser=`ssh admin@101.11.11.255 :put [/tool user-manager user get value-name=actual-profile number=$USR]`

# If valid username found then proceed
if [ -n "$validuser" ]; then
echo -e "User name  - $1 - found with profile reported by Mikrotik = $validuser"

# Look for SCRATCH code, and if it found valid then proceed
# You can also create other functions too like Remove the SCRATCH code once it is used , IMPORTANT !
grep -r1 $CARD /temp/*.txt -q
if [ $? -eq 0 ]; then
grep -q -rl  $CARD /temp/*.txt  | sed 's/\///g' | sed 's/temp//g' |sed 's/\.//g' | sed 's/txt//g'
grep -rl $CARD /temp/*.txt | sed 's/\///g' | sed 's/temp//g' |sed 's/\.//g' | sed 's/txt//g' > /tmp/crd

VAR1=`cat /tmp/crd`
echo "Scratch CODE found in list = $VAR1"

# Login to mikrotik and re-activate or re-assign the profile to the user according to the package found in text files
ssh admin@101.11.11.255 :put [/tool user-manager user create-and-activate-profile user=$USR customer=admin profile=$VA$
ssh admin@101.11.11.255 [:log warning Account_REFREH_DONE_ID_IS_$USR]

# If card number is invalid, then issue error
else
/bin/echo "Invalid CARD Name!"
fi
else

# If username is invalid, then issue error
/bin/echo "Invalid User Name!"
fi

 


 

 

TESTING ….

Send an sms to the server with following code

ren zaib 123

As soon the server will receive the SMS with the word REN, it will start act as following …

playSMS LOG [focus on sms__command # command_output:]


127.0.0.1 localhost 2015-05-12 15:04:32 PID5551d030b76d8 - L2 kannel__call # start load:/var/www/playsms/plugin/gateway/kannel/geturl.php
127.0.0.1 localhost 2015-05-12 15:04:32 PID5551d030b76d8 - L3 kannel__incoming # addr:127.0.0.1 host:localhost t:2015-05-12 10:04:40 q:+923333021909 a:Ren zaib 123 Q:13013 smsc:[]
127.0.0.1 localhost 2015-05-12 15:04:32 PID5551d030b76d8 - L3 recvsms # isrecvsmsd:1 dt:2015-05-12 10:04:40 sender:+923333021909 m:Ren zaib 123 receiver:13013 smsc:
127.0.0.1 localhost 2015-05-12 15:04:32 PID5551d030b76d8 - L2 kannel__call # end load geturl


- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 recvsmsd # id:37 dt:2015-05-12 10:04:40 sender:+923333021909 m:Ren zaib 123 receiver:13013 smsc:
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 setsmsincomingaction # dt:2015-05-12 10:04:40 sender:+923333021909 m:Ren zaib 123 receiver:13013 smsc:
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 sms__command # command_exec:/var/lib/playsms/sms_command/1/test.sh 'zaib 123'
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 sms__command # command_output:User name  - zaib 123 - found with profile reported by Mikrotik = 1mb  Scratch CODE found in list = 1mb
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L2 sendsms # start uid:1 sender_id:[1234] smsc:[]
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 sendsms # maxlen:1676 footerlen:7 footer:[ @admin] msglen:102 message:[User name  - zaib 123 - found with profile reported by Mikrotik = 1mb Scratch CODE found in list = 1mb]
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L2 sendsms_queue_create # saving queue_code:0d756b8e3ac750e4a513bc76f2398489 src:1234 scheduled:2015-05-12 15:04:33
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L2 sendsms_queue_create # saved queue_code:0d756b8e3ac750e4a513bc76f2398489 id:30
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 sendsms_manipulate_prefix # before prefix manipulation:[+923333021909]
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 sendsms_manipulate_prefix # after prefix manipulation:[+923333021909]
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 simplerate_hook_rate_getbyprefix # rate not found to:+923333021909 default_rate:1
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:109 unicode:0 to:+923333021909 enable_credit_unicode:0 count:1 rate:1 charge:1
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L2 sendsms # dst:1 sms_count:1 total_charges:1
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L2 sendsms_queue_push # saving queue_code:0d756b8e3ac750e4a513bc76f2398489 dst:+923333021909
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L2 sendsms_queue_push # saved queue_code:0d756b8e3ac750e4a513bc76f2398489 smslog_id:30
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L2 sendsms # end queue_code:0d756b8e3ac750e4a513bc76f2398489 queue_count:1 sms_count:1 failed_queue:0 failed_sms:0
- - 2015-05-12 15:04:33 PID5551c430f1edc admin L3 setsmsincomingaction # feature:sms_command datetime:2015-05-12 10:04:40 sender:+923333021909 receiver:13013 keyword:REN message:zaib 123 raw:Ren zaib 123 smsc:
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsmsd # start processing queue_code:0d756b8e3ac750e4a513bc76f2398489 sms_count:1 scheduled:2015-05-12 15:04:33 uid:1 gpid:0 sender_id:1234
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsmsd # sending queue_code:0d756b8e3ac750e4a513bc76f2398489 smslog_id:30 to:+923333021909 sms_count:1 counter:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 sendsms_intercept # msgtemplate modified sms_sender:[1234] sms_footer:[@admin] sms_to:[+923333021909] sms_msg:[User name  - zaib 123 - found with profile reported by Mikrotik = 1mb Scratch CODE found in list = 1mb] uid:[1] gpid:[0] sms_type:[text] unicode:[0] queue_code:[0d756b8e3ac750e4a513bc76f2398489] smsc:[]
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 outgoing_hook_sendsms_intercept # no SMSC found uid:1 parent_uid:0 from:1234 to:+923333021909
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsms_process # start
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 simplerate_hook_rate_getbyprefix # rate not found to:+923333021909 default_rate:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:109 unicode:0 to:+923333021909 enable_credit_unicode:0 count:1 rate:1 charge:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 simplerate__cansend # allowed user uid:1 sms_to:+923333021909 credit:111111091.000 count:1 rate:1 charge:1 balance:111111090
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsms # saving smslog_id:30 u:1 g:0 gw:kannel smsc:kannel s:1234 d:+923333021909 type:text unicode:0 status:0
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsms_process # saved smslog_id:30 id:30
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 sendsms # final smslog_id:30 gw:kannel smsc:kannel message:User name  - zaib 123 - found with profile reported by Mikrotik = 1mb Scratch CODE found in list = 1mb @admin len:109
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 kannel_hook_sendsms # enter smsc:kannel smslog_id:30 uid:1 to:+923333021909
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 kannel_hook_sendsms # URL: http://localhost:13013/cgi-bin/sendsms?username=kannel&password=kannel&from=1234&to=%2B923333021909&dlr-mask=31&dlr-url=http%3A%2F%2F101.11.11.241%2Fplaysms%2Findex.php%3Fapp%3Dcall%26cat%3Dgateway%26plugin%3Dkannel%26access%3Ddlr%26type%3D%25d%26smslog_id%3D30%26uid%3D1&account=admin&text=User+name++-+zaib+123+-+found+with+profile+reported+by+Mikrotik+%3D+1mb%0AScratch+CODE+found+in+list+%3D+1mb+%40admin
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 kannel__outgoing # smslog_id:30 response:0: Accepted for delivery
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 dlr # isdlrd:1 smslog_id:30 p_status:0 uid:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 kannel__outgoing # end smslog_id:30 p_status:0
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 simplerate__deduct # enter smslog_id:30
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 simplerate_hook_rate_getbyprefix # rate not found to:+923333021909 default_rate:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:109 unicode:0 to:+923333021909 enable_credit_unicode:0 count:1 rate:1 charge:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 credit_hook_rate_setusercredit # saving uid:1 balance:111111090
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 credit_hook_rate_setusercredit # saved uid:1 balance:111111090
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 simplerate__deduct # user uid:1 parent_uid: smslog_id:30 msglen:109 count:1 rate:1 charge:1 credit:111111091.000 balance:111111090
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 simplebilling__post # saving smslog_id:30 rate:1 credit:111111091.000 count:1 charge:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 simplebilling__post # saved smslog_id:30 id:30
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 simplerate__deduct # deduct successful uid:1 parent_uid: smslog_id:30
- - 2015-05-12 15:04:34 PID5551d03283b74 - L3 simplerate__deduct # credit_lowest_limit:0 balance:111111090 charge:1
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsms_process # end
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsmsd # result queue_code:0d756b8e3ac750e4a513bc76f2398489 to:+923333021909 flag:1 smslog_id:30
- - 2015-05-12 15:04:34 PID5551d03283b74 - L2 sendsmsd # finish processing queue_code:0d756b8e3ac750e4a513bc76f2398489 uid:1 sender_id:1234 sms_count:1
- - 2015-05-12 15:04:35 PID5551c430ef414 - L3 dlrd # id:30 smslog_id:30 p_status:0 uid:1

 

& at Mikrotik LOG, You will see following

renewed


 

I w ill add more details and SMS Return reply screenshot later …

Regard’s
Syed Jahanzaib


Filed under: Mikrotik Related

Give your hardware some freedom of Speech ;)

$
0
0

MT-REPORT-SMS

playSMS_logo_full

kick


 CHANGE LOG:

  • 23-05-2015 – Added few functions in mt.sh to avoid SSH delay bug with mikrotik and to avoid false result

 

Recently I was working on a SMS reporting system to somehow receive some specific information for the Mikrotik health & Radius server information via sending an SMS and it should reply back the required information in some user friendly format. In the beginning it seemed fairly an easy task to accomplish by simply ssh (pass-wordless) to mikrotik and get the required info, BUT … executing the script from the terminal was working flawless, but executing this script from the playSMS was returning command_output EMPTY for ssh $variables. It took almost 15-16 hours wall banging efforts and finally I took another long route in order to achieve my task. You may find many other short routes to achieve this task, but I managed to get it working this way. Share your thoughts please.

TASK:

Send an sms with specific keyword to playSMS server, and it should then SSH to Mikrotik, and get some information (as described in the script) and send back that info (after making it user friendly) to the sender. so in short it’s a very good and handy way to get the server’s health report via sms Quickly ;)

Requirements:

This task is for people with some firm knowledge on Mikrotik and specially with Linux BASH scripting. But even if you are  a simple beginner, you can learn a lot from it. This is how you begin your journey by seeing far objects and then eventually reach to them by finding ways :) and that’s the exact way I started my astronomy journey as well :D

jupiter-first-modified-pic-24-3-2015

My First Picture of ‘Jupiter’ planet taken with 10″ manual Dobsonian with AFOCAL method, It’s an amazing experience when you see the planet from your Eyes Live !

 

 

1- Mikrotik with SSH/FTP services enabled (I changed the ports for security reasons)
2- Linux base System, I used my existing radius server for this purpose. It already have Kannel+playSMS configured with Dlink USB DWM-156 Modem. It can also ssh to mikrotik without password using per-configured public keys.

So you should read following guides before proceeding further.


 

Linux Section:

Here is the main script which will actually perform all the required actions and will gather information from mirkotik and radius itself.


#root@radius:/var/lib/playsms/sms_command/1# cat mt.sh

#!/bin/bash
# Script by Syed Jahanzaib / aacable@hotmail.com
# https://aacable.wordpress.com
# This script can inquire some specific Information from mikrotik and other server
# and send it back to sender via SMS on demand
# Version 2.0 -

MIKROTIK="192.168.1.2"
MTPORT="10001"
SERVER4="10.0.0.200"
SERVICE="radiusd"
DATE=`date`

# Check if Mikrotik is accessible or not, if not then EXIT immediately with error / zaib
if [[ $(ping -q -c 1 $MIKROTIK) == @(*100% packet loss*) ]]; then
echo "ALERT ..... MIKROTIK $MIKROTIK  is DOWN"
exit
else
echo "Galaxy Mikrotik Information SMS @ $DATE ..."
fi

# Execute Internetstatus script on mikrotik which will set the envrionment variable
ssh -q -p $MTPORT admin@$MIKROTIK /sys script run smsnetstatus > /tmp/pingresult

# Print PPP Active user in a file at Mikrotik
ssh -q -p $MTPORT admin@$MIKROTIK /ppp active print file=pppactive

# Print Internet Status Environment variables that we will use later
ssh admin@$MIKROTIK -p $MTPORT /sys script environment print file=netstatus

# Print Mikrotik Systems Resources in a file
ssh admin@$MIKROTIK -p $MTPORT /sys resource print file=resources

# Download pppactive file from mikrotik to local system in /tmp
scp -q -P $MTPORT admin@$MIKROTIK:pppactive.txt /tmp/pppactive.txt

# Verify if file is downloaded from mikrotik or not, if not dueo to ssh delay bug, then print error and exit :) Security Check by zaib
{
if [ ! -f /tmp/pppactive.txt ]; then
echo -e "ERROR: Mikrotik is live but it's SSH not accessible. Its a Mikrotik level BUG, You MUST upgrade with latest version. zaib"
exit 0
fi
}

# Download pppactive file from mikrotik to local system in /tmp
scp -q -P $MTPORT admin@$MIKROTIK:netstatus.txt /tmp/netstatus.txt

# Verify if file is downloaded from mikrotik or not, if not dueo to ssh delay bug, then print error and exit :) Security Check by zaib
{
if [ ! -f /tmp/netstatus.txt ]; then
echo -e "ERROR: Mikrotik is live but it's SSH not accessible. Its a Mikrotik level BUG, You MUST upgrade with latest version. zaib"
exit 0
fi
}

# Download Mikrotik System Resources file from mikrotik to local system in /tmp
scp -q -P $MTPORT admin@$MIKROTIK:resources.txt /tmp/resources.txt

# Verify if file is downloaded from mikrotik or not, if not dueo to ssh delay bug, then print error and exit :) Security Check by zaib
{
if [ ! -f /tmp/resources.txt ]; then
echo -e "ERROR: Mikrotik is live but it's SSH not accessible. Its a Mikrotik level BUG, You MUST upgrade with latest version. zaib"
exit 0
fi
}


# Print/Extract Uptime & CPU load only
cat /tmp/resources.txt  | awk 'NR==4' | sed -e 's/^[ \t]*//'
cat /tmp/resources.txt  | awk 'NR==11' | sed -e 's/^[ \t]*//'

# Extract Netstaus value from the csript we ran earlier on mt.
NETSTATUSVALUE=`grep "smsInternetStatus" /tmp/netstatus.txt | awk '{print $4}'`
echo "NET STATUS = $NETSTATUSVALUE"

# Print/Extract PPP Active Number of users
ACTIVE=`cat /tmp/pppactive.txt | wc -l`
echo "Active PPP users = $ACTIVE"

# Check RADIUS or whatever service PID status
pid=`pidof $SERVICE`
if [ "$pid" == "" ]; then
echo -e "$SERVICE service is NOT running, trying to start it ..."
service $SERVICE start
else
echo "$SERVICE = OK"
fi

# Check status of sharing media server
if [[ $(ping -q -c 1 $SERVER4) == @(*100% packet loss*) ]]; then
echo "ALERT ..... SERVER4 $SERVER4 is DOWN"
exit
else
echo "SERVER4 = OK"
fi
echo "Powered by Syed.Jahanzaib ..."

# Delete Files on Mikrotik so that false reproting may not occur / zaib
ssh -q -p $MTPORT admin@$MIKROTIK /file remove pppactive.txt
ssh -q -p $MTPORT admin@$MIKROTIK /file remove netstatus.txt
ssh -q -p $MTPORT admin@$MIKROTIK /file remove resources.txt

# delete files download from the local tmp folder in linux
rm -fr /tmp/netstatus.txt
rm -fr /tmp/pppactive.txt
rm -fr /tmp/resources.txt

exit 0

You should save this file mt.sh (or whatever name you decide) in following location

/var/lib/playsms/sms_command/1

 


Mikrotik Section

At mikrotik you should create and script which will actually check the internet status and update environment variable which we will fetch and use later via cat/awk.

Mikrotik Script name: smsnetstatus


# Modified few contents to suite local requirements and added descriptions
# Regard's / Syed Jahanzaib / https://aacable.wordpress.com

# Script Starts here...
# Internet Host to be checked You can modify them as per required, JZ
# We are using DOUBLE hosts to avoid FALSE REPORTING : ) / zaib

:local host1   "8.8.8.8"
:local host2   "192.0.78.13"

# Do not modify data below without proper understanding.
:local i 0;
:local F 0;
:local date;
:local time;
:global smsInternetStatus;
:global smsInternetLastChange;

# PING each host 5 times
:for i from=1 to=5 do={
if ([/ping $host1 count=1]=0) do={:set F ($F + 1)}
if ([/ping $host2 count=1]=0) do={:set F ($F + 1)}
:delay 1;
};

# If both links are down and all replies are timedout, then link is considered down
:if (($F=10)) do={
:if (($smsInternetStatus="UP")) do={
:log error "smsRESULT:  - WARNING : The INTERNET link seems to be DOWN. Please Check";
:set smsInternetStatus "DOWN";

:set date [/system clock get date];
:set time [/system clock get time];
:set smsInternetLastChange ($time . " " . $date);
} else={:set smsInternetStatus "DOWN";}
} else={

##      If reply is received , then consider the Link is UP
:if (($smsInternetStatus="DOWN")) do={
:log warning "smsRESULT: WARNING :The INTERNET link have been restored";
:set smsInternetStatus "UP";

##      MAKE SURE TO CHANGE PPPO-OUT1 TO MATCH YOUR WAN INTERFACE
:local currentIP
:local externalInterface "pppoe-out1"

# get the current IP address from the external interface
:set currentIP [/ip address get [find interface="$externalInterface"] address]
# Strip netmask
:for i from=( [:len $currentIP] - 1) to=0 step=-1 do={
:if ( [:pick $currentIP $i] = "/") do={
:set currentIP [:pick $currentIP 0 $i]

:log warning "smsRESULT: PTCL LINK RE - CONNECTED with new WAN IP = $currentIP, Please check and confirm / zaib"

}
}

:set date [/system clock get date];
:set time [/system clock get time];
:set smsInternetLastChange ($time . " " . $date);
} else={:set smsInternetStatus "UP";}
}

# Script Ends Here.
# Thank you

Done!


Now you should create an SMS COMMAND in playSMS as showed below …

sms-command-fro-mt-report


 

TESTING …

Now test by sending an sms with word “mikrotik” to the playsms server mobile number. and you will shortly receive the reply :) Allah Shuker

MT-REPORT-SMS


 

playSMS LOG

here is the playsms log when it will receive the SMS with word mikrotik

127.0.0.1 localhost 2015-05-22 11:40:59 PID555ecf7b2f24c - L2 kannel__call # start load:/var/www/playsms/plugin/gateway/kannel/geturl.php
127.0.0.1 localhost 2015-05-22 11:40:59 PID555ecf7b2f24c - L3 kannel__incoming # addr:127.0.0.1 host:localhost t:2015-05-22 06:42:03 q:+923333021909 a:Mikrotik Q:13013 smsc:[]
127.0.0.1 localhost 2015-05-22 11:40:59 PID555ecf7b2f24c - L3 recvsms # isrecvsmsd:1 dt:2015-05-22 06:42:03 sender:+923333021909 m:Mikrotik receiver:13013 smsc:
127.0.0.1 localhost 2015-05-22 11:40:59 PID555ecf7b2f24c - L2 kannel__call # end load geturl
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 recvsmsd # id:195 dt:2015-05-22 06:42:03 sender:+923333021909 m:Mikrotik receiver:13013 smsc:
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 setsmsincomingaction # dt:2015-05-22 06:42:03 sender:+923333021909 m:Mikrotik receiver:13013 smsc:
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 sms__command # command_exec:/var/lib/playsms/sms_command/1/mt.sh
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 sms__command # command_output:Galaxy Mikrotik Information SMS @ Fri May 22 11:41:00 PKT 2015 ... uptime: 17h54m55s cpu-load: 13% NET STATUS = UP Active PPP users = 295 radiusd = OK SERVER4 = OK Powered by Syed.Jahanzaib ...
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L2 sendsms # start uid:1 sender_id:[1234] smsc:[]
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 sendsms # maxlen:15140 footerlen:7 footer:[ @admin] msglen:193 message:[Galaxy Mikrotik Information SMS @ Fri May 22 11:41:00 PKT 2015 ... uptime: 17h54m55s cpu-load: 13% NET STATUS = UP Active PPP users = 295 radiusd = OK SERVER4 = OK Powered by Syed.Jahanzaib ...]
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L2 sendsms_queue_create # saving queue_code:60c45bad522ae25332bf3b37c33ea19f src:1234 scheduled:2015-05-22 11:41:00
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L2 sendsms_queue_create # saved queue_code:60c45bad522ae25332bf3b37c33ea19f id:163
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 sendsms_manipulate_prefix # before prefix manipulation:[+923333021909]
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 sendsms_manipulate_prefix # after prefix manipulation:[+923333021909]
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 simplerate_hook_rate_getbyprefix # rate not found to:+923333021909 default_rate:1
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:200 unicode:0 to:+923333021909 enable_credit_unicode:0 count:2 rate:1 charge:2
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L2 sendsms # dst:1 sms_count:2 total_charges:2
- - 2015-05-22 11:41:00 PID555ebd2ae9681 admin L2 sendsms_queue_push # saving queue_code:60c45bad522ae25332bf3b37c33ea19f dst:+923333021909
- - 2015-05-22 11:41:01 PID555ebd2ae9681 admin L2 sendsms_queue_push # saved queue_code:60c45bad522ae25332bf3b37c33ea19f smslog_id:157
- - 2015-05-22 11:41:01 PID555ebd2ae9681 admin L2 sendsms # end queue_code:60c45bad522ae25332bf3b37c33ea19f queue_count:1 sms_count:2 failed_queue:0 failed_sms:0
- - 2015-05-22 11:41:01 PID555ebd2ae9681 admin L3 setsmsincomingaction # feature:sms_command datetime:2015-05-22 06:42:03 sender:+923333021909 receiver:13013 keyword:MIKROTIK message: raw:Mikrotik smsc:
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 sendsmsd # start processing queue_code:60c45bad522ae25332bf3b37c33ea19f sms_count:2 scheduled:2015-05-22 11:41:00 uid:1 gpid:0 sender_id:1234
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 sendsmsd # sending queue_code:60c45bad522ae25332bf3b37c33ea19f smslog_id:157 to:+923333021909 sms_count:2 counter:1
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 sendsms_intercept # msgtemplate modified sms_sender:[1234] sms_footer:[@admin] sms_to:[+923333021909] sms_msg:[Galaxy Mikrotik Information SMS @ Fri May 22 11:41:00 PKT 2015 ... uptime: 17h54m55s cpu-load: 13% NET STATUS = UP Active PPP users = 295 radiusd = OK SERVER4 = OK Powered by Syed.Jahanzaib ...] uid:[1] gpid:[0] sms_type:[text] unicode:[0] queue_code:[60c45bad522ae25332bf3b37c33ea19f] smsc:[]
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 outgoing_hook_sendsms_intercept # no SMSC found uid:1 parent_uid:0 from:1234 to:+923333021909
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 sendsms_process # start
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 simplerate_hook_rate_getbyprefix # rate not found to:+923333021909 default_rate:1
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:200 unicode:0 to:+923333021909 enable_credit_unicode:0 count:2 rate:1 charge:2
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 simplerate__cansend # allowed user uid:1 sms_to:+923333021909 credit:55324.000 count:2 rate:1 charge:2 balance:55322
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 sendsms # saving smslog_id:157 u:1 g:0 gw:kannel smsc:kannel s:1234 d:+923333021909 type:text unicode:0 status:0
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 sendsms_process # saved smslog_id:157 id:157
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 sendsms # final smslog_id:157 gw:kannel smsc:kannel message:Galaxy Mikrotik Information SMS @ Fri May 22 11:41:00 PKT 2015 ... uptime: 17h54m55s cpu-load: 13% NET STATUS = UP Active PPP users = 295 radiusd = OK SERVER4 = OK Powered by Syed.Jahanzaib ... @admin len:200
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 kannel_hook_sendsms # enter smsc:kannel smslog_id:157 uid:1 to:+923333021909
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 kannel_hook_sendsms # URL: http://localhost:13013/cgi-bin/sendsms?username=kannel&password=KANNELPASSWORD&from=1234&to=%2B923333021909&dlr-mask=31&dlr-url=http%3A%2F%2Fclick.onmypc.net%3A1235%2Fplaysms%2Findex.php%3Fapp%3Dcall%26cat%3Dgateway%26plugin%3Dkannel%26access%3Ddlr%26type%3D%25d%26smslog_id%3D157%26uid%3D1&account=admin&text=Galaxy+Mikrotik+Information+SMS+%40+Fri+May+22+11%3A41%3A00+PKT+2015+...%0Auptime%3A+17h54m55s%0Acpu-load%3A+13%25%0ANET+STATUS+%3D+UP%0AActive+PPP+users+%3D+295%0Aradiusd+%3D+OK%0ASERVER4+%3D+OK%0APowered+by+Syed.Jahanzaib+...+%40admin
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 kannel__outgoing # smslog_id:157 response:0: Accepted for delivery
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 dlr # isdlrd:1 smslog_id:157 p_status:0 uid:1
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 kannel__outgoing # end smslog_id:157 p_status:0
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 simplerate__deduct # enter smslog_id:157
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 simplerate_hook_rate_getbyprefix # rate not found to:+923333021909 default_rate:1
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L3 simplerate_hook_rate_getcharges # uid:1 u:admin len:200 unicode:0 to:+923333021909 enable_credit_unicode:0 count:2 rate:1 charge:2
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 credit_hook_rate_setusercredit # saving uid:1 balance:55322
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 credit_hook_rate_setusercredit # saved uid:1 balance:55322
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 simplerate__deduct # user uid:1 parent_uid: smslog_id:157 msglen:200 count:2 rate:1 charge:2 credit:55324.000 balance:55322
- - 2015-05-22 11:41:01 PID555ecf7da2f5f - L2 simplebilling__post # saving smslog_id:157 rate:1 credit:55324.000 count:2 charge:2
- - 2015-05-22 11:41:02 PID555ecf7da2f5f - L2 simplebilling__post # saved smslog_id:157 id:156
- - 2015-05-22 11:41:02 PID555ecf7da2f5f - L3 simplerate__deduct # deduct successful uid:1 parent_uid: smslog_id:157
- - 2015-05-22 11:41:02 PID555ecf7da2f5f - L3 simplerate__deduct # credit_lowest_limit:0 balance:55322 charge:2
- - 2015-05-22 11:41:02 PID555ecf7da2f5f - L2 sendsms_process # end
- - 2015-05-22 11:41:02 PID555ecf7da2f5f - L2 sendsmsd # result queue_code:60c45bad522ae25332bf3b37c33ea19f to:+923333021909 flag:1 smslog_id:157
- - 2015-05-22 11:41:02 PID555ecf7da2f5f - L2 sendsmsd # finish processing queue_code:60c45bad522ae25332bf3b37c33ea19f uid:1 sender_id:1234 sms_count:2
- - 2015-05-22 11:41:02 PID555ebd2ae3e02 - L3 dlrd # id:157 smslog_id:157 p_status:0 uid:1


 

Regard’s
Syed Jahanzaib

 


Filed under: Linux Related, Mikrotik Related

Sharing Ideas … Renew Expired User Account via SMS in DMASOFTLAB Radius Manager

$
0
0

EXPANDING POSSIBILITIES

DMASOFTLAB RADIUS MANAGER ACCOUNT RENEWAL VIA SMS USING REFILL CARD

RENEWED


 

Sharing another theory which can actually work and can be modified to perform about any function which is accessible by web panel in DMASOFTLAB Radius Manager.

Do remember that this is just an lab test scripts , in reality radius manager do add few other info in different tables and places. RM recharge method is somewhat quite different then other billing systems. For the demonstration purpose only, I selected an short route by bypassing all extra codes and just added 30 days in the user account via script .

These are just my own thoughts in old days. Lot of improvement can be made in this regard but all of these things requires dedicated time :) Hope you understand.


 

1- RADIUS SECTION TO CREATE REFILL CARDS:

Create REFILL cards so that we can use it to refill our expired account.
As showed in the image below …

1- list cards


 

2- SCRIPT SECTION

#!/bin/bash
SQLUSER="root"
SQLPASS="sqlpassword"
echo $1  > /tmp/user-card
USR=`cat /tmp/user-card | awk {' print $1 '}`
CARD=`cat /tmp/user-card | awk {' print $2 '}`

#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!"
else

# 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!"
else

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

#LOOK FOR SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`

#LOOK FOR Card Unit value via CLI
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'`

# 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

# IF CARD PRICE VALUE IS EQUAL TO SERVICE PRICE VALUE THEN
if [ $CARDPRICE -eq $SRVPRICE ]
then
echo "Card number is valid and equal to service price.  REFRESHING ..."
NEXT_EXPIRE_DATE=$(date +"%Y-%m-%d" -d "+30 days")
# ADD 30 DAYS VALUE TO EXPIRED USER ACCOUNT
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET expiration = '$NEXT_EXPIRE_DATE' 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';"
echo -e "Done/Note: Card Number $CARD  is marked as used in DB to prevent re-usege"

# IF CARD PRICE VALUE IS EQUAL TO SERVICE PRICE VALUE THEN
elif [ $CARDPRICE -gt $SRVPRICE ]
then
echo -e "Card Price is Greater to service price.  REFRESHING ..."
NEXT_EXPIRE_DATE=$(date +"%Y-%m-%d" -d "+30 days")
# ADD 30 DAYS VALUE TO EXPIRED USER ACCOUNT
mysql -u$SQLUSER -p$SQLPASS -e "use radius; UPDATE rm_users SET expiration = '$NEXT_EXPIRE_DATE' 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';"
echo -e "Done/Note: Card Number $CARD  is marked as used in DB to prevent re-usge"
# IF CARD VALUE IS LESS THEN CURRENT PACKAGE PRICE THEN PRINT ERROR AND GOTO END
elif [ $CARDPRICE -lt $SRVPRICE ]
then
echo -e "ERROR: CARD PRICE IS NOT SUFFICIENT TO REFRESH $PKGNAME SERVICE"
echo -e "Done/Note: Card Number $CARD is marked as used in DB to prevent re-usege"

fi
fi
fi

 

3- playSMS COMMAND SECTION

Create command in playSMS
As showed in the image below ..

renew-command


 

4- TESTING RENEWAL VIA SENDING SMS

Send sms to the server (playSMS) with following format

renew test 12345

renew = is the keyword that playSMS will catch and will execute the renew.sh
test = is the user name
12345 = REFILL card number/code

and if all conditions matched like user name and card number valid, then it will execture the rest of script and will add 30 days expiry limit to the account (so if the account is expired it will be re-activated)

RENEWED

 

if code is wrong it will send error

wrongcode

and if user is invalid, it will let you know as well.

wronguser

You can also see its entry in SYSLOG and user properties comments section as well.

syslog


 

Lot’s of possibilities here. You can add more details in the script to do more Logging , send alerts etc etc .

All depend on your capabilities and passion towards achieving the Goal !

If time will allow, I will add more details Insha Allah !

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

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

$
0
0

userinfo


1- TASK

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

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

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

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

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

root@radius:/var/lib/playsms/sms_command/1# cat userinfo.sh

#!/bin/bash
# Script to check Radius Manager Status , Expiry Date, Service Plan, Data Used
# Syed Jahanzaib
# aacable @ hotmail.com
# https://aacable.wordpress.com
# Modified on 26 / 05 / 2015
SQLUSER="root"
SQLPASS="sqlpass"
echo

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

# Check ACCOUNT EXPIRY Status and act accordingly

TODAY=$(date +"%Y-%m-%d")
TODAYDIGIT=`echo $TODAY  | sed -e 's/-//g'`
SRVEXPIRYFULL=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2'`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT expiration FROM radius.rm_users WHERE username = '$1';" |awk 'FNR == 2' | sed 's/00:.*//' | sed -e 's/-//g'`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = '$1';"  |awk 'FNR == 2 {print $1,$2}'`

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

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

else
        echo "Account STATUS= OK! It will expire on $SRVEXPIRYFULL !  Last LOGOFF date was $LOGOFFDATE"

###############

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

#Get Accounting Data
DOWNDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(acctoutputoctets), SUM(acctinputoctets), SUM(acctsessiontime), MAX(acctstoptime) FROM radacct WHERE username = '$1';"  |awk 'FNR == 2 {print $1}'`
UPDATA=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT SUM(acctoutputoctets), SUM(acctinputoctets), SUM(acctsessiontime), MAX(acctstoptime) FROM radacct WHERE username = '$1';" |awk 'FNR == 2 {print $2}'`
TOTCOMBINED=`echo "($DOWNDATA+$UPDATA)/(1024)/(1024)" |bc`
SRVLIMITMB=`echo "($SRVLIMIT)/(1024)/(1024)" |bc`
DOWNDATAUSED=`echo "($DOWNDATA)/(1024)/(1024)" |bc`
UPDATAUP=`echo "($UPDATA)/(1024)/(1024)" |bc`
CURRENCY="PKR"

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

#Print SPECIFIC Service PRICE value via CLI
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;" |awk 'FNR == 2 {print $1}' | cut -f1 -d"."`

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

# Account 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}';`

##################
# Finally ECHO all the DATA to be print on screen or sent via SMS (I used playSMS and kannel)
##################
echo -e "Account Registed to = $USERFLNAME"
echo -e "User Package  = $PKGNAME"
echo -e "Service Price = $SRVPRICE $CURRENCY"
echo -e "Expiration Date: $EXPIRY"
echo -e "Service Quota Limit = $SRVLIMITMB MB"
echo -e "Data Used = $TOTCOMBINED - MB"
echo -e "Downloaded Data = $DOWNDATAUSED - MB"
echo -e "Uploaded Data = $UPDATAUP - MB"
fi
fi

# THE END ! GOTO HOME

2- playSMS SECTION

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

userinfo-playsms-=command


 3- TEST PHASE

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

Both methods results are as follows …

 

by CLI

userinfo-cli

by SMS

userinfo

Regard’s
SYED JAHANZAIB


Filed under: Linux Related, Radius Manager

Modem Status and SIM Balance check with Mail Alert

$
0
0

dlink


 

Task:

Requirement of daily reporting for the Modem status and SIM balance via email.
In this example I had DLINK DWM-156 USB Modem attached with Linux base system [Ubuntu 12.4].
This system had kannel/playsms installed which sends sms alerts for various events and can trigger different scripts upon receiving SMS with specific codes or instructions. I found that this modem was cheap and had many issues like not responding or likewsise, so I created this script which runs few times a day and sends email alerts for any issue related to modem and sim balance. on internet there might be some better guides or methods to do the same task, but this one suites my custom need. at a moment its on a very basic level, later we will modify it if required further :)
Sharing this script, maybe some one will get benefit from it or improve it on a pro level.


 

Requirement:

GAMMU must be installed and must be configured with the modem. you should run gammu –identify to make sure its detecting  the modem.

 


 

Bash Script to do the job:

######################
cat /temp/checkbal.sh
######################

#!/bin/bash
# Script to check Modem status and SIM balance via GAMMU and send email alerts accordingly.
# Syed Jahanzaib / aacable @ hotmail.com
# http//aacable.wordpress.com
# Version 1.0 / Modified on 28-5-2015

## START
# Check for temporary files that might be created by earlier, upto you : )
echo -e "Checking for old garbage files created earlier tby this script"
#[ -f /tmp/modeminfo ] && rm -f /tmp/modeminfo > /dev/null
#[ -f /tmp/mobilebal ] && rm -f /tmp/mobilebal > /dev/null

# Identify MODEM and output its result in tmp file
echo -e "Checking MODEM status"
gammu --identify > /tmp/modeminfo

# Look for Modem string , if not found give error and exit. MTK1 is my dlink modem string, you should change it with your modem string
A=`grep MTK1 "/tmp/modeminfo"`
if [ "$A" == "" ]; then
echo -e "Modem NOT Responding. Now scheduling USBRESET.SH file which will RESET the USB device & then re-run this script again"
echo -e "Modem NOT Responding. Now scheduling USBRESET.SH file which will RESET the USB device & then re-run this script again" > /tmp/mail.txt
# Email the 'modem not responding' result to ADMIN
mail -s 'Galaxy USB Modem NOT responding' aacable-hotmail-com < /tmp/mail.txt

# Running usb reset SCRIPT ,upto you, i made this usbreset.sh which reset the USB device and the modem start working again if its in HANG position, works for me
# /temp/resetusb.sh

#Scheduling current script to run after one minute again to see if modem is detectable after reset.
#echo /temp/checkbal.sh | at now + 1 min
else

# If modem found, then execute USSD code to inquire Mobile SIM Balance in tmp file, in this case I am using ZONG mobile sim
echo -e "Modem seems to be responding OK"
echo -e "================================="
echo -e "Now executing ZONG USSD code via GAMMU to inquire balance "
gammu --getussd *222# > /tmp/mobilebal

# Look for word insufficient in above output file, if not found then all ok.
B=`grep insufficient "/tmp/mobilebal"`
if [ "$B" == "" ]
then
# Print Mobile Balance, modify it accordingly
BAL=`cat /tmp/mobilebal |awk 'FNR == 3 {print $5}' `
echo -e "Balance & Modem both OK, Alhamdolillah"
echo -e "Balance & Modem both OK, Alhamdolillah" > /tmp/mail.txt
echo -e "Balance is $BAL PKR"
echo -e "Balance is $BAL PKR" >> /tmp/mail.txt
mail -s 'Daily Report: Galaxy USB Modem & SIM Balance is OK' aacable-hotmail-com < /tmp/mail.txt

# ELSE print modem and sim status
else
echo -e "Modem Responding but SIM have not enough balance"
echo -e "Modem Responding but SIM have not enough balance" > /tmp/mail.txt
mail -s 'Daily Report: Galaxy USB Modem OK BUT SIM have no Balance' aacable-hotmail-com < /tmp/mail.txt

fi
fi


Result:

CLI result:

Modem responding, but SIM have no balance

 

modem-not-balance

 

Modem responding, & SIM also have enough balance

report3-cli

 

Email Result:

 

MODEM-BAL-OK

Report1

 

 

 


 

Its just rough notes, you must modify things according to your network and requirements.

Regard’s
Syed Jahanzaib


Filed under: Linux Related

Mikrotik with Cisco VLAN made easy

$
0
0
kick1


vlan
~!~ Mikrotik with Cisco VLAN made easy ~!~
 ~!~ For Beginners ~!~

Virtual LANs (VLANs) are a solution to allow you to separate users into individual network segments for security and other reasons. VLAN membership can be configured through software instead of physically relocating devices or connections. VLANs allow you to break up devices on your network regardless of their location.

The main advantage of VLAN are

  • Broadcast Control
  • Security / Client Isolation
  • DMZ
  • Controlled Network Management
  • Costing

It is very useful for any network including large/small offices, ISP’s, Cable.Internet services providers etc. The main problem of any large network is broadcast and specially for network operators when any single user swap his wan router LAN cable to wan cable thus broadcast his router DHCP to operator network, or single user effected with virus/trojans broadcast to whole network. VLAN can help you in many situations like these or others.


 

TASK:

To avoid broadcasting/flooding and above all for better better management +security and monitoring, we want to break the network in smaller segments.

Scenario:

Consider the following scenario

We have Mikrotik Router which is acting as a DHCP and PPPoE Server as well. and we want to isolate the different network areas by breaking them in smaller segments. Each area will get different IP series from the mikrotik dhcp server.

In this example following ports are used for

  • Mikrotik = Port 1 [as TRUNK port]
  • Dealer-1 = Port 2
  • Dealer-2 = Port 3
  • Dealer-3 = Port 4

Hardware Used in this Guide:

  1. Mikrotik RB2011
  2. Cisco 3750-E Series
  3. Two Laptops for testing

As showed in the image below …

2015-06-02 15.16.32


 

MIKROTIK CONFIG

# Create VLAN Interfaces and provide them name and VLAN#ID
/interface vlan
add interface=LAN l2mtu=1594 name=DEALER-1 vlan-id=10
add interface=LAN l2mtu=1594 name=DEALER-2 vlan-id=20
add interface=LAN l2mtu=1594 name=DEALER-3 vlan-id=30

# Assign IP addresses to the interfaces
/ip address
add address=192.168.1.1/24 interface=LAN network=192.168.1.0
add address=192.168.10.1/24 interface=DEALER-1 network=192.168.10.0
add address=192.168.20.1/24 interface=DEALER-2 network=192.168.20.0
add address=192.168.30.1/24 interface=DEALER-3 network=192.168.30.0

# Create DHCP Server and assign different Pools for the dealers
# You can DHCP wizard as well if CLI is a bit hectic
/ip dhcp-server
add address-pool=DEALER-1-POOL disabled=no interface=DEALER-1 lease-time=6h name=dhcp1
add address-pool=DEALER-2-POOL disabled=no interface=DEALER-2 lease-time=6h name=dhcp2
add address-pool=DEALER-3-POOL disabled=no interface=DEALER-3 lease-time=6h name=dhcp3

/ip dhcp-server network
add address=192.168.10.0/24 dns-server=192.168.10.1 gateway=192.168.10.1
add address=192.168.20.0/24 dns-server=192.168.20.1 gateway=192.168.20.1
add address=192.168.30.0/24 dns-server=192.168.30.1 gateway=192.168.30.1

Some screenshots for the reference purpose …

mt

 

Done. Now we have to create VLANs at CISCO Switch…



CISCO VLAN CONFIGURATION

I assume that you have Cisco switch with any IP address for the management purposes.

Telnet to the switch

telnet 192.168.0.1

# Enter your Cisco switch password
User Access Verification
Password: xxxxxx

# Switch to change mode
enable
Password: xxxxxxxxx

# Enter in Config mode
config t

# Select Port number which will be connected with the Mikrotik and change encapsulation method

interface gigabitEthernet 1/0/1
switchport trunk encapsulation dot1q
switchport mode trunk

switchport trunk allowed vlan all
switchport nonegotiate

#Create VLAN id and name for dealers/areas
vlan 10
name DEALER-1
vlan 20
name DEALER-2
vlan 30
name DEALER-3
exit

# Now Select Dealer1 interface , like port 2 and assign it with the vlan id

interface gigabitEthernet 1/0/2
# OR RANGE like interface range gigabitEthernet 1/0/1-4 (Port Range 1 to 4)
switchport mode access
switchport access vlan 10

interface gigabitEthernet 1/0/3
switchport mode access
switchport access vlan 20

interface gigabitEthernet 1/0/4
switchport mode access
switchport access vlan 30

exit
exit

# SAVE the configuration you just made above
wr

Some screenshots for reference…

1

 

3-vlan ports

 

2-VLAN

Done!

 


TEST!

Now connect your PC with the port 2 and port3 , 4

You will get different IP in each port.
As showed in the image below from mikrotik dhcp server’s

dhcp-dealers

 

Test From Dealer-1 System

dealer-1

Dealer-1 have receive 192.168.10.x series ip, exactly the one we configured in mikrotik.

Now try to ping any dealer-2 series and to the internet as well. You will see that you will be able to ping the internet and mikrotik LAN ip, but not with dealer-2 subnet or likewise.

ping result

NOTE: For the client isolation / to block communication between all VLAN’s , you must create FILTER rule as explained in TIP’s n TRICK section below …


TIP’S n TRICKS

 

1- Block communication between all or specific VLAN Subnet

It is usually required to block all communication between specific or all VLAN subnets for security or other reasons. By default mikrotik will allow communications between all vlan. You can block them by creating FILTER rules. Example is we want that users of all vlans can access internet via WAN interface but should not be able to communicate with any other VLAN subnet. use following as an example

Note: there are many other ways to achieve this either at switch level or mikrotik, i am showing just an example only here.


/ip firewall filter
add chain=forward comment="Accept traffic from VLAN subnets to WAN" out-interface=WAN

add action=reject chain=forward comment="Block Communication between all vlan subnets" reject-with=icmp-net-prohibited src-address=\
192.168.0.1-192.168.255.255

# Masquerade rule to allow internet , wan link interface
/ip firewall nat
add action=masquerade chain=srcnat out-interface=WAN


 

Pending work:

– Add pppoe or hotspot configuration
– Firewall configuration for isolation in pppoe/hotpost
– Few more tips n tricks with VLAN

 

Regard’s
Syed Jahanzaib


Filed under: Cisco Related, Mikrotik Related

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

$
0
0

Whatis Gnuplot:

As defined the Wikipedia. …

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

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

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

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

Requirements for this script:

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

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

What this script will do ?

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

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

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


 

To install Gnuplot on Ubuntu , issue following command

apt-get install -y gnuplot

Now create bash script as follows

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

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

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

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

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

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

# Fetch Accounting Data from MYSQL Freeradius radius DB, by using current Year/Month using username provide with the script , and output to file
mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST -e "use radius; SELECT SQL_CALC_FOUND_ROWS date, SUM(allbytesdl) - COALESCE(SUM(specbytesdl), 0), SUM(allbytesul) - COALESCE(SUM(specbytesul), 0), SUM(alltime) - COALESCE(SUM(spectime), 0)
FROM (  SELECT LEFT(radacct.acctstarttime, 10) AS date,  acctoutputoctets AS allbytesdl, SUM(dlbytes) AS specbytesdl,  acctinputoctets AS allbytesul, SUM(ulbytes) AS specbytesul,
radacct.acctsessiontime AS alltime, SUM(rm_radacct.acctsessiontime) AS spectime  FROM radacct  LEFT JOIN rm_radacct ON rm_radacct.radacctid = radacct.radacctid
WHERE LEFT(radacct.acctstarttime, 7) LIKE '$CYEAR-$CMONTH%' AND radacct.username LIKE '$1' AND  FramedIPAddress LIKE '%' AND CallingStationId LIKE '%'   GROUP BY radacct.radacctid
) AS tmp GROUP BY date LIMIT 0, 50;" |awk '{print $1,$2,$3}' > $TMP
sed '1d' -i $TMP

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

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

EOF
# GNUPLOT Script ends here
# Thank you : )

 

Running the SCRIPT

Now execute the script by

/temp/usergraph.sh USERNAME

(like usergraph.sh zaib)

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

http://yourip/radius.jpg

gnuplot


That’s it …

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

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

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

You should give it a try :)


 

 

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

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

$
0
0

 

 

sms-alert

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

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


 

Requirements:

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

 

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

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

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

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

I will add some more details later.

Happy Alerting !

Syed Jahanzaib


Create SMS Script

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

Now paste the following script

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

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

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

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

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

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

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

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

done

 

OUTPUT:

[Just echoing in this example]

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

 

sms-alert-list


 

Schedule to run it DAILY

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

Example of scheduled job bycrontabcommand:

crontab -l

@daily /temp/sms.sh

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

Jz!

 


Filed under: Linux Related, Radius Manager

Sending Email on Router Reboot with Logs and LASTSEEN time !

$
0
0

email


 

Task:

To send email when the router reboots because of any power or other issue, the email should include the time of router failure and its restore time in the email subject, [for quick viewing] . Also it should include last few logs entries in the email body for diagnostic purposes.

Disclaimer: Main script was taken from Mikrotik WIKI
http://wiki.mikrotik.com/wiki/Send_email_about_reboot , and later I modified it to meet local requirement. Also I created second script which keep updates of time in a file to track the time when router got lost,

Following are two scripts which does the following

Script#1 – Update-last-seen-time-on-each-minute
This script will update date+time in a local file called lastseen.txt so that even if a router reboot, the time preserves in this file to print the lastseen time in email or where ever required.

Script#2 – email-on-reboot
This script will run after router reboot/restarts. It will first disable the script-1 schedule to prevent overwritten of lastseen time in the file lastseen.txt, then it will fetch the data from this file and will also get current time and send email with last 60 Seconds logs in the email body.

Script#2 is taken from WIKI and modified it as per my requirement. (to display Last seen time as well in the email so that I don’t have to go through whole logs in search of —–)

Exported Version of both scripts. for copy/pasting, donot go blindly, read them before deploying


####################################
#1st Script: update-last-seen-time-on-each-minute
####################################

/system script
add name=email-on-reboot policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api source="# Disable LASTSEEN script schduler to prevent overwritten of time\"\r\
\n:log error \"Disabling Lastseen Update Time Scheudle to preserve Last REBOOT time\"\r\
\n/sys scheduler disable update-last-seen-time-on-each-minute\r\
\n\r\
\n:delay 30s\r\
\n:global gmailsmtp\r\
\n:set gmailsmtp [:resolve \"smtp.gmail.com\"];\r\
\n\r\
\n# Set your GMAIL Account Password\r\
\n:local gmailpass\r\
\n:set gmailpass GMASILPASS\r\
\n\r\
\n# Set your email where you want to receieve the alert \r\
\n:local mailsendto\r\
\n:set mailsendto aacable@hotmail.com\r\
\n\r\
\n# Wait for NTP Time Synchronization to pritn current timestamp in mail subject, NTP is required in RB's \r\
\n:while ( [/system ntp client get status]!=\"synchronized\" ) do={ :delay 1s }\r\
\n\r\
\n# Set Email Subject\r\
\n:local es \"\$[/system identity get name] got LOST at \$[/file get lastseen.txt contents] & back online at \$[/system clock get date] \$[/system clock get time]\"\r\
\n\r\
\n# Load Last LOGS Entries of 60 seconds\r\
\n:delay 60s\r\
\n:local eb \"Mikrotik Log contents (with 60 seconds delay):\\r\\n\"\r\
\n:foreach le in=[/log print as-value] do={\r\
\n  :set eb (\$eb.[:tostr [(\$le->\"time\")]].\" \".[:tostr [(\$le->\"topics\")]].\": \".[:tostr [(\$le->\"message\")]].\"\\r\\n\")\r\
\n}\r\
\n\r\
\n# Finally send email \r\
\n/tool e-mail send to=\$mailsendto subject=\$es body=\$eb server=\$gmailsmtp tls=yes password=\$gmailpass\r\
\ndelay 5s\r\
\n\r\
\n# Enable back the update time schdule for lastseen value \r\
\n:log warning \"Email Done! Enabling Lastseen Update Time Scheudle ...\"\r\
\n/sys scheduler enable update-last-seen-time-on-each-minute\r\
\n\r\
\n# Syed Jahanzaib\r\
\n# aacable [at] hotmail.com"

####################################
#2nd Script: update-last-seen-time-on-each-minute
####################################

add name=update-last-seen-time-on-each-minute policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api source=":local date;\r\
\n:local time;\r\
\n:set date [/system clock get date];\r\
\n:set time [/system clock get time];\r\
\n/file print file=lastseen.txt where name=lastseen.txt;\r\
\n/file set lastseen.txt contents=\"\$date \$time\"\r\
\n#:local lastdt ([/file get lastseen.txt contents])\r\
\n#:log warning \"Updaintg Last Seen > \$lastdt\"\r\
\n}"

Print View of Both Scripts


/sys scr pr

0   name="email-on-reboot" owner="admin" policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api last-started=jun/15/2015 13:17:47 run-count=39
source=
# Disable LASTSEEN script schduler to prevent overwritten of time"
:log error "Disabling Lastseen Update Time Scheudle to preserve Last REBOOT time"
/sys scheduler disable update-last-seen-time-on-each-minute

:delay 30s
:global gmailsmtp
:set gmailsmtp [:resolve "smtp.gmail.com"];

# Set your GMAIL Account Password
:local gmailpass
:set gmailpass GMAILPASS

# Set your email where you want to receive the alert
:local mailsendto
:set mailsendto aacable@hotmail.com

# Wait for NTP Time Synchronization to pritn current timestamp in mail subject, NTP is required in RB's
:while ( [/system ntp client get status]!="synchronized" ) do={ :delay 1s }

# Set Email Subject
:local es "$[/system identity get name] got LOST at $[/file get lastseen.txt contents] & back online at $[/system clock get date] $[/system clock get time]"

# Load Last LOGS Entries of 60 seconds
:delay 60s
:local eb "Mikrotik Log contents (with 60 seconds delay):\r\n"
:foreach le in=[/log print as-value] do={
:set eb ($eb.[:tostr [($le->"time")]]." ".[:tostr [($le->"topics")]].": ".[:tostr [($le->"message")]]."\r\n")
}

# Finally send email
/tool e-mail send to=$mailsendto subject=$es body=$eb server=$gmailsmtp tls=yes password=$gmailpass
delay 5s

# Enable back the update time schdule for lastseen value
:log warning "Email Done! Enabling Lastseen Update Time Scheudle ..."
/sys scheduler enable update-last-seen-time-on-each-minute

# Syed Jahanzaib
# aacable [at] hotmail.com

#########################
##### Second Script View
########################
1   name="update-last-seen-time-on-each-minute" owner="admin" policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api last-started=jun/15/2015 13:49:18 run-count=307
source=
:local date;
:local time;
:set date [/system clock get date];
:set time [/system clock get time];
/file print file=lastseen.txt where name=lastseen.txt;
/file set lastseen.txt contents="$date $time"
#:local lastdt ([/file get lastseen.txt contents])
#:log warning "Updaintg Last Seen > $lastdt"
}

 

Schedule both scripts

/system scheduler
# First script which will run once only upon system restart
add disabled=no interval=0s name=email-on-reboot on-event=email-on-reboot policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api start-time=startup

# Second script which will run after each minute to update the date/time in local file
add disabled=no interval=1m name=update-last-seen-time-on-each-minute on-event=update-last-seen-time-on-each-minute policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api \
start-date=jun/15/2015 start-time=05:40:08

Configure Email Example

Also don’t forget to set email tools. like

/tool e-mail
set address=173.194.69.109 from=YOURGMAILID@gmail.com password=YOURGMAILPASS port=587 starttls=no user=YOURGMAILID

 


 

SCRIPTS iN ACTiON

Now power off the router , and after few minutes power it on.

After a while, you should see the scripts in action.
As showed in the image below …

email-mikrotik-reboot-emial

 

email

.

Regard’s
Syed Jahanzaib


Filed under: Mikrotik Related

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

$
0
0

sms

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

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

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

At the moment there are two scripts

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

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

 

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


1- SMS for account expiry notification

 

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

Now paste the following code.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



 

CRON JOB TO RUN IT DAILY IN NIGHT

Now set cron job to run it daily in night

@daily /temp/sms.sh


 LOGS

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

Sample:

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

/var/log/smsapi.log

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

Sample:

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


2- SMS for NEW Account Creation

newacc

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


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

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

# APITEL User Name & Password
APIUSER="apiuser"
APIPASS="apipass"
API="senderid"
# Date functions to find current date, month year and Transaction id using seconds ; ) jugaar way ; )
NOW=$(date)
TID=$(date +"-%s")

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

# Create log files
touch /tmp/sms-new-account.log
touch /tmp/sms-new-account-api.log

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

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

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

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

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

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

# SMS Body
BODY="Dear+$username,+Welcome+to+ISP+Services,+Your+account+have+been+successfully+registered.++++zaibisp"

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

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

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

fi

Cron it to run after every 5 minutes

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


ITELSERVICES.NET related information

Sample of URL to send SMS

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

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

 

INFORMATION AND ERROR CODES related to API

For the information/error codes

 

1

 

2

 

3


 

Regard’s
Syed Jahanzaib


Filed under: Linux Related, Radius Manager

RADIUS Redundancy by using MYSQL Master-Master Replication

$
0
0

master-master

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

Scenario:

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

Requirements:

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

Components Used:

  • SERVER1 NAME = MASTER-RADIUS
    OS = Centos 6.5 32bit
    IP = 101.11.11.241
  • SERVER2 NAME = REPLICA-RADIUS
    OS = Centos 6.5 32bit
    IP = 101.11.11.245

Let’s Start

 

Step – 1

Server1 = ‘master-radius’ Configuration

Open mysql config file

nano /etc/my.cnf

and add following under [mysqld] section

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

SAVE and EXIT.

Now restart mysqld service so changes can take effect.

service mysqld restart

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

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

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

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

show master status;

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

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

1 row in set (0.00 sec)

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


 

Step – 2

Server2 = ‘replica-radius’ Configuration

 

Open mysql config file

nano /etc/my.cnf

and add following under [mysqld] section

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

Make sure server-id is different then primary server

SAVE and EXIT.

Now restart mysqld service so changes can take effect.

service mysqld restart

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

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

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

slave stop;

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

slave start; 

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

 

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

We can do that by typing the following:

SHOW MASTER STATUS; 

The output will look similar to the following:

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

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

The next step will explain how to do that.

 

Step – 3

Completing Replication on Server1 [Master-radius]

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

Running this command will replicate all data from Server 2.

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

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

The output will look similar to the following:

Query OK, 0 rows affected (0.01 sec)

 

Now test the status by issuing command to mysql cli

show slave status\G

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

replica-status


 

TEST

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

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

As showed in the images below …

At a moment no users have been created.

server1-empty

 

Now create test user

server1-users-create

 

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

server2-new0user0replicate-ok

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


 

I will add few more details later….

 

Regard’s
Syed Jahanzaib

 


Filed under: Linux Related, Radius Manager

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

$
0
0

Personnel Notes: For future retrieval of the code

1

2

Task:

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

rmRM send following SMS upon new account creation

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

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

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


 

 

Solution:

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

login to mysql and issue following commands

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

Now you can use following script.

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

Add following date in the script

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

SQLUSER="root"
SQLPASS="zaib1234"

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

mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT rm_invoices.username, rm_invoices.paid, rm_users.createdon, rm_invoices.expiration FROM rm_invoices INNER JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= NOW() - INTERVAL 200 MINUTE  AND (paymode = '0' ) AND (invgroup = '0'  OR invgroup = '1' );" > /tmp/temp

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

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

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

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

# If user account creation date is today, then send welcome message with other details
if [ $cratedwod  -eq $paidwod ]
then
echo "Welcome $username, Your Internet Services have been activated with $PKGNAME Service. Login details are / username = $username / Activation Date = $paid / Expiration Date= $expiration"

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

# If user account creation date is old, then send RENEWAL message with other details
else
echo "Dear $username, Your account have been renewed with $PKGNAME Service. Login details are / username = $username / Renewal Date = $paid / Expiration Date= $expiration"
fi
done

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


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

olduser

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

 


 

Regard’s
Syed Jahanzaib

 


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