Syed Jahanzaib Personal Blog to Share Knowledge !

January 15, 2016

[Personnel Reference] Windows General Admin Tips

Filed under: Microsoft Related — Tags: , , , — Syed Jahanzaib / Pinochio~:) @ 11:31 AM

remote


Windows General Administration Tips  for day to day task. These are commands I use in day to day operation to get quick info and control our domain users. Most of commands may work in domain environment, but you can modify it to work with work-group environment if you know the remote PC id password.

Also I am using PSTOOLS to accompany the tasks. You should download pstools and extract them in c:\pstools folder.

https://download.sysinternals.com/files/pstools.zip

 


Most of pstools commands require remote registry on remote PC must be running. you can start that service on remote PC by using following command.

TIP: When the Utilities Won’t Connect Because of Remote Registry

psservice \\remotepc start RemoteRegistry

 

Inquire Remote PC Hardware Info like Board / serial and OS Architecture 32bit/64bit.

– To get Board number of local pc

wmic baseboard get product,Manufacturer,version,serialnumber

– To get  Board number of remote pc

wmic /node:"remotepc" baseboard get product,Manufacturer,version,serialnumber

– To get remote PC Architecture like 32bit or 64bit

wmic /node:"remotepc" os get osarchitecture

2- hardware


PSTOOLS RELATED

# PSLOGGEDON COMMANDS

To check which user is logged on remote PC,

psloggedon \\remotepc

# PSEXEC COMMANDS

– To execute any command on remote PC like

psexec \\remtotepc ipconfig

– To open COMMAND prompt of remote user

psexec \\remotepc cmd

-Interacting with the Logged On User on the Remote PC

psexec \\remotepc -d -i notepad

# PSINFO COMMANDS

Getting general info of OS, uptime etc with disk info as well

psinfo -d \\remotepc

1- psinfo


 

# PSLIST COMMANDS

To get running process list from remote PC.

pslist \\remotepc

# PSKILL COMMANDS

– Kill any running program on remote PC.

pskill \\remotepc notepad

# PSSHUTDOWN COMMANDS

– To shutdown remote PC

psshutdown \\remotepc -d

# WINDOWS BUILTIN SHUTDOWN TOOL

Its recommended to use windows builtin shutdown utility/tool

– To Shutdown local PC in 30 seconds with popup message.

shutdown /s /t 30 /c "Shutdown by Admin"

– To restart Local PC in 30 seconds

shutdown /r /t 30 /c "Restart by Admin"

– To shutdown REMOTE PC in 30 seconds with a message

shutdown /m \\remotepc /s /t 30 /c "Shutdown by Admin"

– To restart REMOTE PC in 30 seconds

shutdown /m \\remotepc /r /t 30 /c "Shutdown by Admin"

# WINDOWS TASK LIST / KILL TOOLS

# WINDOWS BUILTIN TASK LIST TOOL (to view remote pc running process task)

tasklist /S REMOTEPC

tasklist

– To kill remote PC task by name

taskkill /S REMOTEPCNAME /F /IM notepad.exe

# WINDOWS BUILTIN TASKKILL TOOL (to kill any task)

– to kill local task by name with force

taskkill /IM /F notepad.exe

– to kill local running task by PID

taskkill /PID 1234 /T

 

More will be added later.

Some more reference for using PSTOOLS in some automated ways are

https://aacable.wordpress.com/tag/howto-install-snmp-in-windows-7-remotely/

https://aacable.wordpress.com/2015/11/05/adding-external-ntp-server-in-domain-controller-short-notes/


 

Regard’s
Syed Jahanzaib

January 11, 2016

December 30, 2015

2015 in review

Filed under: Uncategorized — Syed Jahanzaib / Pinochio~:) @ 8:43 AM

The WordPress.com stats helper monkeys prepared a 2015 annual report for this blog.

Here’s an excerpt:

The Louvre Museum has 8.5 million visitors per year. This blog was viewed about 1,300,000 times in 2015. If it were an exhibit at the Louvre Museum, it would take about 56 days for that many people to see it.

Click here to see the complete report.

December 18, 2015

ACCESS DSL MODEM PAGE IN BRIDGE MODE

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

bridge

ACCESS DSL MODEM PAGE IN BRIDGE MODE (FROM INTERNET , or local)

As asked by many, here is the short code.

Mikrotik WAN Interface IP = 192.168.2.10
[configure in Mikrotik]

Modem LAN IP Interface IP = 192.168.2.1
[configure in Modem]
[as showed in the image below]

 

First configure IP address in the modem LAN so it can be accessed by Mikrotik.

As showed in the image below …

1- lan


 

Now add rules in Mikrotik NAT section, and move them on TOP

/ip firewall nat
add action=masquerade chain=srcnat comment="Masquerade request going to access DSL Panel/zaib" dst-address=192.168.20.10

add action=dst-nat chain=dstnat comment="Route vdsl modem panel request from internet to local modem - dst-port 1234 to port 80 of modem/zaib" dst-port=1234 in-interface=pppoe-out1 protocol=tcp to-addresses=192.168.2.1 to-ports=80

.

Now you can access modem panel from the internet by

http://your_wan_ip_or_host:1234

or from LAN

http://your_modem_local_ip

Note: You can create ACL to restrict access.

December 14, 2015

Manage Cisco Ports from PHP/VBS/BASH or incoming SMS using kannel/playSMS


linux


 

NOTE:
I am documenting this port just for references purposes. not for everyone. it do requires
some really good knowledge of bash scripting and cisco. These scripts were designed
for very specific network with very targeted requirements. It may not run in your 
network as its really customized and made exclusively for that particular 
network to facilitate terminal and SMS base execution. I will add few sections later
like php and playSMS/kannel.
Regard's
Syed Jahanzaib / 14-DEC-2015 / 1030 hours

 

Scenario:

Two Cisco 3750-E switches are installed in local area. SSH/TELNET access is enabled.
SNMP is also enabled with profile name ‘public‘.

Requirements:

Sometimes any port gets auto shut dueto flooding or manually by admin for management purposes.  It is required that admin can disable or enable any port by using BASH script. Later it should be integrated with SMS using existing KANNEL gateway via playSMS app. so that admin can send an sms to his KANNEL gateway with the parameters and then system can act upon it as directed. in ubuntu, ‘EXPECT’ package is also installed which will be required in executing helper scripts so take a note of it.

SCRIPTS:

It requires 3 scripts.

master.sh
It will act as launcher which will check for 3 variables validity.It will also check the switch availability via ping, it will check for port status before doing any action and will act accordingly.

ciscoup.sh     [helper script for master]
It will SSH to cisco switch and execute shut/noshut command to turn the PORT UP.

ciscodown.sh     [helper script for master]
It will SSH to cisco switch and execute shut command to turn the PORT DOWN.

 

SCRIPT Example

./master.sh switch_number port_number ACTION_required

./master.sh SW1 24 DOWN
./master.sh SW1 24 UP


master.sh

#!/bin/bash
# Script to manage CISCO 3750/xxxx model switch via bash script.
# It can print all errors related to script, it can perform given Action like UP/DOWN for any given port on require switch.
# Comes handy like you can integrate it with PHP  or any frontend.
# I made it for specific network where OP wanted to UP/DOWN the PORT via sending SMS to linux base system, and it will perform
# action as directed.
# Syed Jahanzaib
# aacable at hotmail dot com
# https://aacable.wordpress.com
# Created = 11-DEC-2015
# Last Mofidied = 11-DEC-2015

# Enable set -x to enable SCRIPT DEBUG mode.
#set -x

# Setting various Variables

# SWITCH IP Address VALUE
# Check VAR1 and match value with valid data
if [ "$1" != "SW1" ] && [ "$1" != "SW2" ];
then
echo "Switch Value must be SW1 or SW2
Usage Example:

./master.sh SW1 24 UP"

exit 1; fi

# SWITCH IP ADDRESSES. CHANGE IT AS REQUIRED / ZAIB
SW1IP="192.168.0.1"
SW2IP="192.168.0.2"

###########################################
# MAKE SURE YOU CHANGE THIS OID AS REQUIRED. SOME SWITCHES LIKE MB/GB MAY HAVE DIFFERNT OID IN UR NETWORK.
PORTOID="1.3.6.1.2.1.2.2.1.8.101"
# To get Port description, friendly text for port
PORTDESC="1.3.6.1.2.1.31.1.1.1.18.101"

# SWITCH IP variable
# Check VAR1 and match value with valid data
if [ "$1" = "SW1" ] ; then
SWITCH="$SW1IP"
fi

if [ "$1" == "SW2" ] ; then
SWITCH="$SW2IP"
fi

# SWITCH Variable
# Check VAR1 and match value with valid data
PORT="$2"
if [[ "$PORT" =~ ^[0-9]+$ ]] && [[ "$PORT" -le 48 ]] ; then
echo
else
echo "PORT value not correct. It must be in numeric format like 01 upto max 48 etc
Usage Example:

./master.sh SW1 24 UP"

exit 1; fi

# ACTION Variable
# Check VAR1 and match value with valid data
ACTION="$3"

if [ "$ACTION" != "UP" ] && [ "$ACTION" != "DOWN" ];
then
echo "Action Value not correct, it must be either UP or DONW
Usage Example:

./master.sh SW1 24 UP"

exit 1; fi

# Check PING status of switch.
# Check if Mikrotik is accessibel or not, if not then EXIT immediately with error / zaib
if [[ $(ping -q -c 2 $SWITCH) == @(*100% packet loss*) ]]; then
echo "ALERT ..... $SWITCH is DOWN. cannot process further. check connectivity."
exit
else
echo "$SWITCH is accessible OK."
fi

# Port Description infor to get more accurate idea about port info
DESCR=`snmpwalk -v1 -c public $SWITCH $PORTDESC$PORT | sed -e 's/\"//' | sed -e 's/\"//' | awk '{print $4,$5,$6,$7,$8,$9}'`

# Print Data gaterhed
echo -e "Command Data Received.
SWITCH = $1 = $SWITCH
PORT = $PORT
PORT DESCR = $DESCR
REQUIRED ACTION = $ACTION"

# Query Present / Current PORT Status
PORTQUERY=`snmpwalk -v1 -c public $SWITCH $PORTOID$PORT | awk '{print $4}'`
RESULT="$PORTQUERY"
if [ "$RESULT" == "1" ]; then
PRESULT="UP"
echo -e "PORT Current Status = $PRESULT"
else
PRESULT="DOWN"
echo -e "PORT Current Status = $PRESULT"
fi

# Match condition. If Action required is UP and port is already UP, then NO ACTION, just exit.
PORTQUERY=`snmpwalk -v1 -c public $SWITCH $PORTOID$PORT | awk '{print $4}'`
RESULT="$PORTQUERY"
if [ "$RESULT" == "1" ] && [ "$ACTION" == 'UP' ];
then
echo "Port $PORT is already UP. No action is required. Exiting ..."
fi

# Match condition. If Action required is UP and port is DOWN , then run UP script.
if [ "$RESULT" == "2" ] && [ "$ACTION" == 'UP' ];
then
echo -e "PORT $PORT $PRESULT. doing UP Action..."
/temp/ciscoup.sh  $SWITCH $PORT $ACTION
#> /dev/null 2>&1
fi

# Match condition. If Action required is DOWN and port is also DOWN , then NO ACTION, Just EXIT.
if [ "$RESULT" == "2" ] && [ "$ACTION" == 'DOWN' ];
then
echo "PORT $PORT is already DOWN, no action required. Exiting ..."
fi


# Match condition. If Action required is DOWN and port is UP , then eyb UP script.
if [ "$RESULT" == "1" ] && [ "$ACTION" == 'DOWN' ];
then
echo "Doing DOWN Action..."
/temp/ciscodown.sh $SWITCH $PORT $ACTION
#> /dev/null 2>&1
fi

# PRINT Final Status (after the above actions are done, so we can have idea whats the final result)
PORTQUERY=`snmpwalk -v1 -c public $SWITCH $PORTOID$PORT | awk '{print $4}'`
RESULT="$PORTQUERY"
if [ "$RESULT" == "1" ]; then
echo
echo "FINAL RESULT = UP
~~~~~~~~~~~~~~~~~"

else
echo
echo "FINAL RESULT = DOWN
~~~~~~~~~~~~~~~~~"
fi

# SCRIPT END.
# EXIT
# JZ

ciscodown.sh [make sure you change username and password to match your switch credentials]

#!/usr/bin/expect -f
set timeout 20
set IPaddress [lindex $argv 0]
set Username "zaib"
set Password "zaib"
set PORT [lindex $argv 1]

spawn ssh -o "StrictHostKeyChecking no" $Username@$IPaddress

expect "*assword: "
send "$Password\r"

expect ">"

send "enable\r"
expect "*assword: "
send "$Password\r"


send "conf term\r"


send "interface gigabitEthernet 1/0/$PORT\r"
expect "#"

send "shut\r"
expect "#"

send "exit\r"
expect "#"
send "exit\r"

send "wr\r"
send "exit\r"

# Exit Script
exit

ciscoup.sh [make sure you change username and password to match your switch credentials]

#!/usr/bin/expect -f
set timeout 20
set IPaddress [lindex $argv 0]
set Username "zaib"
set Password "zaib"
set PORT [lindex $argv 1]

spawn ssh -o "StrictHostKeyChecking no" $Username@$IPaddress

expect "*assword: "
send "$Password\r"

expect ">"

send "enable\r"
expect "*assword: "
send "$Password\r"


send "conf term\r"


send "interface gigabitEthernet 1/0/$PORT\r"
expect "#"

send "shut\r"
expect "#"

send "no shut\r"
expect "#"

send "exit\r"
expect "#"
send "exit\r"

expect ">"
send "wr\r"
send "exit\r"

# Exit Script
exit

RESULTS SCREENSHOT

down-switch

 

.

UP

DONE!

T.C


 

WINDOWS VBS TO EXECUTE PORT COMMAND, EXMAPLE ONLY

create file on your windows desktop or in any folder

cisco.vbs

paste the following contents in it.


set  WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd"
WScript.Sleep 300
WshShell.AppActivate "C:\Windows\system32\cmd.exe"
WScript.Sleep 300
WshShell.SendKeys "telnet 192.168.0.1{ENTER}"
WScript.Sleep 300
WshShell.SendKeys "zaib"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300
WshShell.SendKeys "zaib"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300
WshShell.SendKeys "enable"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300
WshShell.SendKeys "zaib"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300

WshShell.SendKeys "configure terminal"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300
WshShell.SendKeys "interface gigabitEthernet 1/0/24"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300

WshShell.SendKeys "shut"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300

WshShell.SendKeys "exit"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300

WshShell.SendKeys "exit"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300

WshShell.SendKeys "wr"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300

WshShell.SendKeys "exit"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 300

Adjust the key stroke as required. some switches access requires user name and password both, and some requires only password. SO YOU MUST SET THE CONTENTS ACCORDINGLY. best is to open command prompt and run script in cmd so that you can see the errors.  DON’T INTERRUPT after RUNNING THE FILE.

Screenshot.

vbs


 

 

Regard’s
Syed Jahanzaib

December 1, 2015

DYNU Script for Mikrotik (free dynamic dns script)

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

logo

An alternate to changeip.com (free ddns) with more features.

From few days , we were having issues in updating our mikrotik/linux base machines dynamic ip to free ddns service like changeip.com, therefore today I tested DYNU as an alternate and it worked very good. we can use it as backup or primary ddns service for our mikrotik routers.

First create account at http://www.dynu.com, add your required host. and then add script and schedule it to run after every 5  (or xx) minutes

Mikrotik Script for dynu ddns.

The below script is working 100% on Mikrotik 5.x and 6.x versions.
[Tested as of now / 1st-DEC-2015]

(You can copy paste following code in mikrotik by going to SYSTEMS / SCRIPTS / CLICK ON + sign to add script, and paste following.

NOTE: MAKE SURE YOU CHANGE THE REQUIRED FIELDS BEFORE DEPLOYMENT.

SCRIPT NAME: “DYNU”

1- SCRIPT FOR DSL MODEM IN BRIDGE MODE, MIKROTIK HAVE THE PUBLIC IP ADDRESS AT WAN INTERFACE.

(FOR BRIDGE MODE, PUBLIC IP IS DIRECTLY ON MIKROTIK WAN INTERFACE)


##############################################
# DYNU SCRIPT for Mikrotik , DSL Modem BRIDGE MODE, 
# Wan dialing is done by mikrotik so public ip is on mikrotik directly
# CHANGE THE FOLLOWING ACCORDING TO YOUR CREDENTIALS
# Syed Jahanzaib / aacable at hotmail dot com
# ####################################################

:global ddnsuser DYNU_USER
:global ddnspass "DYNU_PASSWORD"
:global theinterface "WAN_INTERFACE_NAME"
:global ddnshost "YOUR_DYNU_HOSTNAME.dynu.com"

#### Donot change below this line ####

:global ipddns [:resolve $ddnshost];
:global ipfresh [ /ip address get [/ip address find interface=$theinterface ] address ]
:if ([ :typeof $ipfresh ] = nil ) do={
:log info ("DynuDDNS: No IP address on $theinterface .")
} else={
:for i from=( [:len $ipfresh] - 1) to=0 do={
:if ( [:pick $ipfresh $i] = "/") do={
:set ipfresh [:pick $ipfresh 0 $i];
}
}
:if ($ipddns != $ipfresh) do={
:log info ("DynuDDNS: IP-Dynu = $ipddns")
:log info ("DynuDDNS: IP-Fresh = $ipfresh")
:log info "DynuDDNS: Update IP needed, Sending UPDATE...!"
:global str "/nic/update?hostname=$ddnshost&myip=$ipfresh"
/tool fetch address=api.dynu.com src-path=$str mode=http user=$ddnsuser password=$ddnspass dst-path=("/Dynu.".$ddnshost)
:delay 1
:global str [/file find name="Dynu.$ddnshost"];
/file remove $str
:global ipddns $ipfresh
:log info "DynuDDNS: IP updated to $ipfresh!"
} else={
:log info "DynuDDNS: dont need changes";
} }

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

Now run it and watch the results.


3


 

2- SECOND SCRIPT FOR DSL MODE, MIKROTIK IS CONNECTED TO INTERNET BEHIND DSL. (NAT)

 


########################################
# DYNU DNS Script for Mikrotik Behind DSL
# 14th JAN-2015
# Syed Jahanzaib / aacable at hotmail dot com
# ####################################################


# get the current IP address from the internet (in case of double-nat)

/tool fetch mode=http address="checkip.dyndns.org" src-path="/" dst-path="/dyndns.checkip.html"
:local result [/file get dyndns.checkip.html contents]

# parse the current IP result
:local resultLen [:len $result]
:local startLoc [:find $result ": " -1]
:set startLoc ($startLoc + 2)
:local endLoc [:find $result "</body>" -1]
:local currentIP [:pick $result $startLoc $endLoc]
#:log warning "UpdateDynDNS: currentIP = $currentIP"

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

:global ddnsuser DNSUSERNAME
:global ddnspass "DNSPASSWORD"
:global ddnshost "YOURHOST.dynu.com"
:global ipddns [:resolve $ddnshost];
#:global ipddns 1.2.3.4

:if ($ipddns != $currentIP) do={
:log info ("DynuDDNS: IP-Dynu = $ipddns")
:log info ("DynuDDNS: IP-Fresh = $currentIP")
:log info "DynuDDNS: Update IP needed, Sending UPDATE...!"
:global str "/nic/update?hostname=$ddnshost&myip=$currentIP"
/tool fetch address=api.dynu.com src-path=$str mode=http user=$ddnsuser password=$ddnspass dst-path=("/Dynu.".$ddnshost)
:delay 1
:global str [/file find name="Dynu.$ddnshost"];
/file remove $str
:global ipddns $currentIP
:log info "DynuDDNS: IP updated to $currentIP!"
} else={
:log info "DynuDDNS: dont need changes";
} }

 

To  scheudle it to run every 5 minutes , use


/system scheduler
add disabled=no interval=5m name=dynu on-event=dynu policy=\
ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api start-date=jan/01/1970 \
start-time=00:00:00


 

Regard’s

Syed Jahanzaib

 

November 26, 2015

[LAB TEST] BASH: Linux Script to check Internet/Gateway status and SMS via kannel

Filed under: Linux Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 12:10 PM

net_sms_details

Personnel notes for reference. LAB tests only. Generally not for production usage. Make sure you modify overall script to use at least two hosts for monitoring.

Testing Script to check internet /gateway status. and send alert via kannel sms, while preventing repeated alert for same status.


#!/bin/bash
# Script to check Internet Status and alert (trigger one time for each status changed)
# Host to monitor
HOST1="4.2.2.1"

# Server / This Computer name
HOSTNAME=`hostname`

COMPANY="ZAIB"
DATE=`date`

# How many PING attempts
ping_attempts=30

# Temporary file holder for host status
HOST1_STATUS="/tmp/down_hosts.txt"

# Create temp file if not already present, usually for 1st time execution
touch $HOST1_STATUS

# SMS RELATED and KANNEL INFO

# KANNEL SMS Gateway Info
KANNELURL="127.0.0.1:13013"
KANNELID="kannel"
KANNELPASS="kannel"
CELL1="03333021909"

# SMS Messages for UP / DOWN
SMS_DOWN="$COMPANY ALERT: $DATE

$HOSTNAME: Internet / $HOST1 not responding to ping request. Check internet connectivity."

SMS_UP="$COMPANY INFO: $DATE

$HOSTNAME: Internet / $HOST1 is reachable now. OK!"

SMSDOWNHOLDER="/tmp/$HOST1_down.sms"
SMSUPHOLDER="/tmp/$HOST1_up.sms"

# Run the script
echo -e "Trying to ping $HOST1 / 30 times"
for HOST in $HOST1
do
count=$(ping -c $ping_attempts $HOST | awk -F, '/received/{print $2*1}')
if [ $count -eq 0 ]; then
echo "$HOST is down"
if  [ $(grep -c "$HOST" "$HOST1_STATUS") -eq 0 ]; then
echo "$HOST is down (ping failed) at $(date) .. SENDING DOWN SMS ..."
echo "$SMS_DOWN" > /tmp/$HOST1_down.sms
echo "$HOST" >> $HOST1_STATUS

# Sending DOWN SMS via KANNEL
cat $SMSDOWNHOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-

fi
else
echo "$HOST is alive"
if  [ $(grep -c "$HOST" "$HOST1_STATUS") -eq 1 ]; then
echo "$HOST is up (ping ok) at $(date)... SENDING UP SMS ..."
echo "$SMS_UP" > /tmp/$HOST1_down.sms
# Sending UP SMS via KANNEL
cat $SMSUPHOLDER | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-

sed -i "/$HOST/d" "$HOST1_STATUS"
fi
fi
done

Schedule it to run after very x minutes.

Regard’s
Syed Jahanzaib

BASH: Scheduled script to check linux service status and sms/email while preventing repeated alerts

Filed under: Linux Related — Tags: , — Syed Jahanzaib / Pinochio~:) @ 12:00 PM

BOYSERVICECHECK

sms

MAIL1

Following is linux base bash script which can be scheduled to run every X minutes and it can do following …

Personnel Note:

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

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

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

In this example I took MYSQL and RADIUS services.

Its much easier to use some centralized network monitoring system like Mikrotik DUDE or NAGIOS  or likewise , but as we know that every system have its known limitations, and sometime it is un necessary to setup a network monitoring system just to monitor single PC or service.
In such situation where resources are limited OR you want some thing very customized solution of your own choices with your required bells and whistles ,  its recommended to do it with simple bash without needing any 3rd party tool.

 

PSEUDO CODE:

  • Check for Service status example mysqld
  • If it found it running, then do nothing. Exit
  • If it found it STOPPED, it will send you SMS alert for down status (one time only until next status change) via KANNEL sms gateway. It will also gonna try to start the service one time.
  • If it found the service running on next run, it will send service UP info via sms. (one time only until next status change)
  • Email Alerts for UP n DOWN added on 4th Dec, 2015

SCRIPT:

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

Now paste the following



#!/bin/bash
# Scheduled Script to check linux service status after every 5 minutes.
# If found stopped, send sms or email Alerts, but donot repeat it untill next status change.
# Script Designed by Syed Jahanzaib
# aacable at hotmail dot com
# https://aacable.wordpress.com
# Created : 25-NOV-2015
# Last Modified = 4th-NOV-2015 1600 hours
# Pakistan !!!
#set -x

#SRV="$1"
SRV1="$1"
DATE=`date`

STATUS_HOLDER="/tmp/$SRV1.txt"
touch $STATUS_HOLDER

# COMPANY NAME
COMPANY="ZAIB"

# Hostname
HOSTNAME=`hostname`

# KANNEL SMS Gateway Info
KANNELURL="KANNELIP:13013"
KANNELID="kannel"
KANNELPASS="kannelpass"
CELL1="03333021909"

# GMAIL ACCOUNT INFORMATION AND RELATED ....
MAILER="/temp/sendEmail-v1.56/sendEmail"
TO1="aacable at hotmail dot com"
GMAILID="YOURGMAILID@gmail.com"
GMAILPASS="YOURGMAILPASSWORD"
MAILBODYDOWN="$SRV1 DOWN"
MAILBODYUP="$SRV1 UP"
MAILSUBJECTDOWN="$COMPANY ALERT: $HOSTNAME - $SRV1 is now DOWN @ $DATE"
MAILSUBJECTUP="$COMPANY INFO: $HOSTNAME - $SRV1 is now UP @ $DATE"


# Colors Config  . . . [[ JZ . . . ]]
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"
OS="1"
osver=`cat /etc/issue |awk '{print $1}'`

# OS checkup for UBUNTU
if [[ $osver == Ubuntu ]]; then
echo -e "$COL_GREEN OS = Ubuntu $COL_RESET"
set OS="Ubuntu"
OSPKG="apt-get install -y chkconfig"

else

echo -e "$COL_GREEN OS = CENTOS $COL_RESET"
set OS="CENTOS"
OSPKG="yum -y install chkconfig"
fi

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

# Check if no service name is given
if [ "$SRV1" == "" ]; then
echo -e "$COL_RED No service name have been provided. $COL_RESET"
echo "Usage exmaple:"
echo -e "/temp/checksrv.sh mysqld"
echo "OR"
echo -e "/temp/checksrv.sh (Depend on your OS deployment)"
echo
exit 0
else

# Check if CHKCONFIG command is installed or not.
CHK=`which chkconfig`
if [ "$CHK" == "" ]; then
echo -e "$COL_RED CHKCONFIG command is not installed.
Please install it with following command

$OSPKG $COL_RESET"
exit 0
else

# Check if service is installed / valid or not
CHKSRV=`chkconfig | grep -w $SRV1`
if [ "$CHKSRV" == "" ]; then
echo -e "$COL_RED NO SERVICE is INSTALLED WITH $SRV1 NAME. Exiting ...$COL_RESET"
exit 0
else

#########################################
############## IF ALL OK, PROCEED FURTHER
#########################################

# Query Service UPTIME
QUERYSRVUPTIME=`ps -eo "%U %c %t" |grep "$SRV1" |grep -v grep| grep root`
uptime=`echo $QUERYSRVUPTIME |awk '{ print $NF }'`

SERVICE1="$SRV1"
SUBJECT="ALERT: $SRV1 is Down..."

# SMS Msgs test for up n down
MSG_UP="$COMPANY Info:

$HOSTNAME - $SERVICE1 is now UP @ $DATE.
$SRV1 UPTIME is $uptime.
Powered by Syed.Jahanzaib"
fi

MSG_DOWN="$COMPANY Alert:

$HOSTNAME - $SERVICE1 is now DOWN @ $DATE. Trying to restarting it. wait 1 mnt for next result.

Powered by Jz"

##### CHECK FOR SERVICE STATUS

for SRVCHK in $SERVICE1
do
PID=$(pgrep $SERVICE1)
if [ "$PID" == "" ]; then
echo -e "$COL_RED $SRVCHK is down $COL_RESET "
if  [ $(grep -c "$SRVCHK" "$STATUS_HOLDER") -eq 0 ]; then
echo -e "$COL_RED ALERT: $SERVICE1 is down at $(date) / trying to restart and SENDING SMS and EMAIL....$COL_RESET"
echo "$MSG_DOWN" > /tmp/$SERVICE1_down.sms

# Sending DOWN SMS via KANNEL
cat /tmp/$SERVICE1_down.sms | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-

# Sending DOWN alert EMAIL via GMAIL
$MAILER -t $TO1 -u "$MAILSUBJECTDOWN" -s smtp.gmail.com:587 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o tls=yes -o message-file=/tmp/$SERVICE1_up.sms

# Start $SERVICE1 service if found down
service $SERVICE1 start
echo "$SRVCHK" >> $STATUS_HOLDER
fi

else
echo -e "$COL_GREEN $SRVCHK is alive with Uptime of $uptime
and its PID are as follows... $COL_RESET  \n$PID"

# IF Service found UP send SMS ONE TIME
if  [ $(grep -c "$SRVCHK" "$STATUS_HOLDER") -eq 1 ]; then
echo -e "$COL_GREEN INFO ALERT : $SERVICE1 is UP at $(date)
$SRV1 Uptime is $uptime
SENDING SMS and EMAIL.... $COL_RESET"
echo "$MSG_UP" > /tmp/$SERVICE1_up.sms

# Sending UP SMS via KANNEL
cat /tmp/$SERVICE1_up.sms | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
sed -i "/$SRVCHK/d" "$STATUS_HOLDER"

# Sending UP alert EMAIL via GMAIL
$MAILER -t $TO1 -u "$MAILSUBJECTUP" -s smtp.gmail.com:587 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o tls=yes -o message-file=/tmp/$SERVICE1_up.sms


fi
fi
done
fi
fi

USAGE:

/temp/checksrv.sh mysql
#OR
/temp/checksrv.sh squid

As showed in the image below …

SMS RESULT


cmd_details

EMAIL RESULTS:

FOR EMAIL ALERTS,

2- Download sendEmail tool to send email alerts

Install sendEmail Tool

tar zxvf sendEmail-v1.56.tar.gz
cd sendEmail-v1.56/

ADD SUPPORTING LIBRARY

for ubuntu

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

for centos

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

 

EMAIL CONFIGURATION AND SAMPLE RESULTS OF RECEIVING

Try to send email using command line , make sure you fill the variables with your original values like mail address password etc: Example


/temp/sendEmail-v1.56/sendEmail -t $TO1 -u "Test Email" -s smtp.gmail.com:587 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o tls=yes -m "hi"

 

MAIL1

MAIL2

SCHEDULE the SCRIPT in CRON:

Open crontab in editor

crontab -e

Now add following

# Run CHECK SERVICE script after very 5 minutes
*/5 * * * * /temp/checksrv.sh mysqld
OR
*/5 * * * * /temp/checksrv.sh mysql

SAVE and Exit!


 

Regard’s

Syed Jahanzaib

November 24, 2015

Quick Note: Limit interface total bandwidth by Queue Tree

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

1

Requirement:

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

Use following.


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

/queue tree

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


 

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

Regard’s
Syed Jahanzaib

November 19, 2015

Changeip.com DDNS Bash Script for Linux

Filed under: Linux Related — Tags: , , , — Syed Jahanzaib / Pinochio~:) @ 10:17 AM

changeipzaib-linux-choice

Posting for personnel reference:

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

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

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

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

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

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

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

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

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

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

# END
Older Posts »

The Silver is the New Black Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 3,165 other followers