Archive for the ‘Windows Server’ Category

Powershell script for AD replication monitoring:

	Check AD Replication in a DC Server.
	Check AD Replication in a DC Server and returns Nagios output and code.
	Number of failed replications for warning treshold.
	Default 1.
	Number of failed replications for critical treshold.
	Default 5.
    OK: AD replication successful.
    WARNING: Failed replications equal to Warning treshold.
    CRITICAL: Failed replications equal to Critical treshold.
	.\Get-ADReplication.ps1 -Warning 5 -Critical 10
	Author:	Juan Granados 
	Date:	December 2017
# Variables
$NagiosOutput = ""
$Syncs = 0

# Get AD Replication Status for this DC
$SyncResults = Get-WmiObject -Namespace root\MicrosoftActiveDirectory -Class MSAD_ReplNeighbor -ComputerName $env:COMPUTERNAME |
	select SourceDsaCN, NamingContextDN, LastSyncResult, NumConsecutiveSyncFailures, @{N="LastSyncAttempt"; E={$_.ConvertToDateTime($_.TimeOfLastSyncAttempt)}}, @{N="LastSyncSuccess"; E={$_.ConvertToDateTime($_.TimeOfLastSyncSuccess)}} 

# Process result
foreach ($SyncResult in $SyncResults)
	if ($SyncResult.LastSyncResult -gt 0){
		$NagiosOutput += "$($SyncResult.NumConsecutiveSyncFailures) failed sync with DC $($SyncResult.SourceDsaCN) on $($SyncResult.NamingContextDN) at $($SyncResult.LastSyncAttempt), last success sync at $($SyncResult.LastSyncSuccess)."
		if ($SyncErrors -eq $Warning){
		elseif ($SyncErrors -eq $Critical) {
# Nagios Output
$NagiosOutput += " | Syncs=$($Syncs);;;; SyncErrors=$($SyncErrors);$Warning;$Critical;;"
if ($LASTEXITCODE -eq "2") {
	Write-Host "CRITICAL: Replication error: $($NagiosOutput)"
elseif ($LASTEXITCODE -eq "1") {
	Write-Host "WARNING: Replication error: $($NagiosOutput)"
elseif ($LASTEXITCODE -eq "0") {

	Write-Host "OK: replication is up and running.$($NagiosOutput)"


Install NSClient++ (if on Nagios 4.2.4 ), or  newest version on Windows server.

Edit C:\Program Files\NSClient++\nsclient.ini

; in flight - TODO

; Undocumented key
password = NAGIOS API

; Undocumented key
allowed hosts =, Nagios IP

; in flight - TODO

; Undocumented key
verify mode = none

; Undocumented key
insecure = true

extended response = 1
allow arguments = true
allow nasty characters = true

allow nasty characters = true

; in flight - TODO

; Undocumented key
CheckExternalScripts = enabled

; Undocumented key
CheckHelpers = 1

; Undocumented key
CheckEventLog = 1

; Undocumented key
CheckNSCP = 1

; Undocumented key
CheckDisk = 1

; Undocumented key
CheckSystem = 1

; Undocumented key
NRPEServer = enabled

[/settings/external scripts]

allow arguments = true

[/settings/external scripts/scripts]

check_ad_replication = cmd /c echo scripts\check_ad_replication.ps1 -Warning 5 -Critical 10 | PowerShell.exe -Command -

Restart NSClient++ (x64) service:

Actions on Nagios server

Test it first:

/usr/lib64/nagios/plugins/check_nrpe -H DC IP -c check_ad_replication

OK: replication is up and running. |'Syncs'=10 'SyncErrors'=0;5;10

Add command, edit /etc/nagios/objects/commands.cfg

define command {
command_name check_ad_replication
command_line /usr/lib64/nagios/plugins/check_nrpe -H -c check_ad_replication

Add this command as a service to Nagios host (Windows DC) /etc/nagios/conf.d/win_host.cfg

define service{
        use                             generic-service
        service_description             Check Active Directory Replication
        check_command                   check_nrpe!check_ad_replication

Go to Nagios portal and re-schedule the next check of the service (or wait until the next check)

And finally, check service status




Today, i had to log in to Hyper-V host, bust forgot IP/Hostname, luckily i didn’t forget VM, so i logged it to it and searched registry.

Note: VM have Integration Services installed.

Under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters registry key which reveal Hyper-V hosts are:

  • HostName
  • PhysicalHostName
  • PhysicalHostNameFullyQualified

Command line:

reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters" /v "PhysicalHostNameFullyQualified"


Get-ItemPropertyValue 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name 'PhysicalHostNameFullyQualified'

This script will check if current IP is in specific range

Function IsIpAddressInRange {
        [string] $ipAddress,
        [string] $fromAddress,
        [string] $toAddress

    $ip = []::Parse($ipAddress).GetAddressBytes()
    $ip = [system.BitConverter]::ToUInt32($ip, 0)

    $from = []::Parse($fromAddress).GetAddressBytes()
    $from = [system.BitConverter]::ToUInt32($from, 0)

    $to = []::Parse($toAddress).GetAddressBytes()
    $to = [system.BitConverter]::ToUInt32($to, 0)

    $from -le $ip -and $ip -le $to

# get current IP and perform comparation
$ip1 = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]

if (IsIpAddressInRange $ip1 "" "")
Write-Host "in Corporate Network"
Write-Host "in private network"

I have couple of Hyper-V hosts, and using function below i’m getting CPU,Memory and disk utilization for each of them, so i can decide on which one to create new VM.

function Get-Resources{  
                 $computername =$env:computername  
                 # Processor utilization 
                 #Get-WmiObject -ComputerName $computer -Class win32_processor -ErrorAction Stop | Measure-Object -Property LoadPercentage -Average | Select-Object * 
                $cpu = gwmi win32_perfformatteddata_perfos_processor -ComputerName $computername| ? {$ -eq "_total"} | select -ExpandProperty PercentProcessorTime  -ea silentlycontinue  
                 # Memory utilization 
                 $ComputerMemory = Get-WmiObject -ComputerName $computername  -Class win32_operatingsystem -ErrorAction Stop 
                 $Memory = ((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize) 
                 $RoundMemory = [math]::Round($Memory, 2) 
                 # Free disk space 
                 $disks = get-wmiobject -class "Win32_LogicalDisk" -namespace "root\CIMV2" -computername $computername 
                 $results = foreach ($disk in $disks)  
                 if ($disk.Size -gt 0) 
                   $size = [math]::round($disk.Size/1GB, 0) 
                   $free = [math]::round($disk.FreeSpace/1GB, 0) 
                   Drive = $disk.Name 
                   Name = $disk.VolumeName 
                   "Total Disk Size" = $size 
                   "Free Disk Size" = "{0:N0} ({1:P0})" -f $free, ($free/$size) 
                   } } }     

                   # Write results 
                   Write-host "Resources on" $computername "- RAM Usage:"$RoundMemory"%, CPU:"$cpu"%, Free" $free "GB" 
I Decided to use script block to run this function on remote machines
1..5 | % {

Invoke-Command -ScriptBlock  ${Function:Get-Resources} -ComputerName server$_ 

Visual Studio Code (aka VS Code ) is “a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS and Linux”.It is half-way between an text editor and an IDE. Main reasons for using Visual Studio Code

  • It comes with a built-in support for Javascript, TypeScript, nodeJs (auto-completion, syntax check, debug, …) , and according to Slant – 12 Best IDEs for TypeScript development as of 2019 it has the best typescript support
  • It has a great ecosystem of plugins for supporting other languages (C, C++, C#, Python, …), you can even install keymaps from text editors like sublime text, atom, vim
  • It is cross-platform :  Windows, Mac or Linux

In this post we’ll be installing Visual Studio code on Windows 10,open and execute Python script on remote linux box.

Creating SSH connection between Windows 10 and CentOS 7

Visual Studio Code uses SSH key-pair to connect to linux box.

So we’ll create key-pair on Windows 10 and copy Windows 10 public key to /~/.ssh/authorized_key file

Open Command prompt on Windows 10 and create keys.



On CentOS 7 create ~/.ssh/authorized_keys file, set appropriate permissions and copy content of public key Windows 10 file to ~/.ssh/authorized_keys</code

mkdir /root/.ssh
chmod -R 700 /root/.ssh/
vi /root/.ssh/authorized_keys
# copy content of your public key file to authorized_keys file
chmod 600 /root/.ssh/authorized_keys
systemctl restart sshd

Test ssh connection from Windows 10 to Linux

Open CMD and type

ssh -i c:\Users\user\.ssh\id_rsa root@

Install Visual Studio Code on Windows 10

Once installed, click on “Cog” button – extensions


Type Remote – SSH to install this extension – click on Install


Now, click again on “Cog” – Command Pallete


Type Remote – SSH: Open Configuration File


Select configuration file located in your User Profile


Change alias in some more descriptive, set IP address as hostname, user and path to private key, then save file


Now click green button (far bottom left) – select alias we set in configuration file


Connection to Linux should be established (Connected to), click Open folder, select desired folder – click OK


Now, open existing .py file (File – Open) or create new one (File – New File Save as .py)

Click debug – Add Configuration


Python extension will be offered for installation – Install Python extension


Select python interpreter (2 or 3 – it depends if one is installed on Linux box), choose whether


Click again on Debug icon – Add Configuration – Select Python File


Select interpreter





This script will take Hypervisor and VM as parameters and will check if VM is running, if not it will start it.

# Usage:
# .\script.ps1 -hypervisor "Hyper-V" -machine_name "my_windows"

$state = Get-VM -ComputerName $hypervisor $machine_name | Select-Object -ExpandProperty state

if ($state -ne "Running"){

Write-host "Starting vm: $machine_name"
start-vm $machine_name 


In this example we’ll remove eth0 interface, set eth1 as primary one and  route traffic to the internet through it.

I have 2 networks: eth0 in 4 subnet and eth1 in subnet specified in Vagrant file

eth0: flags=4163 mtu 1500
inet netmask broadcast
inet6 fe80::5054:ff:fe8a:fee6 prefixlen 64 scopeid 0x20 ether 52:54:00:8a:fe:e6 txqueuelen 1000 (Ethernet)
RX packets 13024 bytes 15552552 (14.8 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2981 bytes 316373 (308.9 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

eth1: flags=4163 mtu 1500
inet netmask broadcast
inet6 fe80::a00:27ff:fe3c:2b0a prefixlen 64 scopeid 0x20 ether 08:00:27:3c:2b:0a txqueuelen 1000 (Ethernet)
RX packets 212 bytes 24253 (23.6 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 162 bytes 26752 (26.1 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

eth2: flags=4163 mtu 1500
inet netmask broadcast
inet6 fe80::a00:27ff:fef9:abc9 prefixlen 64 scopeid 0x20 ether 08:00:27:f9:ab:c9 txqueuelen 1000 (Ethernet)
RX packets 32 bytes 3721 (3.6 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 22 bytes 2342 (2.2 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73 mtu 65536
inet netmask
inet6 ::1 prefixlen 128 scopeid 0x10
loop txqueuelen 1000 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

First ,we need to add NAT network, set  range to 192.168. 56.0/24 (same range as eth1) and assign it to eth1 (adapter 2)




set network to macth eth1 subnet.

First interface (eth0) as NAT


NIC 2, NAT Network, matches eth1 interface


3rd NIC host only network (matches range of eth2- 4)


Now, we need to remove int0 interface, and set default route to, Host Only network adapter  matching eth1 range (which will now be primary interface)


Now, on Virtual Box guest (Linux machine) run following commands:

ip link set eth0 down
ip link set eth0 name zenon
ip route add 0/0 via

Edit /etc/resolver.cong and add nameserver