Syed Jahanzaib Personal Blog to Share Knowledge !

February 27, 2017

Radius Manager Theme/Skin Collection

Filed under: Radius Manager — Tags: , — Syed Jahanzaib / Pinochio~:) @ 3:33 PM

Following are few customized themes for DMASOFTLAB Radius manager , Designed by various web developers.

  1. Digital Theme [Responsive as well, made by KANGNDO]
  2. Green Theme
  3. Blue Theme

 


General Steps to install theme

I assume you have DMASoftlab Radius Manager 4.1.x version installed and must be fully functional.

  • Download the theme file, unrar it in any temporary folder. you can use `tar zxvf filename.tar.gz /destination_folder`
  • Copy (or let’s say Overwrite) all the contents including files/folders from the (unzipped) folder name radiusmanager in /var/www/radiusmanager (or for CENTOS, its /var/www/html/radiusmanager). You can cp -vr syntax /source /target
  • Clear the browser cache, and reload the ACP administration control panel) page.

.


1- Digital Theme

Download Link: Radius Manager KANGNDO Theme Official Link

🙂

Sample Images:

1

2

3

4


2- Green Theme

Green Theme Download Link

green-1

 


Will update more later

 

Regard’s
Syed Jahanzaib

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"'
  • 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%immi_ar0Z //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

February 13, 2017

Windows Event-Viewer Logging to MYSQL

Filed under: Uncategorized — Syed Jahanzaib / Pinochio~:) @ 2:10 PM

out-of-the-box

In our small office environment, we are using Windows 2008 R2 Active Directory for user management/authentication and control purpose. Dueto some standard operating procedure I was asked to log User Account Creation / Removal events in Linux base mySQL DB. Since windows doesn’t provide option to directly export event into linux base mysql, therefore I made an workaround for it using specific windows events tagged with task scheduler approach. Not to mention , this approach of using task scheduler with events is not a new thing, but it was definitely a bit confusing for a numbnuts like ME on how to acquire only the very specific fields trimmed according to our taste and get it logged in remote linux mysql db. but Alhamdulillah I managed to get it in few hours struggling.

z@iB

Items I used in this post are …

  • Windows 2008 R2 server with Active Directory
  • c:\temp folder to hold temporary information for the triggered event
  • e:\userlog\ folder to hold all logs
  • Event ID which will be logged in local log file and mySQL DB [as required] :

    4720

    New User Account Created

    4726

    User Account Deleted
  • Two batch files which will be executed when specific event will occur.
  • Mysql (I used mysql-5.7.17-winx64.zip) package to add entries in mySQL DB name events 

You can download mysql-5.7.17-winx64.zip from fmy Google Drive at

mysql-5.7.17-winx64 by Syed Jahanzaib


New Account Batch File for LOG [ac-new-log.bat]

@echo off
set MYSQL_HOST=10.0.0.1
set MYSQL_ID=your_mysqlid
set MYSQL_PASS=your_password
set MYSQL_DB=your_events
set MYSQL_TB=your_table
set ACTION=Account Created
set HOLDER=c:\temp\acnew-temp.txt
set LOGFILE=e:\userlog\users-created-log.log
type nul > %HOLDER%
wevtutil qe security /rd:true /f:text /c:1 /q:"*[System/EventID=4720]" > %HOLDER%
for /f "tokens=4" %%a in ('type %HOLDER% ^| find /i "Account Name"') do set accname=%%a
for /f "tokens=3" %%a in ('type %HOLDER% ^| find /i "Event ID"') do set eventid=%%a
for /f "tokens=2" %%a in ('type %HOLDER% ^| find /i "Date"') do set dt=%%a
set HEADER=%eventid% : %accname% / %ACTION% @ ... %dt%
echo %HEADER%
echo %HEADER% >> %LOGFILE%
c:\mysql\bin\mysql -h %MYSQL_HOST% -u%MYSQL_ID% -p%MYSQL_PASS% -e "use %MYSQL_DB%; INSERT INTO %MYSQL_TB% (eventid,type,account,msg) VALUES ('%eventid%','%ACTION
%','%accname%','%HEADER%');" 

Account Delete Batch File for LOG [ac-del-log.bat]

@echo off
set MYSQL_HOST=10.0.0.1
set MYSQL_ID=MY_ID
set MYSQL_PASS=MY_PASS
set MYSQL_DB=DB
set MYSQL_TB=TABLE
set ACTION=Account Deleted
set HOLDER=c:\temp\acdel-temp.txt
set LOGFILE=e:\userlog\users-deleted-log.log
type nul > %HOLDER%
wevtutil qe security /rd:true /f:text /c:1 /q:"*[System/EventID=4726]" > %HOLDER%
for /f "tokens=3" %%a in ('type %HOLDER% ^| find /i "Account Name"') do set accname=%%a
for /f "tokens=3" %%a in ('type %HOLDER% ^| find /i "Event ID"') do set eventid=%%a
for /f "tokens=2" %%a in ('type %HOLDER% ^| find /i "Date"') do set dt=%%a
set HEADER=%eventid% : %accname% / %ACTION% @ ... %dt%
echo %HEADER%
echo %HEADER% >> %LOGFILE%
c:\mysql\bin\mysql -h %MYSQL_HOST% -u%MYSQL_ID% -p%MYSQL_PASS% -e "use %MYSQL_DB%; INSERT INTO %MYSQL_TB% (eventid,type,account,msg) VALUES ('%eventid%','%ACTION%','%accname%','%HEADER%');" 

Attaching Batch files with Specific Event ID

On Domain Controller, open event viewer, goto 4720 event, right click and select ‘Attach Task to This Event‘ and in trigger select your batch file. (for account creation)

As showed in the image below

1- accoutn creation - attach batch file via event viewer.png

1.5 - triggers.PNG

2- trigger action.PNG

Repeat same for event id 4726.

Ok to finish it.


Creating DB in mySQL

Now create a new DB with required name and tables in mySQL …

One example is as follows.

mydb.sql


;-- MySQL dump 10.13 Distrib 5.5.54, for debian-linux-gnu (i686)
--
-- Host: localhost Database: events
-- ------------------------------------------------------
-- Server version 5.5.54-0ubuntu0.12.04.1

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `mymaindb`
--

DROP TABLE IF EXISTS `mymaindb`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mymaindb` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`eventid` varchar(40) DEFAULT NULL,
`type` varchar(255) NOT NULL,
`account` varchar(255) NOT NULL,
`msg` varchar(10000) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=462 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `mymaindb`
--

LOCK TABLES `mymaindb` WRITE;
/*!40000 ALTER TABLE `mymaindb` DISABLE KEYS */;
INSERT INTO `mymaindb` VALUES (459,'2017-02-13 08:39:45','4720','Account Created','testing.act','4720 : testing.act / Account Created @ ... 2017-02-13T12:02:05.777'),(461,'2017-02-13 08:49:46','4726','Account Deleted','testing.act','4726 : testing.act / Account Deleted @ ... 2017-02-13T12:02:38.521');
/*!40000 ALTER TABLE `mymaindb` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2017-02-13 14:47:11

to import above DB , use following command …

mysql -uroot -pROOTPASS < mydb.sql

Script Result in CMD:

Now try to create/delete a user account in active directory, and you will see the result in mysql db.

I recommend to debug first, to make sure things are working ok, execute the bat file manually to see the results

ac-new-log.bat

script result.PNG

.

Script Result in mySQL DB :

[all above fuss was made just to acquire only specific data trimmed as per out taste, and get it logged in in remote linux mySQL otherwise task was very easy in general]

phpmyadmin snapshot

php-result

mysql cmd line snapshot


mysql> select * from MY_DB;
+-----+---------------------+---------+-----------------+-------------+--------------------------------------------------------------------+
| id | datetime | eventid | type | account | msg |
+-----+---------------------+---------+-----------------+-------------+--------------------------------------------------------------------+
| 459 | 2017-02-13 13:39:45 | 4720 | Account Created | testing.act | 4720 : testing.act / Account Created @ ... 2017-02-13 13:39:45 |
| 461 | 2017-02-13 13:49:46 | 4726 | Account Deleted | testing.act | 4726 : testing.act / Account Deleted @ ... 2017-02-13 13:39:45 |
+-----+---------------------+---------+-----------------+-------------+--------------------------------------------------------------------+
2 rows in set (0.00 sec)


This is a itty-bitty example only, on how you can build your own customized solution using out of the box approach !

Syed Jahanzaib

February 8, 2017

Windows 7 Error: 0x800704cf / Unable to Access remote network shared resources

Filed under: Uncategorized — Syed Jahanzaib / Pinochio~:) @ 2:10 PM

windows-cannot-access-shared-folder

fotolia_3115040_m_tile

Windows cannot access \\testpc
Error Code: 0x800704cf

If your system is a workstation joined with local domain controller and you are getting above (same) error while trying to access ANY shared resource/system on the network, then you may try following fix. This error gave me straight 1 hour headache, so I really don’t want anyone else to bang their head on the wall for the same.

Fix >     :~)

  • Open (Currently active) Network Adapter properties,
  • UNCHECK the ‘Client for microsoft Networks‘  / OK
  • Open Regedit, & Navigate to “HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NetBT\Parameters”
  • Create a new key with following parameters

Type: DWORD Value
Name: SMBDeviceEnabled
Data: 1

  • Once Done, Restart your computer, & MAKE SURE TO ENABLE THE ‘CLIENT FOR MICROSOFT NETWORK’ in the adapter settings.

Now check and hopefully you will be able to access the shared resources without any error.

TIP/Additional Commands

  • ipconfig /flushdns
  • nbtstat -RR
  • netsh int ip reset
  • netsh winsock reset

Regard’s
Syed Jahanzaib

%d bloggers like this: