Syed Jahanzaib Personal Blog to Share Knowledge !

March 8, 2017

MS Project 2016 has stopped working on assign resources

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

microsoft-project-2016-license-key-e1469786312356

Recently we purchased Microsoft Project 2016 licenses for our users. In terms of Functionality – All seems to be working fine except assigning resources

Whenever user tried to assign resources using option `Assign Resources` , project crashed/stopped working with below error …

ms_project_2017_stopped_wroking

 

After little R&D, we found that this is a standard bug in MS Project 2016 and it was fixed with Patch released on February 9, 2016

February 9, 2016, update for Project 2016 (KB3114714)

After updating patch, all went fine.


Advise of the day ! (Golden Rule)

Although we have WSUS (Windows Update Servers) in our organization which regularly update the clients windows , but general patches for MS OFFICE was not selected in the checklist, & that’s the main reason why we had to face this issue. Always keep your Windows and other softwares UP TO DATE. It will keep you away from UNWANTED guests ūüėČ You know what I mean ūüôā

Regard’s
Syed Jahanzaib

Advertisements

February 21, 2017

PowerShell Reference [Continued Post]

Filed under: Microsoft Related — Syed Jahanzaib / Pinochio~:) @ 8:34 AM

pwoershell-logo

coffe code.PNG

Following is reference post for Powershell command line usage to achieve different tasks. Recently I had to perform various administration tasks on more than 20 windows based servers , and using scripting it made my life a bit easier and I let the scripting ¬†do the task on my behalf on scheduled basis ūüėČ

These are very common tasks, commands but when you combine them with the Linux shell, they become ultra powerful and best thing is that you can create / add ¬†some ‘ Artificial Intelligence ‘ in it. I have posted just basic level to hide the sensitivity of original tasks.

Following is collection of my own R&D, some commands are picked from Stackoverflow/Spicework forums as well.


General PowerShell Related CMD


Check PowerShell Version

$PSVersionTable.PSVersion
Upgrade PowerShell to Version 4 in Windows 7/2008 - 64bit
https://blogs.technet.microsoft.com/heyscriptingguy/2014/11/09/weekend-scripter-install-powershell-4-0-in-windows-7/

Execute Powershell script from Linux Shell using winexe

winexe -U DOMAIN/ID%’PASSWORD’ //IP_OR_NAME //101.11.12.38 ‘powershell.exe -inputformat none -command “dir”‘

winexe -U DOMAIN/ID%’PASSWORD’ //IP_OR_NAME ‘powershell.exe -inputformat none -command “c:\scripts\script_name.ps1″‘


Check Powershell Version & Process Architecture

#Check PowerShell Version
$PSVersionTable
# Check Processor Architecture
$env:PROCESSOR_ARCHITECTURE
# Get list of installed HOTFIX with details
Get-HotFix | Format-Table

 # Import Active Directory module

import-module activedirectory

Show folders that have not been updated/modified by X Period of Time

In my company I have Windows 2008 R2 [as a file sharing / backup server] with a centralized shared folder structure like this

  • D:\USERS
  • D:\USERS\USER1
    D:\USERS\USER1\AUTOBACKUP
    D:\USERS\USER1\DROP
    D:\USERS\USER1\EXHIBIT
  • D:\USERS\USER2
    D:\USERS\USER2\AUTOBACKUP
    D:\USERS\USER2\DROP
    D:\USERS\USER2\EXHIBIT

There are are around 100+ users folders and all users copy their important data on a daily basis there corresponding AUTOBACKUP folder. Every AUTOBACKUP folder have several sub folders and files in it.

My requirements was to somehow display ONLY the AUTOBACKUP folders name which are not updated in last 1 month, means no file in written in any autobackup or in its subfolders. (I dont requires drop/exhibit folders details as it can be updated by any1 , but autobackup can be updated only by the corresponding user)

Result Something like:

  • D:\USERS\USER1\AUTOBACKUP – Updated
  • D:\USERS\USER2\AUTOBACKUP – ALERT: Not updated since last month …

or show me result only for users whose auto backup have not updated from past month.

I tried to get result by powershell commands, but it shows me results if some one update the drop/exhibit too, and i want to exclude them in search criteria, the search should be done only in autobackup.

So here was the solution :)~

Get-WmiObject Win32_LogicalDisk -Filter "DriveType='3'" `
 -ComputerName SERVER_NAME | `
 Format-Table `
 @{l="Server";e={$_.SystemName}}, `
 @{l="Drive Letter";e={$_.DeviceID}}, `
 @{l="Free Space on Disk (GB)";e={"{0:n2}" -f ($_.freespace/1gb)}}, `
 @{l="Total Disk Space (GB)";e={"{0:n2}" -f ($_.size/1gb)}}, `
 @{l="Percentage Used";e={ "{0:P2}" -f (1 - ([Int64]$_.FreeSpace / [Int64]$_.Size)) }}

$PrettySizeColumn = @{name="Size";expression={
 $size = $_.Size
 if ( $size -lt 1KB ) { $sizeOutput = "$("{0:N2}" -f $size) B" }
 ElseIf ( $size -lt 1MB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1KB)) KB" }
 ElseIf ( $size -lt 1GB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1MB)) MB" }
 ElseIf ( $size -lt 1TB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1GB)) GB" }
 ElseIf ( $size -lt 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1TB)) TB" }
 ElseIf ( $size -ge 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1PB)) PB" } 
 $sizeOutput
}}

# change the folder name here ...
Get-ChildItem 'D:\USERS' -Directory | ForEach-Object {

$RecentAutoBackupFiles = @(
# change the folder name here too ...
 Get-ChildItem -Path "D:\USERS\$($_.Name)\autobackup" -File -Recurse | 
 Where-Object { $_.LastWriteTime -ge [datetime]::Now.AddMonths(-1) }
)

if (0 -eq $RecentAutoBackupFiles.Count)
 {
 "$($_.Name) "
 }
}

Result of above Script (which was executed using Linux bash script as usual:) )

1

 

2


Show Folder Size (in GB) | Sort by Size | Select top 10

This was intense task for me, and I was not able to sort it on my own. so I have to take help from stackoverflow and spicework forums.

Scenario:

We have a Windows 2008 R2  base file server where users have there shared folders.
Example:

  • D:\USERS
  • D:\USERS\USER1
  • D:\USERS\USER2
  • D:\USERS\USER3
  • D:\USERS\USER4
  • D:\USERS\USER5

All users folders have several hundreds sub folders in it.

Task:

Execute functions from Linux base system , which should remote to file server by winexe, execute powershell script, which should perform functions like

  • List all users folder name
  • Last modified time
  • Size conversion auto in kb/mb/gb ( order by size)
  • Email the result [customized] using sendEmail / gmail.

First the powershell script name foldersize.ps1 which will actually perform the functions on file server. we will copy this script in c:\temp on remote file server.

foldersize.ps1


param ($Path = ".")
$disk = ([wmi]"\\FILESERVER\root\cimv2:Win32_logicalDisk.DeviceID='D:'")
"D: GB Total = {0:#.0}
D: GB Used {2:#.0}
D: GB Free {1:#.0} " -f ($disk.Size/1GB),($disk.FreeSpace/1GB),($disk.Size/1GB-$disk.FreeSpace/1GB) | write-output

Get-WmiObject Win32_LogicalDisk -Filter "DriveType='3'" `
-ComputerName FILESERVER | `
Format-Table `
@{l="Server";e={$_.SystemName}}, `
@{l="Drive Letter";e={$_.DeviceID}}, `
@{l="Free Space on Disk (GB)";e={"{0:n2}" -f ($_.freespace/1gb)}}, `
@{l="Total Disk Space (GB)";e={"{0:n2}" -f ($_.size/1gb)}}, `
@{l="Percentage Used";e={ "{0:P2}" -f (1 - ([Int64]$_.FreeSpace / [Int64]$_.Size)) }}

$PrettySizeColumn = @{name="Size";expression={
$size = $_.Size
if ( $size -lt 1KB ) { $sizeOutput = "$("{0:N2}" -f $size) B" }
ElseIf ( $size -lt 1MB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1KB)) KB" }
ElseIf ( $size -lt 1GB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1MB)) MB" }
ElseIf ( $size -lt 1TB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1GB)) GB" }
ElseIf ( $size -lt 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1TB)) TB" }
ElseIf ( $size -ge 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1PB)) PB" }
$sizeOutput
}}

Get-ChildItem -Path $Path | Where-Object {$_.PSIsContainer} | ForEach-Object {
$size = ( Get-ChildItem -Path $_.FullName -Recurse -Force | where {!$_.PSIsContainer} | Measure-Object -Sum Length).Sum
$obj = new-object -TypeName psobject -Property @{
Path = $_.Name
Time = $_.LastWriteTime
Size = $size
}
$obj
} | Sort-Object -Property Size -Descending | Select-Object Path, Time, $PrettySizeColumn

try to execute this file on the file server from powershell terminal. It should give you proper results. JUST BE VERY SURE TO READ THE SCRIPT VERY WELL, AS IT SHOULD BE MODIFIED AS PER YOUR REQUIREMENTS, PLUS I USED DOMAIN ADMIN ID, SO I HAD ALL THE ACCESS ON ALL THE COMPUTERS FROM MY PC /REMOTELY AS WELL.

.\foldersize.ps1 -Path  \\FILESERVER\C$\Softwares\IMAGES_ISO

Once done,  make a bash script in your linux (ubuntu) system  which will execute the above script remotely and will customized the result and email to the admin.

BASH FILE / folder_iquiry.sh which will run the ps file from linux terminal


#!/bin/bash
#set -x
# This bash script will query remote file server storage using Powershell Commands.
# It will send report via email with relevant details like top used folders , Very useful some times.
# Syed Jahanzaib / aacableAThotmailDOTcom
# http://aacableDOTwordpressDOTcom
# 20-feb-2017
start=`date +%s`
COMPANY="ZAIB"
SRVNAME="SRV01"
SRV_FRIENDLY_NAME="File Server D:Drive"
IP="10.0.0.1"
DOMAIN="DC.LOCAL"
PASS="PASSWORD"
ID="ADMIN"
#TARGET DIRECTORY
TDIR="d:\users"
TEMP_HOLDER="/tmp/xdrive_temp_raw_report.txt"
TEMP_HOLDER_FINAL="/tmp/xdrive_final_mail_report.txt"
> $TEMP_HOLDER
> $TEMP_HOLDER_FINAL
DATE=`date`

# GMAIL DETAILS to send EMAIL alert
SENDMAILAPP="/temp/sendEmail-v1.56/sendEmail"
GMAILID="ADMIN_GMAIL_ID@gmail.com"
GMAILPASS="GMAIL_PASS"
# Add recipient email address below
ADMINMAIL1="aacableAThotmailDOTcom"

MSG_SUB="$COMPANY $SRV_FRIENDLY_NAME - $SRVNAME - / Weekly Report @ $DATE"
MSG_BODY="$COMPANY $SRV_FRIENDLY_NAME - $SRVNAME - Weekly Report for Users D: drive folder's sorted by size
@ $DATE
"

FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin
$COMPANY IS Dept."

echo "
$MSG_BODY
" > $TEMP_HOLDER

#QUERY SERVER X: DRIVE
winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "c:\temp\foldersize.ps1 -Path '"$TDIR"' ' >> $TEMP_HOLDER

# Remove Junk Line with unknonw character, which is unique or specific occured in my lab test

end=`date +%s`
echo "It took $(($end - $start)) seconds to complete this task..." >> $TEMP_HOLDER
echo "
$FOOTER" >> $TEMP_HOLDER

#Print result
cat $TEMP_HOLDER
#send email
sendemail -u "$MSG_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TEMP_HOLDER -o message-content-type=text

# Script ends here

Now execute file from linux terminal like this…

/temp/folder_inquiry.sh

SAMPLE:

userreport.PNG


Show Folder Size (in GB) | Sort by Size | Select top 10

[This method have one BIG disadvantage, dueto 260 characters limit in windows, it may not show files/folders above then this limit. so it may not give your correct result if you have some deep folder structure/long files name in it.]

#Windows PS Version
ls c:\temp | select Name, @{Name="Type";Expression={if($_.psIsContainer){"---Directory---"}else{"---File---"}}}, @{Name="Size(GB)";Expression={[Math]::Round($(ls $_.FullName -recurse| measure Length -sum).Sum/1GB, 2)}}| sort -property "Size(GB)" -desc | Select -First 10

# Linux Winexe format
winexe -U DC/ID%PASS //IP 'powershell.exe -inputformat none -command "ls c:\backup\ | select Name, @{Name='"'"'"Type"'"'"';Expression={if($_.psIsContainer){'"'"'"Directory"'"'"'}else{'"'"'"File"'"'"'}}}, @{Name='"'"'"Size(GB)"'"'"';Expression={[Math]::Round($(ls $_.FullName -recurse| measure Length -sum).Sum/1GB, 3)}}| sort -property '"'"'"Size(GB)"'"'"' -desc | Select -First 10"'

Example of C:\temp contents …

  • C:\TEMP
  • C:\TEMP\FOLDER1
  • C:\TEMP\FOLDER-1\SUB_FOLDER
  • C:\TEMP\FOLDER-1\SUB_FOLDER_MORE
  • C:\TEMP\FOLDER2
  • C:\TEMP\FOLDER3

This will query all folders/sub-folders inside the c:\temp folder, and display only the main folders name including sizes of subfolder as well ..

Name Type Size(GB)
---- ---- --------
Win2008_test Directory 28.9
Ubuntu-PHP-API Directory 2.75
ubuntu-freeradius Directory 2.15
zaib_temp_radius Directory 2.09
MIKROTIK-1 - Copy Directory 0.39


Show files with Name & Size greater than 5 GB

[This was required in a script where I schedule it to email the top users in mail server by querying the folder directly]

Following command is formatted to be executed by WINEXE [Linux]

winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "Get-ChildItem -Path '"$TDIR"' | Where-Object {$_.length -gt 5GB} | Sort-Object -descending -Property Length | Format-Table Name,@{name='"'"'Size GB'"'"';expression={$_.length/1GB};FormatString='"'"'N1'"'"'}"' | sed -e "$DEL_LINE" | sed '/^\s*$/d' |nl >> $TEMP_HOLDER

Script to get specific folder files and specific  folder total size, sort and email to admin on every Monday / Weekly

#!/bin/bash
#set -x
# This bash script will query remote lotus domino mail server storage using Powershell Commands.
# It will send report via email with erelevant details, Very useful some times.
# Syed Jahanzaib / aacableAThotmailDOTcom
# http://aacableDOTwordpressDOTcom
# 20-feb-2017
COMPANY="ZAIB"
SRVNAME="MYSRV"
IP="10.0.0.1"
DOMAIN="DC_NAME"
PASS="PASSWORD"
ID="ADMINISTRATOR"
TDIR="D:\lotus\domino\data\mail"
TDIR_FULL="D:\lotus"
TDIR_MAIL="D:\lotus\domino\data\mail"
TDIR_ARCH="D:\lotus\domino\data\archive"
# How many lines to be dleeted from winexe output for top users section
DEL_LINE="1,3d"
TEMP_HOLDER="/tmp/mail_top_users.txt"
TEMP_HOLDER_FULL="/tmp/mail_lotus_folder_size.txt"
> $TEMP_HOLDER
DATE=`date`

# GMAIL DETAILS to send EMAIL alert
SENDMAILAPP="/temp/sendEmail-v1.56/sendEmail"
GMAILID="ADMIN_GMAIL_ID@gmail.com"
GMAILPASS="GMAIL_PASSWORD"
# Add recipient email address below
ADMINMAIL1="aacableAThotmailDOTcom"

MSG_SUB="$COMPANY Lotus Mail Server / Weekly Report @ $DATE"
MSG_BODY="$COMPANY - $SRVNAME - Lotus Mail Server Weekly Report for Total Usage and TOP users exceeding 5GB mailbox size
@ $DATE
"
FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin
$COMPANY IS Dept."

echo "
$MSG_BODY
" > $TEMP_HOLDER

#Full size of Lotus Folder - Overall
FULL_SIZE=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_FULL"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus Total DATA size in GB = $FULL_SIZE" >> $TEMP_HOLDER

#Full size of Lotus MAIL Folder only
FULL_SIZE_MAIL=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_MAIL"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus Total User Inbox MAIL SIZE in GB = $FULL_SIZE_MAIL" >> $TEMP_HOLDER

