Syed Jahanzaib Personal Blog to Share Knowledge !

January 19, 2017

Windows User Login Logs

Filed under: Microsoft Related — Tags: — Syed Jahanzaib / Pinochio~:) @ 7:12 PM

Disclaimer:
This is a reference post for myself, to recall it later when i need it.
There are tons of tools/apps that can automate such tasks,Example you can do it via GPO (if you are in domain environment), or use dedicated tools, or just simply sort views in event viewer.

But being lazy/blockhead or fond of fetching result using out of the box approach, I try to select method that works for me and which seems easy to me plus with some learning. You may follow the internet to get more elegant / less complicated solution. Read it just to add ideas on how dumb-heads like me doing there work in other dimension approach , lean so that you may enhance it or at least not follow it for many reasons ;). This was a drafted version, later I modified this task for more presentable formatting. Windows batch file is far behind in advance coding as compare to bash, but we understand the limitation dueo to Microsoft platform.

I used WINTAIL to view real time logging of the specific system. we can modify the scripting to any level we want it to be. example we can log this info at our linux based mysql server, email the event, etc etc ūüėÄ

Sky is the only limit !

Zaib!


Scenario#1:

We have a domain environment in our office. At one windows 7 workstation, we have some important application installed which is access by specific users Remote (RDP and Dameware remote app) session & dueto some specific issues, the management wanted to store its full logs for following events only …

  1. When user login to the workstation
  2. When user logoff from the workstation
  3. When user connect to any previous session, either local or by remote
  4. When user re-login to the system (unlock)

Following information should be recorded in simple log file at remote server

  1. Event Type: LOGIN OR LOGOFF
  2. RDP Client IP: If the user is logged in via RDP, his ip should be logged
  3. DAMEWARE IP: If the user is logged in using DAMEWARE remote app, his IP should be logged
  4. Remote Client PC DNS Name: Remote client windows DNS name should be logged
  5. Username: Domain User ID which is being used to logging to the workstation
  6. Computername: name of workstation on which user is logging to
  7. Date / Time

 


Solution using Windows Batch File [Drafted but tested Version on Windows 7 / 64bit]

Requirements:

  • grep
    [Linux tool for windows version]
  • sed
    [Linux tool for windows version]
  • login-log.cmd
    our batch file
  • task scheduler task to trigger it on different events we required

Download grep/sed and place all contents in its bin folder to C:\windows\system32 so that it can be accessed from any path.

login-log.cmd

@echo off
rem ### Batch file to be configured in Task Manager to log events 
rem ### to remote server log file
rem ### Syed Jahanzaib
cls
rem Create Backup folder if not exists already
set TEMPLOC="C:\BACKUP"
if not exist "%TEMPLOC%" mkdir %TEMPLOC%
set LOGLOCAL="%TEMPLOC%\LOCAL.LOG"
rem ### Log Server Folder where logs will be saved
set LOGSERVER="\\LOGSERVER\userlog\%USERNAME%.log"
set IPFILE="%TEMPLOC%\IP.TXT"
set COMPFILE="%TEMPLOC%\COMPNAME.TXT"
set IPADD=
set DAMWIP=
set COMPNAME=
rem ### Delete old holders adn tasks if any
del %IPFILE% 2> nul
del %COMPFILE% 2> nul
taskkill /F /IM nslookup.exe 2> nul

rem ### 
::# Get IP Address of local PC
for /f "skip=1 tokens=2 delims=[]" %%* in (
'ping.exe -n 1 %Computername%') Do (set "LOCALIP=%%*" & goto:exitFor1)
:exitFor1

rem ### Get IP address for any RDP session, IF ANY, 
netstat -na | find "3389" | find "ESTABLISHED" | awk "{print $3}" | sed s/:.*// > %IPFILE%
set /p IPADD=<%IPFILE%
IF "%IPADD%"=="" (
set IPADD=x
)

rem ### If no RDP session found, then skip nslookup to avoid any delay
set "filter=c:\backup/ip.txt"
for %%A in (%filter%) do if %%~zA==0 goto :skipname
nslookup %IPADD% | sed -n "4p" | awk "{print $2}" > %COMPFILE%
set /p COMPNAME=<%COMPFILE%

rem ### Check for any DAMEWARE remote app session and log its ip/name
:skipname
netstat -na | find "6129" | find "ESTABLISHED" | sed -n "2p" | awk "{print $3}" | sed s/:.*// > c:\damwip.txt
set /p DAMWIP=<c:\damwip.txt
rem echo %DAMWIP%
set "filter=c:\damwip.txt"
rem for %%A in (%filter%) do if %%~zA==0 echo no damw
REM goto :skipdamw
rem ### if no damware ip session found, make it null x
IF "%DAMWIP%"=="127.0.0.1" (
set DAMWIP=x
)

rem ### If there is no remote session for both RDP and DW , then set variable accordingly
:skipdamw
if "%DAMWIP%"=="x" goto :1
nslookup %DAMWIP% | sed -n "4p" | awk "{print $2}" > c:\backup\damwip.txt
set /p COMPNAME=<c:\backup\damwip.txt
goto :skip
:1
if "%IPADD%"=="x" goto :cond
goto :skip
:cond
set IPADD=LOCAL-LOGIN
set DAMWIP=LOCAL-LOGIN
:skip

if "%COMPNAME%"=="" set COMPNAME=LOCAL-LOGIN
REM --- SERVER LOG FILE
echo --------------------------------- >> %LOGSERVER%
ECHO LOGIN >> %LOGSERVER%
echo RDP Client IP: %IPADD% - / DW IP: %DAMWIP% / Remote Client PC: %COMPNAME%
echo Login User: %USERNAME% / To: %COMPUTERNAME% / Local IP: %LOCALIP% / %DATE% %TIME%
echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER%
echo --------------------------------- >> %LOGSERVER%

REM --- LOCAL LOG FILE
echo --------------------------------- >> %LOGLOCAL%
ECHO LOGIN >> %LOGLOCAL%
echo RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGLOCAL%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGLOCAL%

echo --------------------------------- >> %LOGLOCAL%


Windows Task Scheduler Configuration >

task1

task-1

task2

 


Result:

Now you can open the log file at log server, or local pc as well.

 


LOGIN
RDP Client IP: x - DW IP: 10.0.0.58 / Remote Client PC: zaib.pc
Username - user.id / Computer - APPSRV / Thu 01/19/2017 14:31:36.68
---------------------------------
---------------------------------
LOGOFF -- APPSRV APPSRV Thu 01/19/2017 14:31:41.09
---------------------------------
---------------------------------
LOGIN
RDP Client IP: LOCAL-LOGIN - DW IP: LOCAL-LOGIN / Remote Client PC: LOCAL-LOGIN
Username - user.id / Computer - APPSRV / Thu 01/19/2017 14:33:11.35
---------------------------------
LOGIN -- user.id APPSRV Thu 01/19/2017 14:33:16.02
---------------------------------
LOGOFF -- user.id APPSRV Thu 01/19/2017 14:33:23.14
---------------------------------
LOGIN -- user.id APPSRV Thu 01/19/2017 15:35:03.51
---------------------------------
LOGIN
RDP Client IP: 10.1.2.250 - DW IP: x / Remote Client PC: seconduser.domain
Username - APPSRV / Computer - APPSRV / Thu 01/19/2017 15:35:04.54
---------------------------------


Scenario#2:

Log information of every user login/logout in %username%.txt in remote server folder .

Using Domain GPO , set it to execute login-log.cmd file at Startup


@echo off
echo LOGIN -- %USERNAME% %COMPUTERNAME% %CLIENTNAME% %DATE% %TIME% >> \\LOGSERVER\userlog\%USERNAME%.log

at remote log server, you can set permission so that user can only write in it, but not explore it.

permission


blah blah blah

Syed.Jahanzaib

December 7, 2016

Fighting with Ransomware !

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

ransomware

What is Ransomware 

Quite a HOT topic Now a days. Every email server administrator must be well familiarized with this malware and they try even harder to protect their users from this malware attack called locky (and many other similar variants) which encrypts users word/excel/etc documents and asks for money to restore them).

Our company users got hitted by this most smart malware repeatedly / several times resulting in great loss. Luckily most users data got recovered from Tape backup. This malware which usually comes by email , posted itself to be some valid / legitimate payment query & no matter how many times we provide users with education/warning about this matter, user stills open it considering it as valid email resulting in lost (encrypt/inaccessible) of all word/excel files.

We are using IBM Lotus Domino Email System along with Symantec Mail Security for Domino. With lots of R&D I am still unable to block this ransomware which comes in .JS files hidden inside .ZIP container. If I block .JS file inside the ZIP container, it will block legitimate PDF files as well. How frustrating ! The symantec should post some simple update to fix this issue. This issue is well discussed over here.

https://www.symantec.com/connect/ideas/exceptions-file-name-rule-smsmse


Workaround ! [Use Domain Group Policy to alter File Association Open with for .JS extension]

DISCLAIMER: THIS IS NOT A SOLUTION ! BUT JUST A `WORKAROUND` YOU CAN REFER TO.

THE PROPER SOLUTION WOULD BE TO USE SOME INTELLIGENT / UPDATED ANTISPAM/FILTRATION SYSTEM FOR YOUR EMAIL SYSTEM.

Since we cannot change our Symantec enterprise protection suite as it is covered under 3 years renewal (till 2018) . therefore aftering conducting lot of R&D I finally made a workaround for our DOMAIN USERS which is working Good so far.

I changed the .JS file extension OPEN WITH policy pointed to NOTEPAD.
[via Group_Policy ]

This way even if the user try to opens the .JS file, it will be open by notepad.
(instead of Windows Scripting Host)

I made changes to our domain controller in Windows 2008 R2

  • Login to Domain Controller PC
  • Open Group Policy (or by issuing following command)
    %SystemRoot%\system32\mmc.exe %SystemRoot%\system32\gpmc.msc
  • Edit the Default Domain Policy (or any custom you may have)
  • Goto User Configuration > Preferences > Control Panel Settings > Folder Options
  • Now Right click on Folder Options > New > Open With
  • Now use the below defined method as a reference to Update/Create the file extension

As shown in below image …

group policy.png

  • Action: Update
  • Files Extension: js
  • Assoticated Progra:¬†%windir%\system32\notepad.exe
  • Set As Default : Select Tick on it

 

At client either issue gpupdate /force or restart the client pc or wait for the policy update.

Now try to open any .JS file and it will be opened in NOTEPAD (instead by windows scripting host program) and thus it will do no harm to user computer ūüėÄ ūüėÄ ūüėÄ

Please test this method and let us know your feedback on it ūüôā

Note: you can use the same method to block / alter the file extension using Local Group POlicy


Alhamdolillah !

Regard’s
Syed Jahanzaib

 

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

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

November 5, 2015

Adding External NTP Server in Domain Controller / Short Notes

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

SHORT NOTES FOR PERSONNEL REFERENCE ONLY


Command to check time on remote Windows PC.

all commands should be executed using administrative privileged account.

net time \\REMOTEPC

 

Adding external NTP server on DC

# Set NTP on DC / on server

w32tm /config /manualpeerlist:"59.106.180.168,0x1 62.201.215.14,0x1 "

w32tm /config /reliable:yes

net stop w32time && net start w32time

 

Command for client side windows , to force update time from DC

I added this file in GP so that every computer on reboot is forced to update time via server

# For client
net time \\DC_SERVER /set /y

 

Using PSTOOLS to execute command on remote PC.

# run command on remote computer.
PsExec.exe \\$1 -u DOMAIN\ADMIN -p PASS cmd "/c net time \\DC_SERVER /set /y"

 

Force client update from your admin PC forcefully.

I sued following script / batch file [named setrtime.bat] to manually update time on remote pc via remote, and show before/after time.

@echo off
cls
echo Current time of %1
echo -------------------------
net time \\%1
echo -------------------------
PsExec.exe \\%1 -u DOMAIN\ADMIN -p PASS cmd "/c net time \\DC_SERVER /set /y"
echo -------------------------
echo Current time of %1 AFTER CHANGING
net time \\%1

now use it like

netrtime.bat REMOTEPCNAME

September 15, 2015

Event ID 7000 The Diagnostic Service Host service failed to start !

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

7000 diagnostic service host error

The Diagnostic Service Host service failed to start due to the following error:
A privilege that the service requires to function properly does not exist in the service account configuration. You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration.

Today at my company, every domain user was receiving above error in  there Event logs / SYSTEM section.

To sort this issue i did following

  1. Login to Domain Controller PC
  2. Open Group policy editor (or run gpedit.msc from RUN) and edit default domain policy (or any other custom policy you may have other then default)
  3. Goto Computer or USER  Configuration -> Policies -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignment -> Profile system performance

There you may see only ADMINISTRATOR user added by default, now add following users

LOCAL SERVICE
NT Service\WdiServiceHost

Now open CMD and issue following command to force GPUDPATE.

gpupdate /force


 

 

At client end, clear the logs, and reboot system. After rebooting check Event Viewer and you wont see the error again. [I waited about 15 minutes before rebooting client]

 

Regard’s
Syed Jahanzaib

September 7, 2015

Resolving “Trust Relation between this workstation and the PDC”

Filed under: Microsoft Related — Tags: — Syed Jahanzaib / Pinochio~:) @ 9:18 AM

Yesterday I converted one of our Physical Windows 2008 base SAP QAS server to ESXI 5.x Virtual Guest for some R&D purposes. It took around 30+ hours for the conversion using vconverter 6 [as old converters have no support UEFI BIOS. When I powered on the newly converted vm guest machine I received the following error upon login

 

trust-error

[I also received same error in year 2014 when our lotus domino server was migrated to new IBM Xseries 3650 M4 series and after every thing got settled i received this error upon final login, what a terrible time that was]

As a quick remedy I tried to RESET the computer account of this PC via AD management but no use.
Finally I used old NETDOM method and it worked instantly.

This is how I solved this problem.

Login with local computer admin account

Open COMMAND prompt

and Issue following command

netdom resetpwd /s:server /ud:domain\User /pd:*

 

Example if you have following setup

AD Server Name : SERVER1
Domain Name : mydomain.local
User Name : jahanzaib

then use following

netdom resetpwd /s:server1 /ud:mydomain.local\jahanzaib /pd:*

It will ask you to enter new password, simply enter password and enter. [prompt will not let u see the typing so careful when typing password]

After then simply log off and login with your domain id and it will work Insha Allah.

Regard’s

Syed Jahanzaib

March 16, 2015

Windows 7 WEATHER GADGET ‘not working’ workaround!

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

UPDATE: May, 2015

The method defined in this post is now not working any more. [at the beginning it was working but not anymore] , I will see if alternate methods may work and will update this post in coming week, to see if its working … Insha Allah,¬†¬†

 


 

 

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

July 18, 2014

Odd Results with Scheduled Batch Files in Windows Server 2008 R2

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

MS DOS BATCH FILE VIA 2008 R2 Scheduled Task / zaib

MS DOS BATCH FILE VIA 2008 R2 Scheduled Task / zaib

Recently I upgraded one of our old File server previously running Windows 2003 with Windows 2008 R2 64bit. this server was a member of AD and was logging with domain admin account.  Everything went smooth, but after few days I faced an strange issue that few scheduled BATCH files were not running properly at given time. If I try to execute batch file manual, they give proper result, but from schedule they dont, even by right click on the task and selecting RUN dont actually execute the batch file. To resolve this issue I added the admin account in Domain Group Policy and every thign now running fine as expected.

  • Edit Group Policy at Domain Controller
  • Goto “Computer ConfigurationPolicies > Windows Settings > Security Settings > Local Policies > Users Rights Assignment
  • Now on Right side menu, Double click on¬† “Log on as a batch job” to take its properties,
  • then click button “Add user or Group
  • then click button “Browse”
  • then click button “Advanced”
  • then button “Find now
  • Add your required user ID / Account here like “administrator” or likewise
  • and then “OK
  • Force by gpupdate /force at DC and Client as well.
  • (Or if pc is stand alone, then goto “Start” > Administrative tools > local security policy”)

.

This solved my problem of BATCH files not running via Scheduled Task,

Regard’s

 

Older Posts »

Create a free website or blog at WordPress.com.