Config-ESXi6.0u3
##############################################################
#Auto Post Configuration - ESXi 6.0
#Version 1.1
#Created Date: Jun 1, 2017
##############################################################
Add-Pssnapin vmWARE.VimAutomation.Core
#vCenter #
${vcip} = "172.16.8.10" # vCenter server IP, for coredump config
#DNS #
${dns1} = "172.16.8.250" # dns server1
${dns2} = "172.16.8.251" # dns server2
${Domain} = "contoso.com" # domain name
${HostNamePrefix} = "ConESXI01" # hostname perfix
#NTP #
${ntpsrv1} = "172.16.8.253" # ntp server 1
#Syslog #
${syslogsrv} = ${vcip} # syslog server IP
${logRotate} = 100 # number of rotated logs to keep
${logSize} = 10240 # size(KB) of logs before rotation
#NIC #
${ManagementActiveNic} = "vmnic1" # active nic for management traffic
${ManagementStandbyNic} = "vmnic6" # standy nic for management traffic
#VLAN #
${ManagementVLan} = "123" # vlan id of Management network
${vMotionVLan} = "124" # vlan id of vMotion network
${BackupVLan} = "125" # vlan id of Backup network
${ManagementPG} = "Management Network" # Portgroup name of Management network
${vMotionPG} = "vMotion" # Portgroup name of vMotion network
${BackupPG} = "Backup" # Portgroup name of Backup network
${vMotionNetwork} = "10.195.114" # first 3 octets of vMotion network
${vMotionNM} = "255.255.255.0" # subnet mask of vMotion network
${BackupNetwork} = "172.16.8" # first 3 octets of Backup network
${BackupNM} = "255.255.255.0" # subnet mask of Backup network
#Hardening #
${HostHardening} = "1" # 1-harden host, 0-don't harden host
${PasswordQualityControl} = "retry=3 min=12,12,12,12,12" # raw options for pam module
${AccountUnlockTime} = 120 # duration(sec) to lock out a account after exceeding the maximum allowed failed login attempt
${AccountLockFailures} = 3 # maximum allowed failed login attempts
${DcuiTimeOut} = 600 # idle time(sec) before DCUI is automatically logged out
${ESXiShellInteractiveTimeOut} = 900 # idle time(sec) before shell is automatically logged out
${ESXiShellTimeOut} = 86400 # time(sec) before automatically disabling local and remote shell access
ESX-install
##############################################################
#Auto Post Configuration - ESXi 6.0
#Version 1.2
#Created Date: Jun 1, 2017
##############################################################
###
Write-Host
Write-Host "ESXi postinstall configuration script" -ForegroundColor Cyan
Write-Host "-------------------------------------------" -ForegroundColor Cyan
Write-Host
###
$scriptpath = get-location
$cfgFile = Read-Host "Please specify a configuration file (Config-XXX.ps1)"
if ((Test-Path .\$cfgFile) -eq $false){
Write-Host
Write-Host "Configuration file does not exist." -foregroundcolor black -backgroundcolor yellow
Write-Host " "
Write-Host "Script will exit now. Please re-run if needed..."
Write-Host
Start-Sleep -s 1
exit
}
. .\$cfgFile
${Log-Name} = ".\log\Postinstall_log_"+(Get-Date -UFormat "%Y%m%d%H%M%S")+".txt"
function REM($s) {write-host $s -foreground Green; $s = (Get-Date -UFormat "%Y %b %d %T ") + $s; $s | add-content ${Log-Name}}
$ESXIP = Read-Host "Enter the ESX IP for post config"
$ESXHostname = Read-Host "Enter the ESX hostname e.g (${HostNamePrefix}00X)"
$rootpwd = Read-Host -assecurestring "Enter the root password"
$rootpwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($rootpwd))
if (${HostHardening} -eq "1"){
$viadmpwd = Read-Host -assecurestring "Enter password for new local account (vi-adm)"
$viadmpwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($viadmpwd))
}
if ($ESXIP -eq "" -or $ESXHostname -eq ""){
Write-Host
Write-Host "Please specify a IP and Host Name " -foregroundcolor black -backgroundcolor yellow
Write-Host " "
Write-Host "Script will exit now. Please re-run if needed..."
Write-Host
Start-Sleep -s 3
exit
}
${Log-Name} = ".\log\Postinstall_log_"+$ESXIP+".txt"
###
#Discconect any existing connections
Try{ Disconnect-viserver -confirm:$false -ErrorAction Stop } Catch {}
#Connect to the esx host directly
Try{
Connect-VIServer $ESXIP -User root -Password $rootpwd -ErrorAction Stop -WarningAction silentlyContinue | out-null
REM("Connected to $ESXIP")
}Catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.ViServerConnectionException]{
Write-Host "Unable to connect to $ESXIP" -ForegroundColor Red
exit
}Catch [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InvalidLogin]{
Write-Host "Incorrect username or password." -ForegroundColor Red
exit
}Catch {
Write-Warning $error[0].Exception.GetType().FullName
Write-Warning $error[0].Exception.Message
exit
}
###
if ( (Get-VM) -eq $null ){
Set-VMHost -State "Maintenance" | out-null
REM("Put the host into maintenance mode")
Start-Sleep -s 3
}
#Make sure the host is in maintenance mode
if ( (Get-VMHost | Select -ExpandProperty ConnectionState) -ne "Maintenance" ) {
Write-Host "Please put the host into maintenance mode before running this script" -ForegroundColor Red
exit
}
###
$last_octet = $ESXIP.Split('.')[3]
$vMotionIP = "{0}.{1}" -f ${vMotionNetwork}, $last_octet
$BackupIP = "{0}.{1}" -f ${BackupNetwork}, $last_octet
$localDatastoreName = "{0}_Local" -f $ESXHostname
$scratchDir = ".locker-{0}" -f $ESXHostname
###
#Rename local datastore & Set Scratch Location
Write-Host
REM("Rename local datastore")
Get-Datastore "datastore1*" | Set-datastore -name $localDatastoreName | out-null
$ds = Get-Datastore "*_Local"
$scratchLocation = "{0}/{1}" -f $ds.ExtensionData.info.url, $scratchDir
try{
Write-Host
REM("Set scratch location")
New-PSDrive -Name "mnt_ds" -Root \ -PSProvider VimDatastore -Datastore $ds | out-null
Set-Location "mnt_ds:" | out-null
New-Item $scratchDir -ItemType directory -ErrorAction Stop -WarningAction silentlyContinue | out-null
Get-AdvancedSetting -Name "ScratchConfig.ConfiguredScratchLocation" -Entity $ESXIP | Set-AdvancedSetting -Value $scratchLocation -confirm:$false -ErrorAction Stop -WarningAction silentlyContinue | out-null
Set-Location $scriptpath | out-null
$scratchConfigured = 1
}Catch {
Set-Location $scriptpath | out-null
REM("Cannot set scratch location")
}
###
$esxcli = Get-EsxCli -WarningAction silentlyContinue #deprecated #$esxcli = Get-EsxCli -V2
$vmHostNetworkInfo = Get-VmHostNetwork
$Switch0 = "vSwitch0"
###
#Set hostname
Write-Host
REM("Setup hostname")
Set-VMHostNetwork -Network $vmHostNetworkInfo -Hostname $ESXHostname -IPv6Enabled $false -WarningAction silentlyContinue | out-null
###
###
#Set the DNS servers and domain name
Write-Host
REM("Add DNS servers")
Set-VMHostNetwork -Network $vmHostNetworkInfo -DnsAddress ${dns1}, ${dns2} | out-null
Set-VMHostNetwork -Network $vmHostNetworkInfo -DomainName ${Domain} -SearchDomain ${Domain} | out-null
###
###
#vSwitch configuration
Write-Host
#Creates a vMotion portgroup on vSwitch0
try{
New-VMHostNetworkAdapter -PortGroup ${vMotionPG} -VirtualSwitch $Switch0 -IP $vMotionIP -SubnetMask ${VMotionNM} -VMotionEnabled:$true -ErrorAction Stop | out-null
REM("Create vMotion portgroup and Configure IP")
}Catch {
REM("Cannot create vMotion portgroup")
}
#Creates a Backup portgroup on vSwitch0
try{
New-VMHostNetworkAdapter -PortGroup ${BackupPG} -VirtualSwitch $Switch0 -IP $BackupIP -SubnetMask ${BackupNM} -VMotionEnabled:$false -ErrorAction Stop | out-null
REM("Create Backup portgroup and Configure IP")
}Catch {
REM("Cannot create backup portgroup")
}
#Set vlan for the vSS portgroups
REM("Set vlan for the vSS portgroups")
Get-VirtualPortgroup -Name ${vMotionPG} | Set-VirtualPortGroup -VlanId ${vMotionVLan} | out-null
Get-VirtualPortgroup -Name ${BackupPG} | Set-VirtualPortGroup -VlanId ${BackupVLan} | out-null
Get-VirtualPortgroup -Name "VM Network" | Set-VirtualPortGroup -VlanId ${ManagementVLan} | out-null
#Configures vSwitch Teaming Policy and Security Policy
REM("Configure Teaming Policy for the vSS and its portgroups")
[array]$nics = ${ManagementActiveNic}, ${ManagementStandbyNic}
Set-VirtualSwitch -VirtualSwitch $Switch0 -Nic $nics -confirm:$false | out-null
Get-VirtualSwitch -Name $Switch0 | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive ${ManagementActiveNic}, ${ManagementStandbyNic} | out-null
Get-VirtualPortgroup -name ${ManagementPG} | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive ${ManagementActiveNic} -MakeNicStandby ${ManagementStandbyNic} | out-null
Get-VirtualPortgroup -name ${vMotionPG} | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive ${ManagementStandbyNic} -MakeNicStandby ${ManagementActiveNic} | out-null
###
###
#Configures NTP and open the firewall port
REM("Configure NTP")
try{
Add-VMHostNtpServer -NtpServer ${ntpsrv1} -ErrorAction Stop -WarningAction silentlyContinue | out-null
Add-VMHostNtpServer -NtpServer ${ntpsrv2} -ErrorAction Stop -WarningAction silentlyContinue | out-null
}Catch {
REM("Cannot configure NTP")
}
Get-VMHostFirewallException "NTP Client" | Set-VMHostFirewallException -enabled:$true | out-null
Get-VmHostService | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService | out-null
Get-VmHostService | Where-Object {$_.key -eq "ntpd"} | Set-VMHostService -policy "automatic" | out-null
###
###
#Enable and configure the syslog
REM("Configure syslog")
Get-VMHostFirewallException "syslog" | Set-VMHostFirewallException -enabled:$true | out-null
Get-AdvancedSetting -Name Syslog.global.defaultRotate -Entity $ESXIP | Set-AdvancedSetting -Value ${logRotate} -confirm:$false | out-null
Get-AdvancedSetting -Name Syslog.global.defaultSize -Entity $ESXIP | Set-AdvancedSetting -Value ${logSize} -confirm:$false | out-null
Get-AdvancedSetting -Name Syslog.global.logHost -Entity $ESXIP | Set-AdvancedSetting -Value "udp://${syslogsrv}:514" -confirm:$false | out-null
Get-AdvancedSetting -Name Syslog.global.logDirUnique -Entity $ESXIP | Set-AdvancedSetting -Value $true -confirm:$false | out-null
###
###
#Set default path policy for local SAS & 3PAR FC SAN
#Usage: storage nmp satp rule add -b, -c, -e, -d, -D, -f, -M, -o, -P, -O, -s, -R, -t, -V
#Usage: storage nmp satp rule add -boot,-claim-option, -description,-device,-driver,-force,-model,-option,-psp,-psp-option, -satp,-transport,-type,-vendor
try{
$esxcli.storage.nmp.satp.rule.add($null,$null,"Serial Attached SCSI Devices",$null,$null,$true,$null,"enable_local",$null,$null,"VMW_SATP_LOCAL","sas",$null,$null)
REM("Add SATP rule for local SAS disk")
}Catch {
REM("Cannot add SATP rule for local SAS disk")
}
try{
$esxcli.storage.nmp.satp.rule.add($null,"tpgs_on","HP 3PAR Custom iSCSI/FC/FCoE ALUA Rule",$null,$null,$true,"VV",$null,"VMW_PSP_RR","iops=1","VMW_SATP_ALUA",$null,$null,"3PARdata")
REM("Add SATP rule for 3PAR")
}Catch {
REM("Cannot add SATP rule for 3PAR")
}
###
###
#Enable and configure the dump collector
REM("Configure coredump")
$esxcli.system.coredump.network.set($null, "vmk0", $null, ${vcip}, 6500)
$esxcli.system.coredump.network.set($true)
###
if (${HostHardening} -eq "1"){
###
#Host Hardening
REM("Hardening Host")
#1. config-ntp (please refer to the above NTP section)
#2. config-persistent-logs (please refer to the above Scratch section)
#3. config-snmp (disable)
REM("config-snmp")
Get-VMHostService | where {$_.Key -eq "snmpd"} | Set-VMHostService -Policy Off -confirm:$false | out-null
Get-VMHostSnmp | Set-VMHostSnmp -Enabled:$false | out-null
#4. create-local-admin
REM("create-local-admin")
New-VMHostAccount -Id "vi-adm" -Password $viadmpwd -Description "Operation Account" | out-null
New-VIPermission -Entity $ESXIP -Principal "vi-adm" -Role "Admin" -Propagate:$true | out-null
#5. disable-esxi-shell
REM("disable-esxi-shell")
Get-VMHostService | where {$_.Key -eq "TSM"} | Set-VMHostService -Policy Off -confirm:$false | out-null
Get-VmHostService | where {$_.Key -eq "TSM"} | Stop-VMHostService -confirm:$false | out-null
#6. disable-ssh
REM("disable-ssh")
Get-VMHostService | where {$_.Key -eq "TSM-SSH"} | Set-VMHostService -Policy Off -confirm:$false | out-null
Get-VmHostService | where {$_.Key -eq "TSM-SSH"} | Stop-VMHostService -confirm:$false | out-null
#7. enable-host-profiles (manually add the host to host profile via vCenter)
#8. enable-normal-lockdown-mode (manually enable lockdown mode when adding host to vCenter)
#9. enable-remote-dump (please refer to the above dump collector section)
#10. enable-remote-syslog (please refer to the above syslog section)
#11. set-account-auto-unlock-time
REM("set-account-auto-unlock-time")
Get-AdvancedSetting -Name Security.AccountUnlockTime -Entity $ESXIP | Set-AdvancedSetting -Value ${AccountUnlockTime} -confirm:$false | out-null
#12. set-account-lockout
REM("set-account-lockout")
Get-AdvancedSetting -Name Security.AccountLockFailures -Entity $ESXIP | Set-AdvancedSetting -Value ${AccountLockFailures} -confirm:$false | out-null
#13. set-dcui-access
REM("set-dcui-access")
Get-AdvancedSetting -Name DCUI.Access -Entity $ESXIP | Set-AdvancedSetting -Value "root,vi-adm" -confirm:$false | out-null
#14. set-dcui-timeout
REM("set-dcui-timeout")
Get-AdvancedSetting -Name UserVars.DcuiTimeOut -Entity $ESXIP | Set-AdvancedSetting -Value ${DcuiTimeOut} -confirm:$false | out-null
#15. set-password-policies
REM("set-password-policies")
Get-AdvancedSetting -Name Security.PasswordQualityControl -Entity $ESXIP | Set-AdvancedSetting -Value ${PasswordQualityControl} -confirm:$false | out-null
#16. set-shell-interactive-timeout
REM("set-shell-interactive-timeout")
Get-AdvancedSetting -Name UserVars.ESXiShellInteractiveTimeOut -Entity $ESXIP | Set-AdvancedSetting -Value ${ESXiShellInteractiveTimeOut} -confirm:$false | out-null
#17. set-shell-timeout
REM("set-shell-timeout")
Get-AdvancedSetting -Name UserVars.ESXiShellTimeOut -Entity $ESXIP | Set-AdvancedSetting -Value ${ESXiShellTimeOut} -confirm:$false | out-null
#18. verify-acceptance-level-accepted (cannot set to VMwareAccepted due to HPE VIB)
#$esxcli.software.acceptance.set(${AcceptanceLevel})
###
###
#vNetwork Hardening
#1. reject-forged-transmit & reject-mac-changes & reject-promiscuous-mode
REM("reject-forged-transmit & reject-mac-changes & reject-promiscuous-mode")
Get-VirtualSwitch -Name $Switch0 | Get-SecurityPolicy | Set-SecurityPolicy -AllowPromiscuous $false -MacChanges $false -ForgedTransmits $false | out-null
#2. limit-network-healthcheck (VDS setting, to be configured via vCenter )
#3. enable-bpdu-filter
REM("enable-bpdu-filter")
Get-AdvancedSetting -Name Net.BlockGuestBPDU -Entity $ESXIP | Set-AdvancedSetting -Value 1 -confirm:$false | out-null
###
}
Write-Host
REM("Finished all the configurations.")
if ($scratchConfigured -ne $null){
REM("Reboot the host to make the new scratch location effective.")
Restart-VMHost -confirm:$false
}
Disconnect-viserver -confirm:$false -ErrorAction Stop -WarningAction silentlyContinue | out-null
Install procedure
- Install ESXi 6.0 U3 (clean install)
- Set IP, VLAN , Gateway, hostname from iLO
- Run postinstall powercli script
ESX-install.ps1
- Add ESXi host to vCenter & cluster
- Check Esxi host Configuration against host profile
转载于:https://blog.51cto.com/549687/2116435