Syed Jahanzaib Personal Blog to Share Knowledge !

November 25, 2016

Mikrotik: Switching between interface

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

f

NOT FOR GENERAL PUBLIC

SHARING IT FOR PERSONAL REFERENCE


Following is an script that switches connectivity between two interfaces (usually wan).

Example: ISP x have provided internet connectivity via fiber link . as a backup / redundancy link ISP have provided second fiber line. Both link have same ip address with same gateway. There are other ways too , this is just one way of achieving task. it can be customized in many ways like forcing specific hosts to be monitored by ping and act accordingly , or by having bridge etc.

IP address example:

in /ip address >>>

sfp1 = 10.0.0.1 (with comments “PRIMARY-SFP1”)
[remains enabled until next status changed]

sfp2 = 10.0.0.1 (with comments “SECONDARY-SFP2”)
[remains enabled until next status changed]

The script will do following.

Check the SFP1 Status, if it does not found “linkok” reply, it will log event, send email/sms alert to admin, and switch to SFP2 port by enabling IP of SFP2 [and Disable ip on SFP1]

On next run, if it found SFP1 link ok, then it will log event, send email/sms alert to admin, and switch back to SFP1 port by enabling IP of SFP1 and disable ip on SFP2.


# Mikrotik SPF Link monitoring SCRIPT with optional Email and SMS Alert,
# We are using local KANNEL as SMS gateway and GMAIL as email sender
# by Syed Jahanzaib
# https://aacable.wordpress.com
# Email : aacable at hotmail dot com
# Script Last Modified : 25-NOV-2016 / 1400 hours

# PRIMARY FIBER LINK
:local INT "sfp1"
# SECONDARY BACKUP FIBER LINK
:local INT2 "sfp2"
:local i 0;
:local F 0;
:local date;
:local time;
:global sub1 ([/system identity get name])
:global sub2 ([/system clock get time])
:global sub3 ([/system clock get date])
:set date [/system clock get date];
:set time [/system clock get time];
:local cell1 "03333021909"
:global FIBERnetstatus;
:global FIBERnetlastchange;
:global FIBERIP;

# Company Name, do not use spaces in it
:local COMPANY "ZZZ"

# Setting GMAIL config
:local sub1 ([/system identity get name])
:local sub2 ([/system clock get date])
:local sub3 ([/system clock get time])
:local TO1 "RECIPIENT-1@hotmail.com"
:local gmailid "YOUR-GMAIL-ID@gmail.com"

#If you dont have kannel sms gateway ignore this.
:local KURL "http://10.0.0.1:13013/cgi-bin/sendsms"
:local KID "kannel"
:local KPASS "KANNEL-PASS"

# SMS DOWN status Msg format for Kannel SMS gateway (donot use spaces in it)
:local MSGDOWNSMS "$COMPANY+FIBER+ALERT:%0A$INT+fiber+is+now+DOWN.%0ASwitching+to+$INT2+backup+fiber+link"
# SMS UP status Msg format for Kannel SMS gateway (donot use spaces in it)
:local MSGUPSMS "$COMPANY+FIBER+INFO:%0A$INT+fiber+is+now+UP.%0ASwitching+back+to+$INT"

# EMAIL Msg format for FIBER DOWN
:local MSGDOWNEMAIL "$COMPANY FIBER ALERT: $INT fiber is now DOWN at $sub1 $sub2 $sub3 . Switching to $INT2 backup link. Please Verify it."
# EMAIL Msg format for FIBER UP
:local MSGUPEMAIL "$COMPANY FIBER INFO: $INT fiber is now UP at $sub1 $sub2 $sub3 . Switching back to $INT primary link. Please Verify it."
# LOG error
:local DOWNLOG1 "$COMPANY FIBER ALERT: $INT fiber is now DOWN at $sub1 $sub2 $sub3 . Switching to $INT2 backup link. Please Verify it."
:local UPLOG1 "$COMPANY FIBER INFO: $INT fiber is now UP at $sub1 $sub2 $sub3 . Switching back to $INT primary link. Please Verify it"

######################################
########## Start the SCRIPT ###############
########## DONOT EDIT BELOW ############
######################################

local link;
/interface ethernet cable-test $INT once do={
:set link $"status";
};

:if ($link != "link-ok") do={
:log error "$INT SFP DOWN"

:if (($FIBERnetstatus="UP")) do={
:set FIBERnetstatus "DOWN";

# Also add status in global variables to be used as tracking
:set date [/system clock get date];
:set time [/system clock get time];
:set FIBERnetlastchange ($time . " " . $date);
##################################################
####### FOR DOWN STATUS, CHANGE THE RULES ########
##################################################

# If the link is down, then LOG info and warning in Mikrotik LOG window [Zaib]
:log error "$DOWNLOG1"

# DOWN ACTION , shifting to SFP2 , backup link
/ip address set disabled=yes [find comment="PRIMARY-SFP1"]
/ip address set disabled=no [find comment="BACKUP-SFP2"]

# Adding delay so gateway should be reachable properly
:delay 5s;

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

# "Emailing the DOWN status. . . "
/tool e-mail send to=$TO1 subject="$MSGDOWNEMAIL" start-tls=yes body="$MSGDOWNEMAIL"

# Send SMS the DOWN status via KANNEL
/tool fetch url="$KURL\?username=$KID&password=$KPASS&to=$cell1&text=$MSGDOWNSMS"

##################################################
####### FOR UP STATUS, CHANGE THE RULES ########
##################################################

} else={:set FIBERnetstatus "DOWN";}
} else={
:if (($FIBERnetstatus="DOWN")) do={

:set FIBERnetstatus "UP";

# If link is UP, then LOG info and warning in Mikrotik LOG window [Zaib]
:log warning "$UPLOG1"

# UP ACTION , shifting back to SFP1
/ip address set disabled=no [find comment="PRIMARY-SFP1"]
/ip address set disabled=yes [find comment="BACKUP-SFP2"]

# Adding delay so gateway should be reachable properly
:delay 5s;
:global gmailsmtp
:set gmailsmtp [:resolve "smtp.gmail.com"];

# "Emailing the UP status. . . "
/tool e-mail send to=$TO1 subject="$MSGUPEMAIL" start-tls=yes body="$MSGUPEMAIL"

# Send SMS via KANNEL Gateway
/tool fetch url="$KURL\?username=$KID&password=$KPASS&to=$cell1&text=$MSGUPSMS"

:set date [/system clock get date];
:set time [/system clock get time];
:set FIBERnetlastchange ($time . " " . $date);

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

Advertisements

November 22, 2016

Query Windows SAP Server Instance status via Linux

Filed under: Linux Related, Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 3:37 PM

sap.jpg

linux_pengiun

Background:

We are using SAP ECC6 on Windows 2008 R2 64bit server in our data center.
The landscape is as below …

  • PRODUCTION
  • DEV [with 2 instances to support our and parent company as well]
  • Q.A  [with 2 instances to support our and parent company as well]
  • DATA GUARD [For PRD Backup/Replication]

Problem:

During the deployment , we were having strange issue that sometimes any single instance at DEV or QAS stops and we get to know it quite late as it was oftenly happening in saturday sundays when no one is available at data center.


Solution:

Therefore I made the following Linux bash script which performs the following functions >

  1. Check Server PING for its availability
  2. Check ORACLE and SAP services and add there name and status in the INFO
  3. Check SAP Instance using sapcontrol command Using WINEXE (Linux utility to execute command on remote windows pc. If it donot find 3 GREEN status in the instance query, then SEND email / SMS to admin.
  4. At next run, check if service/instance is still down, and the alert is already been sent, do not repeat the alert sending until next status changes.
  5. At next run, if the service/instance is UP, then send alert.

Requirements:

  1. Linux (any flavor, I used Ubuntu 12.4 in this guide)
  2. Winexe (Linux utility to execute command on remote windows pc via Linux CLI)
  3. NET RPC tools to check remote windows services via Linux CLI
  4. sendEMAIL tool (To send email using your GMAIL account, you can use your own app too)
  5. KANNEL SMS Gateway (To send sms, you can change it , or disable it if not required)

TO DO LIST


the SCRiPT ~

#!/bin/bash
# Script to check windows based SAP SERVER PING / SERVICES and INSTANCE status via linux query
# and send sms/email accordingly using NET RPC / winexe / sendEmail / Kannel
# Created by SYED JAHANZAIB / aacable at hotmail dot com
# CREATED: 21-NOV-2016
# LAST REVISION: 26-NOV-2016
#set -x

ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"
COL_YELLOW=$ESC_SEQ"33;01m"
DATE=`date`

# TEMPORARY FOLDER NAME
TEMP="temp"

# Checking if $TEMP folder is previously present or not [To hold all status]. . .
{
if [ ! -d "/$TEMP" ]; then
echo
echo -e "$COL_RED /$TEMP folder not found, Creating it so all TEMPORARY STATUS / HOLDERS will be placed there . . . $COL_RESET"
mkdir /$TEMP
else
echo > /dev/null
fi
}

# SAP-SERVER RELATED INFO
SAPSRVIP="10.0.0.1"
SAPSRVNAME="SAP - DEV-0"
DOMAIN="DOMAIN-OR-WORKGROUP"
ADMINID="ADMINID"
ADMINPASS="PASSWORD"
# You must change following path to point sapcontrol.exe
COMPATH="E:\usr\sap\R3d\DVEBMGS00\exe\sapcontrol"
WINEXE="/usr/sbin/winexe"
# If you have multiple instance, you may change it as required
INSTANCE="0"
SRV1="OracleServiceR3D"
SRV2="OracleServiceODV"
SRV1_STATUS1="/$TEMP/$SAPSRVIP.$INSTANCE.$SRV1.status1.txt"
SRV1_STATUS2="/$TEMP/$SAPSRVIP.$INSTANCE.$SRV1.status2.txt"
SRV2_STATUS1="/$TEMP/$SAPSRVIP.$INSTANCE.$SRV2.status1.txt"
SRV2_STATUS2="/$TEMP/$SAPSRVIP.$INSTANCE.$SRV2.status2.txt"

# COMPANY NAME
COMPANY="-ZAIB-"
FOOTER="Powered by $COMPANY SYS ADMIN"

# KANNEL SMS Gateway Info to send SMS if required
KANNELURL="KANNEL-IP:13013"
KANNELID="kannel"
KANNELPASS="PASSWORD"
# ZAIB CELL
CELL1="03333021909"

# GMAIL DETAILS to send EMAIL alert
GMAILID="YOUR-GMAIL-ID@gmail.com"
GMAILPASS="GMAIL-PASS"
# Add recipient email address below
ADMINMAIL1="syed.jahanzaib@ZAIB"
SENDMAILAPP="/temp/sendEmail-v1.56/sendEmail"

# Various holders to store different Status
SENTSMSRESULT="/$TEMP/$SAPSRVIP.$INSTANCE.txt"
STATUS_HOLDER="/$TEMP/$SAPSRVIP.$INSTANCE.status.txt"
SRV_HOLDER="/$TEMP/$SAPSRVIP.$INSTANCE.srvstatus.txt"
SRV_HOLDER_HEADER="$SAPSRVNAME Services Status ..."
UPMSG="/$TEMP/$SAPSRVIP.$INSTANCE.up.sms"
DOWNMSG="/$TEMP/$SAPSRVIP.$INSTANCE.down.sms"
SAPINSTSTATUS1="/$TEMP/$SAPSRVIP.$INSTANCE.inst-try1.txt"
SAPINSTSTATUS2="/$TEMP/$SAPSRVIP.$INSTANCE.inst-try2.txt"
> $SAPINSTSTATUS1
> $SAPINSTSTATUS2
echo "" > $SRV_HOLDER
touch  $DOWNMSG
> $DOWNMSG
> $UPMSG
touch $STATUS_HOLDER

# Messages which will be sent via email/sms
MSG_UP_SUB="INFO: $SAPSRVNAME - $SAPSRVIP -  Instance $INSTANCE Restored"
MSG_DOWN_SUB="ALERT:$SAPSRVNAME - $SAPSRVIP -  Instance $INSTANCE IS DOWN"
MSG_SRV_DOWN_SUB="ALERT: $SAPSRVNAME - $SAPSRVIP -  One or More Services are Down DOWN"

#######################
### PING SECTION STARTS
#######################

PING_DOWN_MSG="ALERT: $AGPSRVNAME  $SAPSRVIP - PING COMMUNICATION FAILED @ $DATE"
PING_UP_MSG="INFO: $AGPSRVNAME  $SAPSRVIP - PING COMMUNICATION RESTORED - OK @ $DATE"
PING_NORMAL_MSG="INFO: $AGPSRVNAME  $SAPSRVIP - PING COMMUNICATION - OK @ $DATE"
PING_STATUS_HOLDER="/$TEMP/$SAPSRVIP.ping.status"
FINAL_PING_STATUS="1"
# PING Attempts
PING_ATEMPTS="5"

# Check if SERVER is accessibel or not, then inform if sms/email is already been sent / zaib
## IF PING FAILS  then send sms and email, IF NOT ALREAY SENT
echo -e "$COL_YELLOW>Checking PING response at $SAPSRVNAME $SAPSRVIP ... $COL_RESET"
if [[ $(ping -q -c $PING_ATEMPTS $SAPSRVIP) == @(*100% packet loss*) ]]; then
echo ""
FINAL_PING_STATUS="DOWN"
else
echo ""
FINAL_PING_STATUS="UP"
fi

echo $SRV_HOLDER_HEADER >> $SRV_HOLDER

##########################
### PING SECTION ENDS HERE
##########################

# If temporary status holder is not present , then create it,
# forumla is being applied to prevent repeated attempt of file creation / zaib
if [ ! -f $STATUS_HOLDER ]; then
echo -e "Creating Status Holder for first time usage"
touch $STATUS_HOLDER
fi

#######################################
#### QUERY SERVICES SECTION STARTS HERE
#######################################

# $SRV - 1 - CHECK
echo -e "$COL_YELLOW>Checking $SRV1 Service status at $SAPSRVNAME $SAPSRVIP ... Check#1 $COL_RESET"
# IF SAP SERVICE QUERY result is not running, then UPDATE its status accordingly
net rpc service status $SRV1 -I $SAPSRVIP --user=$DOMAIN/$ADMINID%$ADMINPASS |grep running > $SRV1_STATUS1
sleep 5
echo -e "$COL_YELLOW>Checking $SRV1 Service status at $SAPSRVNAME $SAPSRVIP ... Check#2 $COL_RESET"
net rpc service status $SRV1 -I $SAPSRVIP --user=$DOMAIN/$ADMINID%$ADMINPASS |grep running > $SRV1_STATUS2
QSRV1_STATUS1=`cat $SRV1_STATUS1 | grep -o running | wc -l`
QSRV1_STATUS2=`cat $SRV1_STATUS2 | grep -o running | wc -l`
if [[ $QSRV1_STATUS1 -gt 0 ]] && [[ $QSRV1_STATUS1 -gt 0 ]]; then
echo "$SRV1 UP" >> $SRV_HOLDER
else
echo "ALERT: $SRV1 Service is DOWN ...."
echo "$SRV1 DOWN" >> $SRV_HOLDER
fi

# $SRV - 2 - CHECK
# IF SAP SERVICE QUERY result is not running, then UPDATE its status accordingly
echo -e "$COL_YELLOW>Checking $SRV2 Service status at $SAPSRVNAME $SAPSRVIP ... Check#1 $COL_RESET"
net rpc service status $SRV2 -I $SAPSRVIP --user=$DOMAIN/$ADMINID%$ADMINPASS |grep running > $SRV2_STATUS1
sleep 5
echo -e "$COL_YELLOW>Checking $SRV2 Service status at $SAPSRVNAME $SAPSRVIP ... Check#2 $COL_RESET"
net rpc service status $SRV1 -I $SAPSRVIP --user=$DOMAIN/$ADMINID%$ADMINPASS |grep running > $SRV2_STATUS2
QSRV2_STATUS1=`cat $SRV2_STATUS1 | grep -o running | wc -l`
QSRV2_STATUS2=`cat $SRV2_STATUS2 | grep -o running | wc -l`
if [[ $QSRV2_STATUS1 -gt 0 ]] && [[ $QSRV2_STATUS1 -gt 0 ]]; then
echo "$SRV2 UP" >> $SRV_HOLDER
else
echo "ALERT: $SRV2 Service is DOWN ...."
echo "$SRV2 DOWN" >> $SRV_HOLDER
fi

echo "" >> $SRV_HOLDER

# MESSAGES
# SMS and email msg fromat for up n down
NORMSG="$SAPSRVNAME - Oracle Services and SAP instance $INSTANCE QUERY is OK !- All Seems OK @ $DATE!"
LOWMSG="ALERT: $SAPSRVNAME - $SAPSRVIP -  Instance $INSTANCE is DOWN @ $DATE"
OKMSG="INFO: $SAPSRVNAME - $SAPSRVIP -  Instance $INSTANCE is UP now @ $DATE"

##########################################################
#### CHECK FOR RUNNING SERVICES LIKE ORACLE and others ...
##########################################################
CHKGSRVDOWNSTATUS=`cat $SRV_HOLDER | grep -o DOWN | wc -l`
if [[ $CHKGSRVDOWNSTATUS -gt 0 ]]; then
echo -e "$COL_YELLOW >PING STATUS = $FINAL_PING_STATUS"
echo "PING STATUS = $FINAL_PING_STATUS" >> $DOWNMSG
echo "" >> $DOWNMSG
echo ""
echo -e "$COL_RED >ALERT: FOLLOWING SERVICES ARE DOWN ... $COL_RESET"
cat $SRV_HOLDER
NORMSG="$SAPSRVNAME - Oracle Services seems to be $COL_RED DOWN $COL_RESET BUT SAP instance $INSTANCE QUERY is $COL_GREN OK $COL_RESET ! @ $DATE!"

echo "ALERT: FOLLOWING SERVICES ARE DOWN ..." >> $DOWNMSG
cat $SRV_HOLDER >> $DOWNMSG

else
echo -e "$COL_GREEN>INFO: FOLLOWING SERVICES ARE UP at $SAPSRVNAME $SAPSRVIP ... $COL_RESET"
cat  $SRV_HOLDER
fi

#############################################################################
#############################################################################
###
### CHECK SAP INSTANCE FOR 3 GREEN COUNTS and inform if alert is already sent
###
#############################################################################
#############################################################################

# IF SAP INSTANCE QUERY result does not contains 3 GREEN, then send sms and email
# To prevent FALSE alaram, I have added double check : ) HURAAAH, Allah Shuker / zaib
echo -e "$COL_YELLOW> Testing SAP Instance No $INSTANCE ... Check#1 $COL_RESET"
$WINEXE --user=$DOMAIN/$ADMINID%$ADMINPASS //$SAPSRVIP "$COMPATH -nr $INSTANCE -function GetProcessList" > $SAPINSTSTATUS1
sleep 5
echo -e "$COL_YELLOW> Testing SAP Instance No $INSTANCE ... Check#2 $COL_RESET"
$WINEXE --user=$DOMAIN/$ADMINID%$ADMINPASS //$SAPSRVIP "$COMPATH -nr $INSTANCE -function GetProcessList" > $SAPINSTSTATUS2
sleep 1
CHKGREENSTATUS1=`cat $SAPINSTSTATUS1 | grep -o GREEN | wc -l`
CHKGREENSTATUS2=`cat $SAPINSTSTATUS2 | grep -o GREEN | wc -l`

if [[ $CHKGREENSTATUS1 -lt 3 ]] && [[ $CHKGREENSTATUS2 -lt 3 ]]; then
if  [ $(grep -c "TEMP" "$STATUS_HOLDER") -eq 1 ]; then
echo -e "$COL_RED>ALERT: $LOWMSG$COL_RESET"
echo "$LOWMSG" >> $DOWNMSG
echo "SMS/Email for DOWN have already been sent"

fi
fi

if [[ $CHKGREENSTATUS1 -lt 3 ]] && [[ $CHKGREENSTATUS2 -lt 3 ]]; then
if  [ $(grep -c "TEMP" "$STATUS_HOLDER") -eq 0 ]; then
echo  "ALERT: $LOWMSG
SENDING DOWN SMS/Email .... "
echo "$LOWMSG" > $DOWNMSG
echo "" >> $DOWNMSG
echo "PING STATUS = $FINAL_PING_STATUS" >> $DOWNMSG
cat $SRV_HOLDER >> $DOWNMSG
echo "" >> $DOWNMSG
echo "$FOOTER" >> $DOWNMSG
echo "TEMP" > $STATUS_HOLDER

# Sending DOWN Alert SMS/EMAIL
cat $DOWNMSG | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
$SENDMAILAPP -u "$MSG_DOWN_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID  -o message-file=$DOWNMSG -o message-content-type=text

fi
else

# SETTING NEW MSG
echo -e "$COL_GREEN $NORMSG ... $COL_RESET"
if  [ $(grep -c "TEMP" "$STATUS_HOLDER") -eq 1 ]; then
echo -e "$OKMSG
SENDING OK UP SMS/Email .... "
echo $MSG_UP_SUB > $UPMSG
echo "" >> $UPMSG
echo "PING STATUS = $FINAL_PING_STATUS" >> $UPMSG
cat $SRV_HOLDER >> $UPMSG
echo "" >> $UPMSG
echo "$FOOTER" >> $UPMSG
sed -i "/TEMP/d" "$STATUS_HOLDER"
# Sending UP INFO SMS/EMAIL
cat $UPMSG | curl "http://$KANNELURL/cgi-bin/sendsms?username=$KANNELID&password=$KANNELPASS&to=$CELL1" -G --data-urlencode text@-
$SENDMAILAPP -u "$MSG_UP_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID  -o message-file=$UPMSG -o message-content-type=text

fi
fi

# Script Ends Here
# Syed Jahanzaib / aacable @ hotmail . com
# http:// aacable . wordpress . com

Result:

Run the bash script which we created.

CLI RESULT:

1-all-ok

2-all-down

Email Result:

1-down

2-up

SMS  Result:

screenshot_2016-11-22-14-21-49


~ TIPS  ‘N’  TRICKS ~

To install sendEmail tool (using GMAIL account), use following

First install Supporting Libraries
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

Now Download and unzip the sendEmail tool

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

To test use following

/temp/sendEmail-v1.56/sendEmail -t DESTINATIONMAIL@hotmail.com -u "Test Email" -s smtp.gmail.com:587 -xu YOURGMAILID@gmail.com -xp GMAILPASS -f YOURGMAILID -o tls=yes -m "hi"
Nov 22 15:16:46 linux sendEmail[12561]: Email was sent successfully!

to install NET tools/command on Ubuntu 12.4 [zaib]

 sudo apt-get install samba-common

to install WINEXE on Ubuntu 12.4 [zaib]

mkdir /temp && cd /temp
apt-get install python-all-dev
wget http://downloads.sourceforge.net/project/winexe/winexe-1.00.tar.gz
tar xzvf winexe-1.00.tar.gz
cd winexe-1.00/source4/
./autogen.sh
./configure
make basics bin/winexe
./bin/winexe -V
# copy winexe binary to /usr/sbin   so that it can be called from any path
# cp /temp/winexe-1.00/source4/bin  /usr/sbin

To query Remote SAP Server instance status use following command

*Make sure you change the path of sapcontrol path/folder to match with your local installation folder structure

# Remote Server with workgroup/standalone
/temp/winexe-1.00/source4/bin/winexe -U ADMINID%PASSWORD //10.0.0.1 "E:\usr\sap\ECC\DVEBMGS00\exe\sapcontrol -nr 0 -function GetProcessList"

# Remote Server with DOMAIN base authentication
winexe --user=DOMAINNAME/ADMINID%PASSWORD //10.0.0.1 "e:\usr\sap\R3d\DVEBMGS00\exe\sapcontrol -nr 0 -function GetProcessList"

To query Remote windows services status , use following command

install the require tool by following

sudo apt-get install samba-common

List all services on remote windows server by following

net rpc service list -I 10.0.0.1 -U DOMAIN/ADMINID%PASSWORD

now query the service STATUS with following

net rpc service status OracleServiceR3D -I 10.0.0.1 -U DOMAIN/ADMINID%PASSWORD

net rpc service status OracleServiceR3D -I 10.0.0.1 -U DOMAIN/ADMINID%PASSWORD | grep running

to stop or start

net rpc service stop SERVICENAME -I IPADDRESS -U USERNAME%PASSWORD
net rpc service start SERVICENAME -I IPADDRESS -U USERNAME%PASSWORD

Regard’s
SYED JAHANZAIB

November 13, 2016

mysql unable to connect with remote mysql host/database

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

If you are trying to connect with remote mysql database to perform remote management or connectivity with some web app to add data into the db , and sees the following error

Connection failed: Access denied for user ‘zaib’@’x.x.x.x’ (using password: YES)

OR

Host ‘xxx.xx.xxx.xxx’ is not allowed to connect to this MySQL server

Then you need to grant access to the user from any hostname. This is how you add new privilege from mysql command line.

NOTE: Please beware that this is for just example purpose only , and you MUST take good security measures like Strong Password, and allow only specific IP address to access etc.


When you setup the MySQL server on Linux machine, it sets MySQL Server to accept connection from local IP only (i.e 127.0.0.1).  We need to make modification on this.
If wewant to allow connections from any IP, we need to set the bind-address IP to 0.0.0.0,

[for Ubuntu]

Edit /etc/mysql/my.cnf 

nano /etc/mysql/my.cnf 

Search ‘bind-address’

 bind-address=127.0.0.1

& change it to

 bind-address=0.0.0.0

 

Open mySQL , and issue following commands

mysql -uroot -pMYSQLPASSWORD
CREATE USER 'zaib'@'localhost' IDENTIFIED BY 'zaib1234';
GRANT ALL PRIVILEGES ON *.* TO 'zaib'@'localhost' WITH GRANT OPTION;
CREATE USER 'zaib'@'%' IDENTIFIED BY 'zaib1234';
GRANT ALL PRIVILEGES ON *.* TO 'zaib'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit

 

Restart mySQL service ..

service mysql restart

 


Sample PHP page to test Remote Mysql connection

Now you can test it with sample php page. change the host name of remote mysql server, and the id , password we just created in above steps.

<?php
$servername = "remote.mysql.host.ip.or.name";
$username = "zaib";
$password = "PASSWORD";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully. Hurraahhhhh/Alhamdolillah";
?>

Regard’s
Syed Jahanzaib

 

November 8, 2016

Personnel Short Notes for Cisco Switches/Routers


This post contains some personnel short notes on various configuration related to Cisco Switches/Routers. I wrote this post so that I can find my day to day usage commands from this centralized location.

Regard’s
Syed Jahanzaib

 


> Method#0 – Erase setting while you are have already access on the switch

write erase
delete flash:vlan.dat
reload

After this switch will reload its OS, and will come back with default switch settings. Recommended to use Serial console cable.


> Method#1 – Reset Everything – Factory Default

Following is a quick method to reset Cisco switch to factory default settings. This method can also be used to recover password.

Requirements:

  • Cisco Switch
  • Console Cable
  • PC/Laptop with Serial Port

 

  • Connect your console cable from the switch Console port to PC/Laptop serial Port.
  • Open the Hyper Terminal application, and select settings as per your hardware. Following is configuration for Cisco 3750 Model.
    Bits per second: 115200
    Data bits: 8
    Parity: None
    Stop bits: 1
    Flow control: Xon / Xoff
  • Different switches connect with different Bits per Second setting . For Cisco 2950 Model try to lower it at 9600.

hyperterminal.PNG

  • Power Off the switch / Now hold the MODE button on the switch and power ON the switch.

sw-power.jpg

  • Once the switch initialize itself (may take 1 minute for 3750, and for 2950 it generally requires 5-6 seconds to hold mode button. ), This will interrupt the boot process before the Flash file system can initialize, and after a short while (continue holding the “mode” button) you will see the following prompt:

sw-1

Once you see the

The password-recovery mechanism is enabled.

you can release the Mode button.

  • Press enter few times to make sure you get the prompt. Now issue following commands to initialize flash and delete files which contains the switch configuration

flash_init
del flash:config.text
del flash:vlan.dat

Th eoutput may look a like following

switch:

switch: del flash:config.text
Are you sure you want to delete "flash:config.text" (y/n)?y
File "flash:config.text" deleted

switch: del flash:vlan.dat
Are you sure you want to delete "flash:vlan.dat" (y/n)?y
File "flash:vlan.dat" not deleted -- no such file or directory

switch:

Once its done, you may continue booting the switch which will allow you to do any configuration of your choice.

boot

This will continue booting the & after a while it will ask you following

Would you like to enter the initial configuration dialog? [yes/no]:

Type no and continue with below ..


Adding IP to default Vlan 1 interface

To add ip use following

en
config t
hostname zaib-switch
interface vlan 1
ip address 101.11.100.1 255.0.0.0
ip default-gateway 101.11.100.255
# Following is important, as vlan1 may be in shut status after ip config, so enable it
no shut
exit
exit
copy running-config startup-config
# When it will ask "Destination filename [startup-config]?" just press ENTER
wr

Connect ethernet cable to the switch port and see the ping result.

ping.PNG

Now you will be able to connect with the switch using IP.

Cisco configuration assistant software is the best GUI tool to configure the switch with ease and it will save you from remembering all the commands. Although command is more powerful in most cases but still GUI is feasible for most beginners.

cisco-network-gui

You can download Cisco Network Assistant and Hyper-Terminal it from my google drive.

https://drive.google.com/drive/folders/0B8B_P2ljEc2xQlpvRUQ2QWVfR0E


TIPS:


General Commands:

Show ALL Interfaces Status

at ENABLE section, use this command to get all ports status

show interfaces status


To show Ip addresses and interface status

show ip interface brief

To show vlan details (via enable mode)

show vlan

Add ENABLE section Password

en
config t
enable secret zaib1234
exit
wr


Reboot Switch

reload


Port is Down/Shutdown / Vlan1 is administratively down, line protocol is down

en
config t
interface vlan 1
no shut


Enable TELNET access

en
config t
line vty 0 15
transport input telnet
password zaibtelnetpass
login
exit
exit
wr


Enable SSH access

*** Set hostname and domain-name
config t
hostname cisco-switch
ip domain-name zaib.com

*** Generate the RSA Keys
crypto key generate rsa
“How many bits in the modulus [512]: 1024”

*** Set Up the Line VTY configurations
transport input ssh
login local
password zaib1234
exit

*** Set the console line
line console 0
logging synchronous
login local

*** Create the username password
config t
username zaib password zaib1234
enable secret zaib1234
service password-encryption


Method#2 – Password Recovery Only:
(While Keeping existing running configuration intact)

  • Connect Hyperterminal with the switch using console cable. [as mentioned in the beginning of this guide]
  • Power ON the switch while pressing mode button, one you see the “The password-recovery mechanism is enabled.”

More example for switch models:

sw-1

Now issue following commands one by one …

flash_init
dir flash:
rename flash:config.text flash:config.old
(The config.text file contains the password)

Now continue the boot process by following command

boot

When you see the following dialogue

Would you like to enter the initial configuration dialog? [yes/no]:

Enter n to abort the initial configuration dialog.

Now rename the config.old file to config.text so that we can get our existing settings restored , and still let us change the password

rename flash:config.old flash:config.text
Press enter when ask for destination file name

Now save the config in running-config so that switch must load all the settings on next boot

copy flash:config.text system:running-config
Press enter when ask for destination file name

Changing Password …

*** Overwrite the existing secret/password

en
conf t
enable secret zaib1234
enable password zaib12345

### Overwrite the existing vty password
line vty 0 15
password zaib1234

### Overwrite the existing console password
line con 0
password zaib1234
exit
exit
copy running-config startup-config
wr
DONE !

Some short notes for Cisco related command [added on 19-OCT-2017]


#SAVE Configuration
copy running-config startup-config
wr

#Enable interface
no shutdown
show ip route

#Reset running configuration

write erase
delete flash:vlan.dat
reload
show vlan br
show ip int brie
#To configure port 24 as TRUNK

enable
configure terminal
interface GigabitEthernet 1/0/1
switchport trunk encapsulation dot1q
switchport mode trunk

*** FIRST Create VLAN

en
conf t
vlan 1
name Default-Vlan
exit
vlan 2
name vlan2-users
exit
vlan 3
name vlan3-users
exit
interface vlan 1
ip address 192.168.254.1 255.255.255.0
interface vlan 2
ip address 192.168.2.1 255.255.255.0
interface vlan 3
ip address 192.168.3.1 255.255.255.0

(If range then use int range f0/1 - 15 )
interface GigabitEthernet 1/0/2
switchport mode access
switchport access vlan 2

interface GigabitEthernet 1/0/3
switchport mode access
switchport access vlan 3

#
en
conf t
show ip route
#OR#
show run | include ip route
ip route 0.0.0.0 0.0.0.0 192.168.254.2
# REMOVE IP ROUTE
en
conf t
no ip route 172.16.100.0 255.255.255.0 192.168.254.2
#---------------------------------------
#remove IP on interface
en
conf t
int vlan X
no ip address
OR
no ip address 192.x.x.x 255.255.255.0
#remove VLAN
en
conf t
no int vlan 24

Backup / Restore switch config from/to TFTP Server

Download any free TFTP Server like Solarwind TFTP , install it to your local Laptop/Desktop. Start it as showed below …

tftp

Make sure that switch and your TFTP can can communicate with each other.

Now from switch issue following command to backup to TFTP server.

copy running-config tftp

It will ask you to enter IP of TFTP server, enter the IP address where TFTP is running, example your Laptop/Desktop where you install the TFTP server.

tftp uploaded.JPG

Switch config file is uploaded successfully & can be viewed in c:\TFTP-Root folder.

To restore this config file to your switch, you can download it from the TFTP using following commands

copy tftp running-config

it will ask for TFTP server IP  & file name, enter details

Address or name of remote host []? 101.11.11.161
Source filename []? switch-confg
Destination filename [running-config]?
Accessing tftp://101.11.11.161/switch-confg...
Loading switch-confg from 101.11.11.161 (via Vlan1): !
[OK - 3946 bytes]

restore from tftp


Enable Logging to Remote SYS LOG server (liek syslog-ng)

login to switch terminal, and issue


logging 101.11.11.240
logging trap informaional

# to test log sending to log server
send log Hello World

Regard’s
Syed Jahanzaib

November 4, 2016

Windows batch files to get file/dir size in backup

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

batch file icon.png

Following are some references to create windows based batch file which performs backups and sends email using windows cmd functions. The task can be achieved by builtin or 3rd party backup applications, but most of the time , there is an Worm which always crawled in my mind and it forces me to do things oddly and above all strangely it somehow works amazingly good with the exact results I want!


Get File Size!

@echo off
rem *** This batch file will list file size ***
 setlocal enableextensions disabledelayedexpansion

rem Change the file name/location in below line
set "file=d:\zaib\setup.exe"

for %%z in ("%file%") do for /f "tokens=1,2" %%a in ('
 robocopy "%%~dpz." "%%~dpz." "%%~nxz" /l /nocopy /is /njh /njs /ndl /nc
 ') do if "%%~dz"=="%%~db" (
 echo "%%~z" : [%%a]
 ) else (
 echo "%%~z" : [%%a%%b] 
 )

Result:

1- file size.PNG


Get Folder Size!


@echo off

rem *** This batch file will list FOLDER size ***
setlocal enableextensions disabledelayedexpansion

set "folder=%~f1" & if not defined folder set "folder=%cd%"

set "size=" & for %%z in ("%folder%") do for /f "skip=2 tokens=2,3 delims=: " %%a in ('
robocopy "%%~fz\." "%%~fz\." /l /nocopy /s /is /njh /nfl /ndl /r:0 /w:0 /xjd /xjf /np
^| find ":"
') do if not defined size (
(for /f "delims=0123456789." %%c in ("%%b") do (break)) && (
set "size=%%a%%b"
) || (
set "size=%%a"
)
)

echo "%folder%" : [%size%]

Result:

2- folder size.PNG

 


 

Backup File Example:

I made following batch file long time ago which does the following

  1. Check for MAP drive , if not attache then reconnect it,
  2. If MAP drive is still not available , then break the script and send email to admin
  3. execute oracle exp command to export the DB into the map drive
  4. Delete files older then 15 days to prevent disk fill up
  5. email the result to the admin.

These are just for example only, just to give you an idea only

@echo off
rem # Syed Jahanzaib #
rem # ORACLE-DB SAS BACKUP SCRIPT BY zaib
rem #######################################################
rem Setting various Descriptions via environment variables
rem #######################################################
set dt=%date:~-4,4%%date:~-10,2%%date:~-7,2%
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2%__%ldt:~8,2%-%ldt:~10,2%
set mail-to="ADMINMAIL@GMAIL.COM"
set attachment=C:\backup\last-%ldt%.log
set srvname=ORACLE-DB-SAS.AGP1
set mail-subject=ORACLE-DB-SAS DB %ldt% Dump/Export Report by_Syed_Jahanzaib

break > %attachment%

if exist b:\ (
echo Map Drive is present. Hurraaahhhh zaib you got it Alhamdulillah
) ELSE (
net use B: \\agpinf03\datapark
)

if not exist b:\ (
cho Sorry unable to MAP Drive.
c:\backup\blat\blat.exe %attachment% -to %mail-to% -i %srvname% -s "ERROR UNABLE TO MAP DRIVE - PLEASE CHECK IT. NO BACKUP"
exit /b )

set logpath="B:\ORACLE-DB-sas"
set fname="%logpath%\ORACLE-DB-sas-daily-backup-%ldt%"
echo Executing Backup to DUMP ORACLE-DB-sas Database export Now ...
echo .

exp userid=SAS/ARORACLE-DBS file=%fname% direct=y COMPRESS=y

echo .
echo This script is made by AGP IS Dept. to export daily dump from ORACLE-DB system > %attachment%
echo Please ntoe that Files older then 15 days will be deleted from Fileserver DATAPARK folder %logpath% >> %attachment%
echo Database Export Done. now deleting files older then 15 days
echo .
echo Deleting B:\ORACLE-DB-sas\*.DMP files older then 15 Days from File Server.
echo ****** >> %attachment%
echo Last file name exported is >> %attachment%
forfiles -p "b:\ORACLE-DB-sas" -s -m *.dmp -d 0 -c "cmd /c dir @path" >> %attachment%
echo ****** >> %attachment%
echo File Size is >> %attachment%
ls -lh %fname%.dmp | awk " {print $4;} " >> %attachment%
echo ****** >> %attachment%
echo ****** >> %attachment%
echo Following Files DELETED as per policy if applied >> %attachment%
forfiles -p "b:\ORACLE-DB-sas" -s -m *.dmp -d -15 -c "cmd /c del @path" >> %attachment%
echo ****** >> %attachment%
echo SCRIPT ENDS HERE >> %attachment%
echo powered by Syed Jahanzaib >> %attachment%
echo Done.

c:\backup\blat\blat.exe %attachment% -to %mail-to% -i %srvname% -s "%mail-subject%"

Sample Result:

backup-email-sample

%d bloggers like this: