Archive for the ‘Windows Server’ Category

Powershell script for AD replication monitoring:

<#
.SYNOPSIS
	Check AD Replication in a DC Server.
.DESCRIPTION
	Check AD Replication in a DC Server and returns Nagios output and code.
.PARAMETER Warning
	Number of failed replications for warning treshold.
	Default 1.
.PARAMETER Critical
	Number of failed replications for critical treshold.
	Default 5.
.OUTPUTS
    OK: AD replication successful.
    WARNING: Failed replications equal to Warning treshold.
    CRITICAL: Failed replications equal to Critical treshold.
.EXAMPLE
	.\Get-ADReplication.ps1 -Warning 5 -Critical 10
.NOTES 
	Author:	Juan Granados 
	Date:	December 2017
#&gt;
Param(
		[Parameter(Mandatory=$false,Position=0)] 
		[ValidateNotNullOrEmpty()]
		[int]$Warning=1,
		[Parameter(Mandatory=$false,Position=1)] 
		[ValidateNotNullOrEmpty()]
		[int]$Critical=5
)
# Variables
$SyncErrors=0
$LASTEXITCODE = 0
$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)."
		$SyncErrors++
		if ($SyncErrors -eq $Warning){
			$LASTEXITCODE = 1
		}
		elseif ($SyncErrors -eq $Critical) {
			$LASTEXITCODE = 2
		}			
	}
	else{
		$Syncs++
	}
}
# Nagios Output
$NagiosOutput += " | Syncs=$($Syncs);;;; SyncErrors=$($SyncErrors);$Warning;$Critical;;"
if ($LASTEXITCODE -eq "2") {
	Write-Host "CRITICAL: Replication error: $($NagiosOutput)"
    #$host.SetShouldExit(2)
	 
} 
elseif ($LASTEXITCODE -eq "1") {
	Write-Host "WARNING: Replication error: $($NagiosOutput)"
    #$host.SetShouldExit(1)
	 
} 
elseif ($LASTEXITCODE -eq "0") {

	Write-Host "OK: replication is up and running.$($NagiosOutput)"
	#$host.SetShouldExit(0)
	 
}

exit $LASTEXITCODE

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

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

; in flight - TODO
[/settings/default]

; Undocumented key
password = NAGIOS API

; Undocumented key
allowed hosts = 127.0.0.1, Nagios IP


; in flight - TODO
[/settings/NRPE/server]

; 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
[/modules]

; 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 192.168.98.21 -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
        host_name                       dc.example.com
        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

Host_status.png

 

Advertisements

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"

Powershell:

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 {
param(
        [string] $ipAddress,
        [string] $fromAddress,
        [string] $toAddress
    )

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

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

    $to = [system.net.ipaddress]::Parse($toAddress).GetAddressBytes()
    [array]::Reverse($to)
    $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 "192.168.0.10" "192.168.0.254")
{
Write-Host "in Corporate Network"
}
else
{
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{  
                 param(  
                 $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| ? {$_.name -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) 
                   [PSCustomObject]@{ 
                   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.

ssh-keygen

1.png

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

Install Visual Studio Code on Windows 10

Once installed, click on “Cog” button – extensions

1-1.png

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

1-2.PNG

Now, click again on “Cog” – Command Pallete

2.PNG

Type Remote – SSH: Open Configuration File

1-3.png

Select configuration file located in your User Profile

1-4.PNG

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

1-5.PNG

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

1-6.png

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

1-7-1.PNG

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

Click debug – Add Configuration

2-0.PNG

Python extension will be offered for installation – Install Python extension

2-1.PNG

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

1-10.png

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

2-2.png

Select interpreter

 

selecting_interpreter.png

 

2-3.PNG

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"
[string]$hypervisor
[string]$machine_name

$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 10.0.2.0/2 4 subnet and eth1 in 192.168.56.0/24 subnet specified in Vagrant file

eth0: flags=4163 mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
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 192.168.56.10 netmask 255.255.255.0 broadcast 192.168.56.255
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 10.0.2.10 netmask 255.255.255.0 broadcast 10.0.2.255
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 127.0.0.1 netmask 255.0.0.0
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)

1.PNG

File-Preferences-Network

3.PNG

set network to macth eth1 subnet.

First interface (eth0) as NAT

4.PNG

NIC 2, NAT Network, matches eth1 interface

3-1.PNG

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

5.PNG

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

5-1.PNG

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 192.168.56.1
ping 8.8.8.8

Edit /etc/resolver.cong and add nameserver