Thursday, July 13, 2017

ESX Snmp XML

<?xml version="1.0"?>
<config>
  <snmpSettings>
    <communities>public</communities>
    <enable>true</enable>
   

<engineid>00000063000000a10a0c1024</engineid></snmpSettings>
</config>

Eventviewer

@echo off
FOR /F "tokens=1,2*" %%V IN ('bcdedit') DO SET adminTest=%%V
IF (%adminTest%)==(Access) goto noAdmin
for /F "tokens=*" %%G in ('wevtutil.exe el') DO (call :do_clear "%%G")
echo.
echo goto theEnd
:do_clear
echo clearing %1
wevtutil.exe cl %1
goto :eof
:noAdmin
exit

VM add ram


[code]
$vms = Import-Csv C:\cvs\vms.cvs

Foreach ($vm in $vms) {
Get-VM -name $vm | Shutdown-VMGuest | Set-VM -MemoryMB "4096" | -MemReservationMB "4096" –Confirm:$False | Start-VM
}






CVS input

NAME
__PBTPW732NP_Temp
PBTPW732NP_Temp
BTPXDWIN7O10
clone-example
PBTPCTL01
PBTPDEVW764001
PBTPDEVW764002
PBTPDEVW764003
PBTPDEVW764004
PBTPDEVW764005

Check ESX Host NTP

#requires -version 2
<#

.SYNOPSIS
    Script can be used to report or setup NTP configuration on all vSphere hosts in given cluster

.DESCRIPTION
    Script takes vCenter Server name and host cluster name as mandatory parameters, NTPSources parameter is optional.
    If only mandatory parameters are provided script generates report aobut NTP settings for all vSphere hosts that are
    connected to cluster. Report include ntp service status, policy, up to 5 ntp servers configured and calculated time difference
    between host and system where the script is invoked. For consistent results script should be run from vCenter Server.
    Optional parameter NTPSources is a comma-separated list of ntp servers that will be configured in cluster.
    If NTPSources paramter is provided the script will configure ntp service to start together with host ("on" policy),
    configure ntp servers provided, set the time manually (to avoid drift problems) and restart ntpd.

.PARAMETER vCenterServer
    Mandatory parameter indicating vCenter server to connect to (FQDN or IP address)

.PARAMETER ClusterName
    Mandatory parameter indicating host cluster name where vms need to be reconfigured

.PARAMETER NTPSources
    Optional parameter indicating NTP servers that will be used

.EXAMPLE
    To configure two NTP servers provide all parameters.

    vmhost-timekeeping.ps1 -vCenterServer vcenter.seba.local -ClusterName Production-Cluster -NTPSources "time01.seba.local,time02.seba.local,10.0.0.1"

.EXAMPLE
    If you provide -NTPSources only the script will ask for mandatory parameters

    vmhost-timekeeping.ps1 -NTPSources "time01.seba.local,time02.seba.local,10.0.0.1"

.EXAMPLE
    To generate report about NTP service status provide only mandatory parameters.

    vmhost-timekeeping.ps1 -vcenter 10.0.0.1 -cluster tdq-cluster

.EXAMPLE
    Script will interactively ask for two mandatory parameters, no changes will be made, only report will be created.

    vmhost-timekeeping.ps1
#>

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
   [string]$vCenterServer,
   [Parameter(Mandatory=$True, Position=2)]
   [string]$ClusterName,
   [Parameter(Mandatory=$False, Position=3)]
   [string]$NTPSources=""
)

Function Write-And-Log {

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
   [string]$LogFile,
   [Parameter(Mandatory=$True,Position=2)]
   [string]$line,
   [Parameter(Mandatory=$False,Position=3)]
   [int]$ErrorCount=0,
   [Parameter(Mandatory=$False,Position=4)]
   [string]$type="terse"
)

$LogEntry = (Get-Date -Format ("[yyyy-MM-dd HH:mm:ss] ")) + $line
$ui = (Get-Host).UI.RawUI

if ($ErrorCount) {

   $ui.ForegroundColor = "red"
   $LogEntry = ">>> ERROR <<< " + $LogEntry
   Write-Output $LogEntry
   $LogEntry | Out-File $LogFile -Append

}
else {

   $ui.ForegroundColor = "green"
   if ($type -ne "terse"){
      Write-Output $LogEntry
      $LogEntry | Out-file $LogFile -Append
   }
   else {
      Write-Output $LogEntry
   }

}

$ui.ForegroundColor = "white"
}

#constans
$maxtimedrift = 1

#variables
$ScriptRoot = Split-Path $MyInvocation.MyCommand.Path
$StartTime = Get-Date -Format "yyyyMMddHHmmss_"
$csvoutfile = $ScriptRoot + "\" + $StartTime+ "time_config_report_for_$($ClusterName)_cluster.csv"
$logfilename = $ScriptRoot + "\" + $StartTime + "vmhost-timekeeping.log"
$transcriptfilename = $ScriptRoot + "\" + $StartTime + "vmhost-timekeeping_Transcript.log"
$all_vmhosts_timeconfig_info = @()
$total_errors = 0
$total_vmhosts = 0

#start PowerShell transcript
Start-Transcript -Path $transcriptfilename

#load PowerCLI snap-in
$vmsnapin = Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue
$Error.Clear()
if ($vmsnapin -eq $null)
    {
    Add-PSSnapin VMware.VimAutomation.Core
    if ($error.Count -eq 0)
        {
        write-and-log $logfilename "PowerCLI VimAutomation.Core Snap-in was successfully enabled." 0 "full"
        }
    else
        {
        write-and-log $logfilename "Could not enable PowerCLI VimAutomation.Core Snap-in, exiting script" 1 "full"
        Exit
        }
    }
else
    {
    write-and-log $logfilename "PowerCLI VimAutomation.Core Snap-in is already enabled" 0 "full"
    }

#check PowerCLI version
if (($vmsnapin.Version.Major -gt 5) -or (($vmsnapin.version.major -eq 5) -and ($vmsnapin.version.minor -ge 1))) {

    #assume everything is OK at this point
    $Error.Clear()

    #connect vCenter from parameter
    Connect-VIServer -Server $vCenterServer -ErrorAction SilentlyContinue | Out-Null

    #execute only if connection successful
    if ($error.Count -eq 0){

        #measuring execution time is really hip these days
        $stop_watch = [Diagnostics.Stopwatch]::StartNew()

        #use previously defined function to inform what is going on, anything else than "terse" will cause the message to be written both in logfile and to screen
        Write-And-Log $logfilename "vCenter $vCenterServer successfully connected" $error.count "full"

        #get all reachable vmhosts in cluster
        $vmhosts_in_cluster = get-vmhost -location $ClusterName | where-object { ($_.connectionstate -eq "connected") -or ($_.connectionstate -eq "maintenance") }

        #only if we've found some vmhosts
        if ($vmhosts_in_cluster){

            #if no NTP server given - create report only
            if ($NTPSources -eq ""){

                $mode = "checked"
                foreach ($vmhost in $vmhosts_in_cluster){

                        #all OK here
                        $error.Clear()
                        $total_vmhosts += 1
           
                        #display nice progress bar in PowerCLI window
                        write-progress -Activity "Gathering host NTP config report" -Status "Percent complete" -PercentComplete (($total_vmhosts / $vmhosts_in_cluster.count) * 100) -CurrentOperation "$("{0:N2}" -f (($total_vmhosts / $vmhosts_in_cluster.count) * 100))% complete"
                   
                        #retrieve NTPD information
                        $single_vmhosts_timeconfig_info = New-Object PSObject
                        $single_vmhosts_timeconfig_info | Add-Member -Name "VmHostName" -Value $vmhost.name -MemberType NoteProperty
                        $single_vmhosts_timeconfig_info | Add-Member -Name "VmHostTZ" -Value $vmhost.TimeZone -MemberType NoteProperty
                        $ntpservice = $vmhost | get-vmhostservice | Where-Object {$_.key -eq "ntpd"}
                        $single_vmhosts_timeconfig_info | Add-Member -Name "NTPDisRunning" -Value $ntpservice.running -MemberType NoteProperty
                        $single_vmhosts_timeconfig_info | Add-Member -Name "NTPDPolicy" -Value $ntpservice.policy -MemberType NoteProperty
                   
                        #retrieve NTP Servers configured, report only first 5
                        $ntpserver = @($vmhost | get-vmhostntpserver)
                        for ($index = 0; $index -lt 5; $index++){
                            if ($ntpserver[$index]){
                                $single_vmhosts_timeconfig_info | Add-Member -Name "NTPServer$($index)" -Value $ntpserver[$index] -MemberType NoteProperty
                            }
                            else{
                                $single_vmhosts_timeconfig_info | Add-Member -Name "NTPServer$($index)" -Value "none" -MemberType NoteProperty
                            }
                        }
                   
                        #calculate time difference between host and system this script is invoked from
                        $hosttimesystem = get-view $vmhost.ExtensionData.ConfigManager.DateTimeSystem
                        $timedrift = ($hosttimesystem.QueryDateTime() - [DateTime]::UtcNow).TotalSeconds
                   
                        #raise alarm if difference bigger than acceptable
                        if([math]::abs($timedrift) -gt $maxtimedrift){
                            Write-And-Log $logfilename "Time difference exceeded for host $($vmhost.name)!" 1 "full"
                            Write-And-Log $logfilename "Acceptable difference: $("{0:N2}" -f $maxtimedrift)s Current difference: $("{0:N2}" -f $timedrift)s" 1 "full"
                            $total_errors++
                        }
                        $single_vmhosts_timeconfig_info | Add-Member -Name "TimeDrift" -Value $timedrift -MemberType NoteProperty
                   
                        $all_vmhosts_timeconfig_info += $single_vmhosts_timeconfig_info
                        $total_errors += $error.Count
                        Write-And-Log $logfilename "Host $($vmhost.name) added to report" $error.Count "terse"
                }
               
                #export to CSV
                $all_vmhosts_timeconfig_info | Export-Csv -Path $csvoutfile -NoTypeInformation
                Write-And-Log $logfilename "Report created in $($csvoutfile)" $total_errors "full"
            }
           
            #if NTP servers provided - configure them
            else {
           
                #give the engineer invoking the script chance to abort
                Write-And-Log $logfilename "NTP configuration for all vSphere hosts in cluster $ClusterName will be RESET" 1 "full"
                Write-And-Log $logfilename "This is your LAST CHANCE TO ABORT" 1 "full"
                Write-And-Log $logfilename "Press Y + ENTER to continue" 0 "full"
                Write-And-Log $logfilename "Press any other key + ENTER to ABORT..." 1 "full"
                $response = read-host
                if ( $response -ne "Y" ) {
                    write-and-log $logfilename "Operation ABORTED, no changes have been made to NTP settings" 1 "full"
                    #exit
                } else {
               
                    #let's sanitize input a little and leave only NTP servers that respond to ping (from system where this script is invoked!)
                    $NTPSourcesArray = $NTPSources.Split(",") | Where-Object { Test-Connection -ComputerName $_ -Quiet -Count 1}
                    $mode = "configured"
                   
                    #make sure we've got some NTP servers left
                    if ($NTPSourcesArray){
                       
                        foreach ($vmhost in $vmhosts_in_cluster){
                   
                                #all OK here
                                $error.Clear()
                                $total_vmhosts += 1
                           
                                #display nice progress bar in PowerCLI window
                                write-progress -Activity "Configuring NTP for hosts" -Status "Percent complete" -PercentComplete (($total_vmhosts / $vmhosts_in_cluster.count) * 100) -CurrentOperation "$("{0:N2}" -f (($total_vmhosts / $vmhosts_in_cluster.count) * 100))% complete"
                           
                                #stop ntp service on host
                                $ntpservice = $vmhost | get-vmhostservice | Where-Object {$_.key -eq "ntpd"}
                                stop-vmhostservice -HostService $ntpservice -confirm:$False | out-null
                           
                                #clear current NTP servers
                                $current_NTPSources = @($vmhost | get-vmhostntpserver)
                                foreach ($current_NTPSource in $current_NTPSources){
                                        remove-vmhostntpserver -ntpserver $current_NTPSource -vmhost $vmhost -confirm:$false | Out-Null
                                }
                           
                                #and set new NTP servers
                                foreach ($NTPSource in $NTPSourcesArray) {
                                        add-vmhostntpserver -ntpserver $NTPSource -vmhost $vmhost -confirm:$False | out-null
                                }
                           
                                #set service policy to start and stop with host
                                set-vmhostservice -HostService $ntpservice -Policy "on" -confirm:$False | out-null
                           
                                #set vmhost time manually (to avoid problem with too big drift) to match time of system where script is invoked
                                $hosttimesystem = get-view $vmhost.ExtensionData.ConfigManager.DateTimeSystem
                                $hosttimesystem.UpdateDateTime([DateTime]::UtcNow)
                           
                                #finally - start NTP on vmhost
                                start-vmhostservice -HostService $ntpservice -confirm:$False | out-null
                           
                                $total_errors += $error.Count
                                Write-And-Log $logfilename "Host $($vmhost.name) NTP configuration changed" $error.Count "terse"
                        }
                   }    
                   else{
                        Write-And-Log $logfilename "None of NTP servers provided ($NTPSources) is responding, exiting" 1 "full"
                        $total_errors++
                   }    
                }
            }
        }
        else {
            $total_errors += $Error.Count
        }
        $stop_watch.Stop()
        $elapsed_seconds = ($stop_watch.elapsedmilliseconds)/1000
       
        #farewell message before disconnect
        Write-And-Log $logfilename "Total of $total_vmhosts hosts $mode in $("{0:N2}" -f $elapsed_seconds)s, $total_errors ERRORS reported, exiting" $total_errors "full"
       
        #disconnect vCenter
        Disconnect-VIServer -Confirm:$false -Force:$true
    }
    else {
        Write-And-Log $logfilename "Error connecting vCenter server $vCenterServer, exiting" $error.count "full"
    }
}
else {
    write-and-log $logfilename "This script requires PowerCLI 5.1 or greater to run properly" 1 "full"
}
Stop-Transcript

Change ESX Host Passwords

Param ( [String] $vCenter = (Read-Host "Enter Virtual Center"),
[String] $Location = (Read-Host "Enter VMHost Location (can be a vCenter, DataCenter, Cluster or * for all)"),
[System.Security.SecureString] $RootPassword = (Read-Host "Enter current root password" -AsSecureString),
[System.Security.SecureString] $NewPassword = (Read-Host "Enter new root password" -AsSecureString),
[System.Security.SecureString] $NewPasswordVerify = (Read-Host "Re-enter new root password" -AsSecureString)
)

<#
    .SYNOPSIS
      Displays a list of WMI Classes based upon a search criteria
    .EXAMPLE
     Get-WmiClasses -class disk -ns root\cimv2"
     This command finds wmi classes that contain the word disk. The
     classes returned are from the root\cimv2 namespace.
  #>

# Define a log file
$LogFile = "Change-HostPasswords.csv"
# Rename the old log file, if it exists
if(Test-Path $LogFile) {
$DateString = Get-Date((Get-Item $LogFile).LastWriteTIme) -format MMddyyyy
Move-Item $LogFile "$LogFile.$DateString.csv" -Force -Confirm:$false
}
# Add some CSV headers to the log file
Add-Content $Logfile "Date,Location,Host,Result"

# Hide the warnings for certificates (or better, install valid ones!)
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false | Out-Null

# Create credential objects using the supplied passwords
$RootCredential = new-object -typename System.Management.Automation.PSCredential -argumentlist "root",$RootPassword
$NewRootCredential = new-object -typename System.Management.Automation.PSCredential -argumentlist "root",$NewPassword
$NewRootCredentialVerify = new-object -typename System.Management.Automation.PSCredential -argumentlist "root",$NewPasswordVerify

# Test that the new password and verified one match, if not abort!
if(($NewRootCredential.GetNetworkCredential().Password) -ne ($NewRootCredentialVerify.GetNetworkCredential().Password)) {
throw "Passwords do not match!!!"
}


# Connect to the vCenter server
Connect-VIServer $vCenter | Out-Null

# Create an object for the root account with the new pasword
$RootAccount = New-Object VMware.Vim.HostPosixAccountSpec
$RootAccount.id = "root"
$RootAccount.password = ($NewRootCredential.GetNetworkCredential().Password)
$RootAccount.shellAccess = "/bin/bash"

$VMHosts = Get-VMHost -Location $Location
# Get the hosts from the Location and for each host
$VMHosts | % {
# Disconnect any connected sessions - prevents errors getting multiple ServiceInstances
$global:DefaultVIServers | Disconnect-VIServer -Confirm:$false
Write-Debug ($_.Name + " - attempting to connect")
# Create a direct connection to the host
$VIServer = Connect-VIServer $_.Name -User "root" -Password ($RootCredential.GetNetworkCredential().Password) -ErrorAction SilentlyContinue
# If it's connected
if($VIServer.IsConnected -eq $True) {
Write-Debug ($_.Name + " - connected")
$VMHost = $_
# Attempt to update the Root user object using the account object we created before
# Catch any errors in a try/catch block to log any failures.
try {
$ServiceInstance = Get-View ServiceInstance
$AccountManager = Get-View -Id $ServiceInstance.content.accountManager
$AccountManager.UpdateUser($RootAccount)
Write-Debug ($VMHost.Name + " - password changed")
Add-Content $Logfile ((get-date -Format "dd/MM/yy HH:mm")+","+$VMHost.Parent+","+$VMHost.Name+",Success")
}
catch {
Write-Debug ($VMHost.Name + " - password change failed")
Write-Debug $_
Add-Content $Logfile ((get-date -Format "dd/MM/yy HH:mm")+","+$VMHost.Parent+","+$VMHost.Name+",Failed (Password Change)")
}
# Disconnect from the server
Disconnect-VIServer -Server $VMHost.Name -Confirm:$false -ErrorAction SilentlyContinue
Write-Debug ($VMHost.Name + " - disconnected")
} else {
# Log any connection failures
Write-Debug ($_.Name+" - unable to connect")
Add-Content $Logfile ((get-date -Format "dd/MM/yy HH:mm")+","+$_.Parent+","+$_.Name+",Failed (Connection)")
}
}

Upgrade UCS steps

BTP-FC-03# sho zoneset active vsan 1 | b PBTP-ESXSQL-01-BTP-NEXSAN-CT01LP
  zone name PBTP-ESXSQL-01-BTP-NEXSAN-CT01LP vsan 1
    device-alias PBTP-ESXSQL-01
  * fcid 0xbf1c00 [device-alias PBTP-NEXSAN-CT01LP]



1.   Create a All configuration backup under UCS Manager Admin and save configuration locally

2.   Verify I/O Modules and Fabric Interconnects modules for High availability and operable

3.   Verify servers and adapters are operable

4.   Download approved Cisco UCS 2.2(5B) Infrastructure bundle, C & B series server bundle
5.   Verify Fabric A/B for adequate storage is available for firmware update

6.   Upload firmware to CDC firmware management storage for staging

7.   Disable call home (turn off)

8.   Equipment tab - Firmware management - activate firmware

9.   UCS Manager filter - adjust firmware level to 2.2 (b) and check Ignore Compatibility check - update

10. UCS Manager will close session and re-login and notice new version 2.2 (5b)

11. Equipment - Firmware Management - update firmware - firmware auto install - Install Infrastructure Firmware - change version to 2.2(5b)  -check Upgrade Now - ok

12. Verify data path has been restored after update, equipment - FSM

13. VIF status check - Check each Chassis - Server - adapter - check each HBA is operable and vNICs - repeat for every Chassis and server verify all is operable

14. Verify Fabric Interconnect A - High avaibilty is UP and ready

15. Verify Fabric Interconnect B - High avaibilty is UP and ready

16. Verify Equipment - Firmware Management - Installed firmware - verify secoundary IO module is 2.2(5b) for each CDC Chassis

17. Verify Equipment - Firmware Management - Installed firmware - verify secoundary Fabric Interconnect B Kernal is running v2.2(5b) CDC Chassis

18. Acknowledge the reboot of FabricInterconnect A - click pending Activities - User acknowledge Activities - Fabric Interconnects - REBOOT - Yes

19. Equipment - Firmware Management - Firmware Auto Install - Install Server firmware - choose 2.2(5b) for C and B series



Server firmware update:

1. PCDCESX01 enter maintenance mode - SVMOTION local storage VMs if needed - Shutdown ESX host

2. UCS Manager - conitue from step 19

3. Click Root - find PCDESX01 on Chassis 1 and update server and Chassis service profiles - note Impact Endpoint summary - review server that will reboot after upgrade

4. Click install and confirm install - click pending activities - Acknowledge reboots - status will change for server and then reboot  

5. Upgrade completed

6. Enable UCS call home alerts - admin

7. Power PCDESX01 on

8. Exit ESX maintenance mode

9. Relocate local VMs if needed

10. Verify ZEN apps  

LDAP examples

PATLDC01.st.com


CN=LDAPQuery, OU=Admin and Service Accounts,DC=st,DC=com

DC=st,DC=com

sAMAccountName=$userid,


sAMAccountName=$userid,


CN=DirectoryBind,OU=Admin and Service Accounts,DC=st,DC=com


CN=UCS Admins,OU=Admin and Service Accounts,DC=st,DC=com








bind user

CN=-service-ucs,OU=Service Accounts,OU=Georgia,OU=Admin and Service Accounts,DC=st,DC=com


group
CN=UCS Admin,OU=Admin and Service Accounts,DC=st,DC=com


CN=-service-ucs,OU=Service Accounts,OU=Georgia,OU=Admin and Service Accounts,DC=st,DC=com

DC=st,DC=com

sAMAccountName=$userid

Vmware NSX SSL creation 

Using OpenSSL for NSX Manager SSL import: Creates CSR and 4096 bit KEY Creating NSX 6.4.2 SSL    openssl req -out nsxcert.csr -newkey rsa:40...