#Full size of Lotus ARCHIVE Folder only
FULL_SIZE_ARCH=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_ARCH"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus User's ARCHIVE Folder SIZE in GB = $FULL_SIZE_ARCH" >> $TEMP_HOLDER

echo "----------------------------------------------
Lotus Users List whose inbox is exceeding 5 GB" >> $TEMP_HOLDER

#Only Top users exceeding 5GB
winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "Get-ChildItem -Path '"$TDIR"' | Where-Object {$_.length -gt 5GB} | Sort-Object -descending -Property Length | Format-Table Name,@{name='"'"'Size GB'"'"';expression={$_.length/1GB};FormatString='"'"'N1'"'"'}"' | sed -e "$DEL_LINE" | sed '/^\s*$/d' |nl >> $TEMP_HOLDER

echo "

$FOOTER" >> $TEMP_HOLDER
# Display result by cat
cat $TEMP_HOLDER
# Send email
sendemail -u "$MSG_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TEMP_HOLDER -o message-content-type=text

Result of above script …

1.PNG


PowerShell Get Folder / File ACL list

Get-Acl c:\temp | select -Expand Access

Sample Result:


PS C:\> Get-Acl c:\temp | select -Expand Access
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : 268435456
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : 268435456
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

FileSystemRights : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : BUILTIN\Users
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : None

FileSystemRights : Modify, Synchronize
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : -536805376
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

PS C:\>


Regard’s
Syed Jahanzaib

February 16, 2017

Modifying ‘tombstoneLifetime’ value in Active Directory

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

Default lifetime for tombstone.jpg


What is tombstone Lifetime?

The AD tombstone lifetime determines how long deleted items exist in AD before they are purged, for example users  or other objects. The default value in Windows 2008 is 180 Days.

Why I need to modify its default value,  ?

We want to increase it for some audit purpose, specially to track deleted objects (example how many Users were deleted in last 1 or 2 years)

Let’s Start …

METHOD # 1 РUsing GUI Method

Execute ADSIEdit tool by

%SystemRoot%\system32\adsiedit.msc

  • Now using ADSIEdit tool, connect to your domain controller.
  • Navigate to CN=Directory Services , Right click and select Properties.
  • Find tombstoneLifetime and Click Edit,
  • Now define value in days for how long you want to increase the value. I wanted 2 years so I put 630¬†. This values must be in DAYS.

As showed in the image below …

tombstone.PNG

Note: By Some mistake, i typed 630, whereas the actual number for 2 years is 730, so change it accordingly


METHOD # 2 – Using PowerSHELL Command

Setting Two Years Tombstone Lifetime

Import-Module ActiveDirectory
$ConfNameContext = Get-ADRootDSE | Select-Object -Expandproperty configurationNamingContext
Set-ADObject -Identity "CN=Directory Service,CN=Windows NT,CN=Services,$ConfNameContext" -Replace @{'tombstonelifetime'='730'}

Querying tombstoneLifetime value via command

 

# Using dsquery command

dsquery * " cn=Directory Service,cn=Windows NT,cn=Services,cn=Configuration,dc=agp1" -scope base -attr tombstonelifetime

[COMMAND RESULT OUTPUT]

tombstonelifetime
730

# Using POWERSHELL 

#1

(get-adobject ‚Äúcn=Directory Service,cn=Windows NT,cn=Services,$(([adsi](‚ÄúLDAP://RootDSE‚ÄĚ)).configurationNamingContext)‚ÄĚ -properties ‚Äútombstonelifetime‚ÄĚ).tombstonelifetime

#2

Import-Module ActiveDirectory
$ConfNameContext = Get-ADRootDSE | Select-Object -Expandproperty configurationNamingContext
Get-ADObject -Identity ‚ÄúCN=Directory Service,CN=Windows NT,CN=Services,$ConfNameContext‚ÄĚ -properties tombstonelifetime |Format-List

Note / z@iB:

I found out that all commands doesn’t show default tombstoneLifetime. Once I modify the value, then I was able to see the value using above commands.

Regard’s
Syed Jahanzaib

February 15, 2017

Personnel Notes on Active Directory


ad

audit reporting in excel.PNG

Recently our IT dept was going through yearly Audit and we had to provide active directory details asked by the auditor team. I used few commands that saved lot of time to get our desired/trimmed results. and since I mostly use my Ubuntu box to manage large portion of my network, therefore i made few scripts using these commands to be executed from linux based pc.

I had to repeat the whole search criteria every time by refreshing the memory/google, and since it this is a repeating task , and I had to go through the search process every time, I thought to make all these documented so that I can retrieve them when required.

I also linked these scripts with the Linux base WEBMIN, so they can be called by GUI for support staff as well.


Most queries are executed from Linux base system using WINEXE, if you are using windows only then you may want to modify it as required, I am just showing an way of executing AD commands via powershell using *nix ūüôā . The most annoyed thing was to wrap the commands in single/double quotes along with other parameters to make it single liner execution bomb.

Some of following commands are wrapped for linux base execution, and some are common powershell commands, make sure to run import-module activedirectory command before querying AD instance]

Make sure to change the IP / credentials as required.




  • Command to Display Total Number Of Active Directory Users [Including disabled/enabled accounts as well]
(get-aduser -filter *).count
#OR
get-aduser -filter * | measure-object | select-object count
  • Command to Display Total Number Of Active Directory Users [Only ENABLED]
(get-aduser -filter *|where {$_.enabled -eq "True"}).count
#OR
get-aduser -filter 'enabled -eq $true' | measure-object | select-object count
  • Command to Display Total Number Of Active Directory Users [Only DISABLED]
(get-aduser -filter *|where {$_.enabled -ne "False"}).count
  • Command to Display All users along with every detail / information
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties *"'
  • Command to display only single user information as mentioned
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADUser ZAIB-USER-NAME -Properties *"'
  • Command to display only specific information
winexe -U DOMAIN/ADMIN%"PASSWORD" //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties * | select Name,UserPrincipalName,Enabled,LockedOut,Created,LastLogonDate"' 
  • Show Members from SPECIFIC GROUP¬†group only
dsquery group -samid "Domain Admins" | dsget group -members | dsget user
  • Show specific user OU & MemberOf
$user = get-aduser USERNAME;
$memb = (GET-ADUSER ‚ÄďIdentity USERNAME ‚ÄďProperties MemberOf | Select-Object MemberOf).MemberOf -replace "DC=DCNAME*" -replace "CN="
$uo = $user.distinguishedname.substring($user.distinguishedname.indexof(",") + 1,$user.distinguishedname.Length - $user.distinguishedname.indexof(",") - 1)
write-host "$($user.Name) = $($uo.split(',')[0])"
echo "Member of:" $memb
  • Command to get all users and show only following fields

UserPrincipalName,Created,Enabled,MemberOf

winexe -U DOMAIN/ID%PASSWORD //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties * | select
UserPrincipalName,Created,Enabled,MemberOf |Format-Table -Property * -AutoSize | Out-String -Width 4096 | Out-File c:\1.txt"'
  • Query for speciifc User belongs to which groups
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; (GET-ADUSER ‚ÄďIdentity zaib.user¬†‚ÄďProperties MemberOf | ¬†Select-Object MemberOf).MemberOf"'
  • Get Members List of specific Group
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADGroupMember "'"'Domain Admins'"' |Select name,distinguishedName |  Format-Table -AutoSize"'
#OR
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADGroupMember "'"'Limited Internet Facility Group'"' |Select sAMAccountName| Format-Table -AutoSize"'
  • Show All Users Created Dated Only using PowerShell
winexe -U DOMAIN/ID%PASSWORD //10.0.0.1 'powershell.exe -command "import-module activedirectory; Get-ADUser -Filter * -Properties Created | Select-Object Name,Created | Sort-Object Created"'
  • Show Users created in Last 30 days
winexe -U DOMAIN/ID%PASSWORD //10.0.0.1 'powershell.exe -command "import-module activedirectory; $When = ((Get-Date).AddDays(-30)).Date; Get-ADUser -Filter {whenCreated -ge $When} -Properties whenCreated"'
  • Show Users created in specific after DATE RANGE
Get-ADUser -Filter * -properties whencreated | ? { $_.whenCreated -ge (get-date "January 1, 2017") -and  $_.whenCreated -le (get-date "January 31, 2017")} |Select Samaccountname,whenCreated,office 
  • Show Users created in specific after DATE RANGE
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory;Get-ADUser -Filter * -properties whencreated | ? { $_.whenCreated -ge (get-date "'"'January 1, 2017'"') -and $_.whenCreated -le (get-date "'"'January 31, 2017'"')} |Select Samaccountname,whenCreated,office"'
  • Show Users DELETED in specific DATA RANGE … [powershell commands]
[datetime]$StartTime = "1/1/2017"
[datetime]$EndTime = "1/15/2017"
Get-ADObject -Filter {(isdeleted -eq $true) -and (name -ne "Deleted Objects") -and (ObjectClass -eq "user")} -includeDeletedObjects -property whenChanged | Where-Object {$_.whenChanged -ge $StartTime -and $_.whenChanged -le $EndTime} |Select Name,whenChanged |Format-Table
  • Show DISABLED Users Only …
#Method 1 using PS
winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; search-adaccount -UsersOnly -AccountDisabled | select samAccountName"'
  • Show users who have not logged in Since 60 days

winexe -U DOMAIN/ID%PASS //10.0.0.1 'powershell.exe -command "import-module activedirectory; $domain = "DOMAIN-NAME"; $DaysInactive = 60; $time = (Get-Date).Adddays(-($DaysInactive)); Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp"'
# Method 3 using dsquery
dsquery user "dc=Your_Domain_Name" -inactive 2

  • Show DISABLED Users Only using DSQUERY
dsquery user -disabled | dsget user -display -email -dept -title
  • Show Only Specific User Details [ Method#2]
winexe -U DOMAIN/ID%PASSWORD //10.0.0.1 'Net user ZAIB /domain"'

  • Get DHCP info from server to acquire some customized report
# 10.0.0.1 IS DOMAIN
# 101.0.0.0 is our scope
winexe -U DC/ID%PASSWRORD //10.0.0.1 'netsh dhcp server scope 101.0.0.0 show clients 1'
  • Dump DHCP SERVER DETAILS IN FILE for some specific purpose, i required to get mobile devices list
# Dump DHCP
# 101.11.11.5 IS DOMAIN
# 101.11.14. IS MOBILE DEVICES IP SERIES, SO WE ARE CATCHING IT
# 101.11.11.36 IS GATEWAY
# 101.11.11.6 IS OTHER GATEWAY
winexe -U DC/ID%PASSWD //101.11.11.5 'netsh dhcp server \\DCSERVERNAME dump' > /tmp/dhcp_temp.txt
cat /tmp/dhcp_temp.txt | grep 101.11.14. | awk '{ print $11,$12}' | sed -e 's/"101.11.11.6"//g' -e 's/"101.11.11.36"//g' -e 's/"//g' -e 's/ BOTH//g' | sed '/ \r/d' | sort
cat /tmp/dhcp_temp.txt | grep 101.11.14. | awk '{ print $11,$12}' | sed -e 's/"101.11.11.6"//g' -e 's/"101.11.11.36"//g' -e 's/"//g' -e 's/ BOTH//g' | sed '/ \r/d' | sort | wc -l

Regard’s
Syed Jahanzaib

January 26, 2017

Check remote windows logged-in user/lock status via BASH

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

locked

Scenario:

We have Active Directory environment in our office. Clients OS are mixed starting from windows 2000/2003/2008 and Win7.
For some specific reasons/policy, our helpdesk staff is often required to inquire if the employee is working on his workstation or if his/her windows status is locked.

Solution:

Since I am using my Ubuntu box to manage most of the Active Directory functions using Webmin/BASH scripts, therefore I made a small bash script which queries for remote windows logged in user session and windows locked/unlocked status.

The bash script does the following …

  • Check for remote PC PING Status, if ping fails, exit with error
  • Get remote windows IP via NSLOOKUP using local DNS
  • Current Logged-in user and their status
  • Current status of windows either its locked/unlocked.
  • TRIM the results and display according to our taste

the Script!

> root@linux:/temp# cat winuserstatus.sh

#!/bin/bash
# Script to check remote windwos status, like Loggedin + Windows Lock/Unlock status
# More functions can be added/removed as required.
# I attached this script to webmin for our Support dept.
# Syed Jahanzaib / aacable.wordpress.com / aacable @ hotmail . com
# Created: 25-JAN-2017
# Revised: 29-JUN-2017
#set -x
QUSER_HOLDER="/tmp/$1.quser"
LOCK_HOLDER="/tmp/$1.lockstatus"
REMOTE_PC="$1"
PING_ATEMPTS="1"
PING_STATUS="/tmp/$1.ping.status"
LOCAL_DNS_IP="101.11.11.5#"

# Domain credentials details so that winexe can execute commands on all domain clients
DOMAIN="YOURDOMAINNAME"
DOMAIN_ADMIN="ADMINID"
ADMIN_PASS="PASSWORD"
# Empty All Holders
> $QUSER_HOLDER
> $LOCK_HOLDER
> $PING_STATUS
# Check if remote PC is accessibel or not,
## IF PING FAILS then inform accordingly and EXIT
ping -q -c $PING_ATEMPTS $REMOTE_PC &>/dev/null > $PING_STATUS
PING_RESULT=`cat $PING_STATUS`
if [ "$PING_RESULT" = "" ]; then
echo "ERROR: Unable to resolve hostnname using $LOCAL_DNS_IP DNS Server.
Unknown HOST. Exiting"
exit 1
fi
# Print PC NAME (from $1 variable)
echo "Remote PC : $1"
IPADD=`nslookup $1 | grep Address | sed /$LOCAL_DNS_IP/d`
# Print IP of remote PC via nslookp using local DNS
echo "IP $IPADD"
# If ping failed, then print Error and EXIT
if [[ $(ping -q -c $PING_ATEMPTS $REMOTE_PC) == @(*100% packet loss*) ]]; then
echo "$1 not responding to ping request, probably system is not UP & without ping the status cannot be queried. Exiting ..."
exit 1
fi
# Query remote windows Logged in user using Linux WINEXE tool
winexe -U $DOMAIN/$DOMAIN_ADMIN%"$ADMIN_PASS" //$1 "quser" > $QUSER_HOLDER
QUSER_RESULT=`cat $QUSER_HOLDER |grep "Failed"`

if [[ -n "$QUSER_RESULT" ]]; then
echo "User Status = ERROR: Ping is ok but unable to query the user status."
exit 1
fi
QUSER_RESULT=`cat $QUSER_HOLDER |grep "Active"`
if [[ -n "$QUSER_RESULT" ]]; then
echo "User Status = Logged in User found ... details as below ...
$QUSER_RESULT"
fi

# Query remote windows TASK list to find if windows is locked/unlocked
winexe -U $DOMAIN/$DOMAIN_ADMIN%"$ADMIN_PASS" //$1 "tasklist" > $LOCK_HOLDER
LOCK_RESULT=`cat $LOCK_HOLDER |grep -E "LogonUI.exe|logon.scr"`

#Check if Someone is logged in via RDP session
QUSER_RESULT=`cat $QUSER_HOLDER |grep "rdp-tcp#0"`
if [[ -n "$QUSER_RESULT" ]]; then
echo "It seems someone is logged IN from RDP Session."
fi

# CHeck if windows is unlocked locally
if [[ "$LOCK_RESULT" = "" ]]; then
echo "Windows Status = Windows is UN-LOCKED"
fi

#Check if windwos is LOCKED locallay
if [[ -n "$LOCK_RESULT" ]]; then
echo "Windows Status = Windows Local Login seems to be Locked!"
fi

# Script function ends here
# Thank you


Result:

winuserexec result.PNG


Regard’s
Syed Jahanzaib

January 19, 2017

Windows Users Centralized Logging with AD & GPO

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, But being lazy/blockhead or fond of fetching result using out of the box approach, I usually 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 workstation gets LOCK dueto inactive session (after 5 minutes)
  4. When user connect to any previous session, either local or by remote
  5. When user re-login to the system (unlock)

Following information should be recorded in simple log file at remote server. there must be 2 log file for each user, one for the USER ID , and second for the COMPUTER NAME, so that we can view which users logged in to the PC, or which ID is used to loggedin to the PC. i am unable to explain right now, but later.

  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, it will be triggered by Event ID 1102
  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:

Since we are using Active Directory, We can use Login/Logoff script using DOMAIN Group Policy. What we will do is to create a new TASK scheduler entry via GPO to trigger task on specific actions like login/logoff/lock/unlock etc.

Requirements:

  • grep
    [Linux tool for windows version, copy its files in shared folder like \\DC1\TOOLS]
  • sed
    [Linux tool for windows version, copy its files in shared folder like \\DC1\TOOLS]
  • login-log.cmd
    This file will add login entry in user/computer log file [Copy it to DC SYSVOL Folder]
  • logoff.cmd
    This file will add logoff entry in user/computer log file [Copy it to DC SYSVOL Folder]
  • lock-log.cmd
    This will log unlock log in user/computer log file [Copy it to DC SYSVOL Folder]
  • Some addition in group policy to add task triggering via GPO

Download grep/sed and place all contents  to some shared location which all user can access example DC1\tools

Create another folder name DC1\userlogs which users can only write in it, but they should not able to browse in it.

Now create files for different tasks


login-log.cmd

@echo off
rem Script to add LOGIN log to our log server
rem *** by Syed Jahanzaib aacable@hotmail.com ***
cls
rem Create Backup folder if not exists already
set TEMPLOC="C:\BACKUP"
if not exist "%TEMPLOC%" mkdir %TEMPLOC%
set LOGLOCAL="%TEMPLOC%\LOCAL.LOG"
set LOGSERVER="\\DC1\userlog\%USERNAME%.log"
set LOGSERVER2="\\DC1\userlog\%COMPUTERNAME%.log"
set IPFILE="%TEMPLOC%\IP.TXT"
set COMPFILE="%TEMPLOC%\COMPNAME.TXT"
set IPADD=
set DAMWIP=
set DAMWIPFILE="%TEMPLOC%\damwipfile.txt"
set COMPNAME=
del %IPFILE% 2> nul
del %COMPFILE% 2> nul
taskkill /F /IM nslookup.exe 2> nul


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

netstat -na | find "3389" | find "ESTABLISHED" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %IPFILE%
set /p IPADD=<%IPFILE%
IF "%IPADD%"=="" (
set IPADD=x
)


set "filter=c:\backup/ip.txt"
for %%A in (%filter%) do if %%~zA==0 goto :skipname

nslookup %IPADD% | \\DC1\tools\sed -n "4p" | \\DC1\tools\awk "{print $2}" > %COMPFILE%
set /p COMPNAME=<%COMPFILE%

:skipname
netstat -na | find "6129" | find "ESTABLISHED" | \\DC1\tools\sed -n "2p" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %DAMWIPFILE%
set /p DAMWIP=<%DAMWIPFILE%
rem echo %DAMWIP%
set "filter=%DAMWIPFILE%"
rem for %%A in (%filter%) do if %%~zA==0 echo no damw
REM goto :skipdamw

IF "%DAMWIP%"=="127.0.0.1" (
set DAMWIP=x
)

IF "%DAMWIP%"=="" (
goto :nodamw
)

:skipdamw
if "%DAMWIP%"=="x" goto :1
nslookup %DAMWIP% | \\DC1\tools\sed -n "4p" | \\DC1\tools\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


:nodamw
set DAMWIP=x
:skip

if "%COMPNAME%"=="" set COMPNAME=LOCAL-LOGIN
echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGSERVER2%
ECHO LOGIN >> %LOGSERVER%
ECHO LOGIN >> %LOGSERVER2%
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 RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER2%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER2%

echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGSERVER2%
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%

lock-login.cmd


@echo off
cls
rem *** Script to add workstation is locked entry in log file ***
rem *** Syed Jahanzaib aacable@hotmail.com ***
rem Create Backup folder if not exists already
set TEMPLOC="C:\BACKUP"
if not exist "%TEMPLOC%" mkdir %TEMPLOC%
set LOGLOCAL="%TEMPLOC%\LOCAL.LOG"
set LOGSERVER="\\DC1\userlog\%USERNAME%.log"
set LOGSERVER2="\\DC1\userlog\%COMPUTERNAME%.log"
set IPFILE="%TEMPLOC%\IP.TXT"
set COMPFILE="%TEMPLOC%\COMPNAME.TXT"
set IPADD=
set DAMWIP=
set DAMWIPFILE="%TEMPLOC%\damwipfile.txt"
set COMPNAME=
del %IPFILE% 2> nul
del %COMPFILE% 2> nul
taskkill /F /IM nslookup.exe 2> nul
::# Get IP Address
for /f "skip=1 tokens=2 delims=[]" %%* in (
'ping.exe -n 1 %Computername%') Do (set "LOCALIP=%%*" & goto:exitFor1)
:exitFor1

netstat -na | find "3389" | find "ESTABLISHED" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %IPFILE%
set /p IPADD=<%IPFILE%
IF "%IPADD%"=="" (
set IPADD=x
)
set "filter=c:\backup/ip.txt"
for %%A in (%filter%) do if %%~zA==0 goto :skipname

nslookup %IPADD% | \\DC1\tools\sed -n "4p" | \\DC1\tools\awk "{print $2}" > %COMPFILE%
set /p COMPNAME=<%COMPFILE%

:skipname
netstat -na | find "6129" | find "ESTABLISHED" | \\DC1\tools\sed -n "2p" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %DAMWIPFILE%
set /p DAMWIP=<%DAMWIPFILE%
rem echo %DAMWIP%
set "filter=%DAMWIPFILE%"
rem for %%A in (%filter%) do if %%~zA==0 echo no damw
REM goto :skipdamw

IF "%DAMWIP%"=="127.0.0.1" (
set DAMWIP=x
)

IF "%DAMWIP%"=="" (
goto :nodamw
)

:skipdamw
if "%DAMWIP%"=="x" goto :1
nslookup %DAMWIP% | \\DC1\tools\sed -n "4p" | \\DC1\tools\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
:nodamw
set DAMWIP=x
:skip

if "%COMPNAME%"=="" set COMPNAME=LOCAL-LOGIN
echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGSERVER2%
ECHO LOCKED >> %LOGSERVER%
ECHO LOCKED >> %LOGSERVER2%
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 RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGSERVER2%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER2%

echo --------------------------------- >> %LOGSERVER%

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

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


LOGOFF.CMD

@echo off
echo LOGOFF -- Username: %USERNAME% / PC_name: %COMPUTERNAME% / Local_ip: %LOCALIP% / Rdp_client: %CLIENTNAME% / %DATE% %TIME% >> \\DC1\userlog\%USERNAME%.log
echo LOGOFF -- Username: %USERNAME% / PC_name: %COMPUTERNAME% / Local_ip: %LOCALIP% / Rdp_client: %CLIENTNAME% / %DATE% %TIME% >> \\DC1\userlog\%COMPUTERNAME%.log

 


RELOGIN-LOG.CMD

@echo off
rem *** Script to add log of session continue / relogin ***
rem *** Syed Jahanzaib aacable@hotmail.com ***
rem schtasks /delete /tn "Update LOGIN - LOG to Server" /f
cls
rem test file for computer name
rem Create Backup folder if not exists already
set TEMPLOC="C:\BACKUP"
if not exist "%TEMPLOC%" mkdir %TEMPLOC%
set LOGSERVER=
set LOGTOSERVERBYCOMPNAME=
set LOGSERVER="\\DC1\userlog\%USERNAME%.log"
set LOGTOSERVERBYCOMPNAME="\\DC1\userlog\%COMPUTERNAME%.log"
set LOGLOCAL="%TEMPLOC%\LOCAL.LOG"
set IPFILE="%TEMPLOC%\IP.TXT"
set COMPFILE="%TEMPLOC%\COMPNAME.TXT"
set IPADD=
set DAMWIP=
set DAMWIPFILE="%TEMPLOC%\damwipfile.txt"
set COMPNAME=
del %IPFILE% 2> nul
del %COMPFILE% 2> nul
taskkill /F /IM nslookup.exe 2> nul
::# Get IP Address
for /f "skip=1 tokens=2 delims=[]" %%* in (
'ping.exe -n 1 %Computername%') Do (set "LOCALIP=%%*" & goto:exitFor1)
:exitFor1

netstat -na | find "3389" | find "ESTABLISHED" | \\DC1\tools\awk "{print $3}" | \\DC1\tools\sed s/:.*// > %IPFILE%
set /p IPADD= %COMPFILE%
set /p COMPNAME= %DAMWIPFILE%
set /p DAMWIP= c:\backup\damwip.txt
set /p COMPNAME=> %LOGSERVER%
echo --------------------------------- >> %LOGTOSERVERBYCOMPNAME%
ECHO SESSION-CONTINUED >> %LOGSERVER%
ECHO SESSION-CONTINUED >> %LOGTOSERVERBYCOMPNAME%
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 RDP Client IP: %IPADD% - DW IP: %DAMWIP% / Remote Client PC: %COMPNAME% >> %LOGTOSERVERBYCOMPNAME%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGSERVER%
echo Username - %USERNAME% / Computer - %COMPUTERNAME% / %DATE% %TIME% >> %LOGTOSERVERBYCOMPNAME%
echo --------------------------------- >> %LOGSERVER%
echo --------------------------------- >> %LOGTOSERVERBYCOMPNAME%

REM --- LOCAL LOG FILE
echo --------------------------------- >> %LOGLOCAL%
ECHO S-RELOGIN >> %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 via GPO

 

1-task-scheudler

2-update-re-login

3-trigger

4-action

for login entries, I used startup script like welcome.vbs

welcome.vbs


' Domain Users Welcome Logon script / syed jahanzaib
dim objShell, objNetwork
set objShell = WScript.CreateObject("WScript.Shell")
set objNetwork = WScript.CreateObject("WScript.Network")
' let's display a welcome message
dim strDomain, strUser
strDomain = objNetwork.UserDomain
strUser = objNetwork.UserName
msgbox "Welcome to AGP (Pvt) Ltd. " & strUser & "!"
' msgbox "Welcome to the " & strDomain & ", " & strUser & "!"
' Syed jahanzaib


Result:

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

---------------------------------
---------------------------------
LOGOFF -- user1.id USER1_PC Mon 01/23/2017 17:03:34.68
---------------------------------
---------------------------------
LOGIN
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 8:31:15.80
---------------------------------
---------------------------------
LOCKED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:33:30.06
---------------------------------
---------------------------------
SESSION-CONTINUED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:36:22.70
---------------------------------
---------------------------------
LOCKED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:36:30.19
---------------------------------
---------------------------------
SESSION-CONTINUED
RDP Client IP: LOCAL-LOGIN - DW IP: x / Remote Client PC: LOCAL-LOGIN
Username - user1.id / Computer - USER1_PC / Tue 01/24/2017 9:49:58.99
---------------------------------

Uuserlog Folder Permission

At remote log server, you can set permission of userlog folder 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

Older Posts »

%d bloggers like this: