Syed Jahanzaib Personal Blog to Share Knowledge !

October 8, 2015

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

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

keep calm n coding

mikrotik status updated script via sms

Quick Note:

Scenario#1:

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

 

Dirty Solution:

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

#SCRIPT-1

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

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

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

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

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

# Admin SMS Number Config
:local cell1 "03333021909"

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

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

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

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

 

Sample Image of SMS:

debug

sms


 

Enable Mikrotik to Receive SMS and run script

Use following command to enable SMS receiving on mikrotik.

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

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

:cmd 12345 script test

 

Explanation:

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

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

 


#SCRIPT-2

Another mature version where we are using 2 mikrotik as NAS and freeradius as billing.

#!/bin/bash
PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# 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 to admins via SMS
# Version 2.0 -
# Created in year 2013
# Last modified 20-NOV-2018
# set -x
logger DAILY_9_am_sms_executed
#ntpdate -u 91.189.91.157
UPTIME=`uptime | sed -e 's/^.*up //' -e 's/[^0-9:].*//' | sed 's/:/*60+/g'`
DATE=`date`
COMPANY="ZAIBB"
SQLUSER="root"
SQLPASS="SQLPASSWORD"
DB_RADIUS="radius"
RADIUS_SRV="freeradius"
MYSQL_SRV="mysql"
SQL_ACCOUNTING_TABLE="radacct"
export MYSQL_PWD=$SQLPASS
TMP="/tmp/dailysms.txt"
> $TMP
# snmp must be enabled on both NAS
MIKROTIK1="1.2.3.4"
MIKROTIK2="5.6.7.8"
SERVICE="freeradius"
SNMPCOM="PUBLIC"
# KANNEL SECTION
KURL="127.0.0.1:13013"
KPASS="kannel_pass"

CELL1="03333021909"

# Check if Mikrotik 1 is accessibel or not, if not then update status
if [[ $(ping -q -c 2 $MIKROTIK1) == @(*100% packet loss*) ]]; then
MIKROTIK1_STATUS="DOWN"
echo -e "ALERT ..... MIKROTIK $MIKROTIK1 is DOWN"
else
MIKROTIK1_STATUS="OK"
echo -e "-Mikroik $MIKROTIK1 PING OK, Proceeding further ..."
fi

# Check if Mikrotik 2 is accessibel or not, if not then update status
if [[ $(ping -q -c 2 $MIKROTIK2) == @(*100% packet loss*) ]]; then
MIKROTIK2_STATUS="DOWN"
echo -e "ALERT ..... MIKROTIK $MIKROTIK2 is DOWN"
else
MIKROTIK2_STATUS="OK"
echo -e "-Mikroik $MIKROTIK2 PING OK, Proceeding further ..."
fi

# Check if $DB (in this case radius ) is accessible or not, if NOT, then update status
DB_RESULT=`mysql --skip-column-names -e "SHOW DATABASES LIKE '$DB_RADIUS'"`
if [ "$DB_RESULT" == "$DB_RADIUS" ]; then
DB_RADIUS_RESULT="UP"
echo "-$DB_RADIUS database exist OK. Proceeding further ..."
else
DB_RADIUS_RESULT="DOWN"
echo "-$DB_RADIUS database does not exist!"
fi

# Check if SRV (in this case MYSQL) is running or not, if NOT, update status
MYSQL_SRVSTATUS=$(pgrep $MYSQL_SRV | wc -l);
if [ "$MYSQL_SRVSTATUS" -ne 1 ];
then
echo "-$MYSQL_SRV is down. Pleasec check your $RADIUS_SRV service first"
MYSQL_STATUS="DOWN"
else
MYSQL_STATUS="UP"
echo "-$MYSQL_SRV is accessible OK. Proceeding further ..."
fi

# Check if SRV (in this case FREERADIUS) is running or not, if NOT, then update status
RADIUS_SRVSTATUS=$(pgrep $RADIUS_SRV | wc -l);
if [ "$RADIUS_SRVSTATUS" -ne 1 ];
then
echo "-$RADIUS_SRV is down. Pleasec check your $RADIUS_SRV service first"
FR_STATUS="DOWN"
else
FR_STATUS="UP"
echo "-$RADIUS_SRV is accessible OK. Proceeding further ..."
fi

PPP1=`snmpwalk -Oqv -v1 -c $SNMPCOM $MIKROTIK1 1.3.6.1.4.1.9.9.150.1.1.1.0`
PPP2=`snmpwalk -Oqv -v1 -c $SNMPCOM $MIKROTIK2 1.3.6.1.4.1.9.9.150.1.1.1.0`

SESSIONS=`mysql --skip-column-names -e "use $DB_RADIUS; SELECT username FROM $SQL_ACCOUNTING_TABLE WHERE acctstoptime IS NULL;" |wc -l`

# Print total and each vlan users
MSG="$COMPANY - Daily INFO SMS
@ $DATE

$MIKROTIK1 ping = $MIKROTIK1_STATUS
$MIKROTIK2 ping = $MIKROTIK2_STATUS
Radius Online = $SESSIONS
CCR $MIKROTIK1 PPP Users = $PPP1
CCR $MIKROTIK2 PPP Users = $PPP2
Radius = $FR_STATUS
MYSQL = $MYSQL_STATUS
DB = $DB_RADIUS_RESULT"
echo "$MSG" > $TMP
cat $TMP

# Finally SEND SMS
#curl "http://$KURL/cgi-bin/sendsms?username=kannel&password=$KPASS&to=$CELL1" -G --data-urlencode text@$TMP

# THE END

Regard’s
Syed Jahanzaib!

January 10, 2013

Mikrotik: Netwatch Script to Detect Target Server Link & Act Accordingly

Filed under: Mikrotik Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 9:16 AM

matrix

Someone requested me to create a script that can check Squid Proxy or Target Server Link state from Mikrotik, and if the Squid Proxy / Target Server is not responding, then it should Disable the redirect NAT rule so all load can be handle by Mikrotik.You can modify this script as per your requirements. you can modify it to check WAN link, and if the WAN link is down, it can trigger SMS Script / Sound Alaram, or shift to backup WAN link by enabling diabling ROUTE’s or it can also be used to detect any wan link failure detection and change the rules accordingly.
Possibilities are endless.
So here it is.

[for ver 5.x]

Adding Comments in Redirect Rule

First add comments in required NAT rule, i.e Rule that redirects port 80 traffic to squid. You can also disable/enable rules based on the numbers, BUT its not recommended BECAUSE if you add any new rule and move it somewhere, all your scripts will disable/enable wrong rules, that is why you have to use find command and get rules this way.

You can use GUI to add comment in the rule, I am showing you an example below . . .
/ip firewall nat
add action=dst-nat chain=dstnat comment=”Redirect to SQUID” disabled=no dst-port=80 protocol=tcp to-addresses=192.168.6.1 to-ports=8080

add action=masquerade chain=srcnat comment=”Default NAT Rule for Internet Access / zaib” disabled=no to-addresses=0.0.0.0

1- nat rule

Change the host ip address as your local requirements. Its jsut an example to show you.

.

.

Adding EMAIL account in mikrotik

/tool e-mail set address=73.194.78.109 from=yourgmailid@gmail.com password=your_password port=587 start-tls=no user=your_gmailid

Adding Scripts to Enable/Disable Rule

After adding comments in the dst-nt rule, you have to create two scripts that can enable and disable the dst-nat rule. We can name them UP and DOWN.
 Copy paste the below scripts on Mikrotik Terminal. It will create two scripts in System/Scripts with the name of UP and DOWN.

DOWN SCRIPT

:log info "Squid Proxy Server is not responding. Please Check Connectivity"
/ip firewall nat disable [find comment="Redirect to SQUID"]
:log info "Emailing the DOWN status. . . "
#/tool e-mail send to="aacable@hotmail.com" password=yourgmailid subject="Squid Proxy Server is not responding. Please Check Connectivity"  body="Squid Proxy Server is not responding. Please Check Connectivity" from=yourgmailid@gmail.com server=173.194.69.109 tls=yes

UP SCRIPT

:log info "Squid Proxy Server is OK."
/ip firewall nat enable [find comment="Redirect to SQUID"]
:log info "Emailing the UP status. . . "
#/tool e-mail send to="aacable@hotmail.com" password=yourgmailid subject="Squid Proxy Server is OK."  body="Squid Proxy Server is OK." from=yourgmailid@gmail.com server=173.194.69.109 tls=yes

2- Script-List

.

Adding NETWATCH to monitor Target Server [Squid] Link Detection

Use the below script to add netwatch entry for squid / target server link detection. It will also add the UP and DOWN script for the appropriate action. For example. When the target server link is down, it will execute script DOWN which will disable the NAT redirect rule , when the target server link is up and working, it will execute the UP script which will re-enable the redirect rule.

/tool netwatch
add comment=”Netwatch to Check SQUID Server Link state / zaib” disabled=no down-script=”/sys script run down” host=192.168.6.1 interval=5m timeout=1s \
    up-script=”/sys script run up”

3 - Squid Link Detection

(Replace the host ip to match your local target server ip)

.

.

Testing THE Scripts . . .   :)~

Now test the scripts, Unplug the Target Server LAN link, and you will see something like below in the LOG.

4- link down

.

Now plugin the Target Server LAN link, and you will see something like below in the LOG.

5- link up

.

.

[For Ver 6.x]

Netwatch base monitoring for local server. copy paste following and modify necessary information before enabling this rule.


 

First setup EMAIL config.

/tool e-mail
set address=173.194.67.108 from=YOUR_GMAILID@gmail.com last-status=succeeded password=GMAIL_PASSWORD port=587 start-tls=yes user=YOUR_GMAILID

 

Now add the netwatch script … You can simply copy paste the script, modify it before pasting …

/tool netwatch
add down-script=":log warning \"Squid Proxy Server is not responding. Please C\
    heck Connectivity . . . \"\r\
    \n:global sub1 ([/system identity get name])\r\
    \n:global sub2 ([/system clock get time])\r\
    \n:global sub3 ([/system clock get date])\r\
    \n:global adminmail1 YOURGMAIL@gmail.com\r\
    \n:global gmailid  YOURGMAIL@gmail.com\r\
    \n:global gmailpwd  GMAIL_PASSWORD\r\
    \n:global gmailsmtp\r\
    \n:set gmailsmtp [:resolve \"smtp.gmail.com\"];\r\
    \n\r\
    \n# ENABLING SQUID Redirect Rule\r\
    \n/ip firewall nat disable [find comment=\"Redirect to SQUID\"]\r\
    \n\r\
    \n/tool e-mail send to=\$adminmail1 password=\$gmailpwd subject=\"\$sub3 \
    \$sub2 \$sub1 SQUID IS DOWN ... DISABLING NAT RULE\" from=\$gmailid server\
    =\$gmailip start-tls=yes  body=\"Squid Proxy Server is not responding. Ple\
    ase Check Connectivity\"" host=192.168.6.2 interval=10s timeout=3s \
    up-script=":log warning \"Squid Proxy Server is UP. Enalbing REDIRECT NAT \
    rule  . . . \"\r\
    \n\r\
    \n:global sub1 ([/system identity get name])\r\
    \n:global sub2 ([/system clock get time])\r\
    \n:global sub3 ([/system clock get date])\r\
    \n:global adminmail1 YOURGMAIL@gmail.com\r\
    \n:global gmailid  YOURGMAIL@gmail.com\r\
    \n:global gmailpwd  GMAIL_PASSWORD\r\
    \n:global gmailsmtp\r\
    \n:set gmailsmtp [:resolve \"smtp.gmail.com\"];\r\
    \n\r\
    \n# Disabling SQUID Redirect Rule\r\
    \n/ip firewall nat disable [find comment=\"Redirect to SQUID\"]\r\
    \n\r\
    \n/tool e-mail send to=\$adminmail1 password=\$gmailpwd subject=\"\$sub3 \
    \$sub2 \$sub1 Squid Proxy Server is OK UP. Enabling REDIRECT NAT rule\" fr\
    om=\$gmailid server=\$gmailsmtp start-tls=yes  body=\"Squid Proxy Server i\
    s UP. Enalbing REDIRECT NAT rule\"\r\
    \n"


 

It will add the netwatch script, and will monitor your local server and will email you as well. Modify it before using it

 


 

SCRIPT TO CHECK SQUID STATUS AND START IT IF REQUIRED

Following script [checksquid.sh] will check SQUID service status , and if it found squid stop, it will start it auto, if the squid is already running , it will do nothing :)

First create file in any folder or temp folder by

mkdir /temp
touch /temp/checksquid.sh
chmod +x  /temp/checksquid.sh

Now edit this file

nano /temp/checksquid.sh

& paste the following code

#!/bin/bash
pid=`pidof squid`
if [ "$pid" == "" ]; then
echo -e "SQUID service is NOT running, Trying to start using SERVICE command  (( IF squid is installed via apt-get or yum ))  . . ."
service squid start

# or if squid is compiled then use simple command to start squid
echo -e "Now, Trying to start using squid command ( IF Squid is Compiled from the source)  . . ."
/usr/sbin/squid
echo You should now see the squid process below ...
echo .
sleep 3
ps aux |grep squid
else
echo SQUID service is Running OK , no further action required, EXITING  . . . You should see Squid process below ...
ps aux |grep squid
fi

Save & Exit.

Test it by running

/temp/checksquid.sh

You can check any service status with above command, if the service is not running , it will try to start with.

You can create its cron entry to run it after every 5 minutes.

For example, add it using CRON by following

crontab -e

and add following line

*/5 * * * * /temp/checksquid.sh

Now save and exit.

Regard’s

Syed Jahanzaib

%d bloggers like this: