# Este script chequea el estado de un entorno de VMWARE en los siguientes puntos: # # PROCEDIMIENTO PARA LA MODIFICACIÓN DEL SCRIPT # Editamos el fichero powershell.ps1 y se editan las siguientes variables: # $vcserver="localhost" # Se introducirá el nombre del Virtual Center al que nos conectaremos. # Si el script se ejecuta desde un VC se # tipeará "localhost" # $portvc="443" # Se edita el puerto. Por defecto es el 443 # $filelocation="c:\healthcheck.htm" # Se especifica en $filelocation la ruta donde se desea guardar el report # $enablemail="yes" # Habilitado (yes) o deshabilitado (no) para enviar el report por mail # $smtpServer = "mail.samuelgarciacalventehealthcheck.org" # Se especificará el servidor smtp desde el cual se hará el envío del Report # $mailfrom = "Health Check del Virtual Center XX <powershellAVA@healthcheck.ava>" # Se especifica la cuenta desde donde se envía y el “Display Name que queremos mostrar” # $mailto = "users@healtcheck.ava" # Se especifica la cuenta de recepción# # ########################################################################################### # ########################################################################################### # Procedimiento de Configuración del Script # # Editamos el fichero powershell.ps1 y se editan las siguientes variables: # $vcserver="localhost" # Se introducirá el nombre del Virtual Center al que nos conectaremos. Si el script se ejecuta desde un VC se tiepará "localhost" # $portvc="443" # Se edita el puerto. Por defecto es el 443 # $filelocation="c:\healthcheck.htm" # Se especifica en $filelocation la ruta donde se desa guardar el report # $enablemail="yes" # Habilitado (yes) o deshabilitado (no) para enviar el report por mail # $smtpServer = "mail.healthcheck.org" # Se especificará el servidor smtp desde el cual se hará el envío del Report # $mailfrom = "Health Check del Virtual Center XX <powershellAVA@healthcheck.ava>" # Se especifica la cuetna desde donde se envía. # $mailto = "users@healtcheck.ava" # Se especifica la cuenta de recepción# # ########################################################################################### # Utilización: # # Ejecutar manualmente el script en .ps1 # # 1. Abrir Powershell con el snapin de Powercli # 2. Navegar hasta el directorio donde resida el script .ps1 # 3. Ejecutar el comando: # ./script.ps1 # # ########################################################################################### ############################################### # Nombre de servidor de VMware VirtualCenter # ############################################### $vcserver="VIRTUALSERVERNAME Ó HOSTNAME" $portvc="443" ################################ # Añadir Snapin de VI-toolkit # ################################ Add-PSsnapin VMware.VimAutomation.Core # SGC. Eliminado puesto que Powercli será un requisito y no se desea su comprobación. Desrenombrar en caso de que se desee comprobar el estado del snapin## # Se arranca VI Toolkit y se realiza conexión contra el virtual center desde el puerto definido Initialize-VIToolkitEnvironment.ps1 connect-VIServer $vcserver -port $portvc ############# # Variables # ############# #$date=get-date -format g $date=get-date -displayhint date #SGC modificado la toma de datos de fecha para Castellano.Si se desea en americano eliminar "-displayhint date" $filelocation="C:\scripts\healthcheck_VIRTUALSERVER.HTM" $vcversion = get-view serviceinstance $snap = get-vm | get-snapshot $ErrorActionPreference = "SilentlyContinue" ####################### # Variables de Correo # ####################### $enablemail="yes" $smtpServer = "mail.healthcheck.org" $mailfrom = "Estado de Salud del Entorno VMWARE de …<administracion@healthcheck.org>" $mailto = "users@healtcheck.ava"
####################################### # Conversión a HTML y hoja de estilos # ####################################### #ConvertTo-Html –title "VMware Health Check " –body "<H1>VMware Health script</H1>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File $filelocation ConvertTo-Html –title "VMware Health Check " –body "<style>body { background-color:#F9F9F9; } body,table,td,th { font-family:Calibri; color:Black; Font-Size:12pt } th { font-weight:bold; background-color:#81BEF7; } td { background-color:white; } </style><H1>VMware Health Script (Hosts de UBICACIÓN X)</H1>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File $filelocation ConvertTo-Html –title "VMware Health Check " –body "<H4>Fecha y hora</H4>",$date -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation # código de colores: http://html-color-codes.info/codigos-de-colores-hexadecimales/ #body { background-color: #F2F2F2; } gris de fondo #body,table,td,th { font-family:Calibri; color:Black; Font-Size:10pt } tipo de letra negro #th { font-weight:bold; background-color:#CCCCCC; } gris más oscuro de las tablas #td { background-color:white; } color de fondo de las tablas ############################ # Hardware de VMware ESX # ############################ Get-VMHost | Get-View | ForEach-Object { $_.Summary.Hardware } | Select-object Vendor, Model, MemorySize, CpuModel, CpuMhz, NumCpuPkgs, NumCpuCores, NumCpuThreads, NumNics, NumHBAs | ConvertTo-Html –title "Configuración Hardware de los servidores ESX" –body "<H2>Configuración Hardware de los servidores ESX.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ########################################## # Versión de Virtual Center de VMware # ########################################## $vcversion.content.about | select Version, Build, FullName | ConvertTo-Html –title "Versión VMware de vCenter" –body "<H2>Versión VMware de vCenter.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" |Out-File -Append $filelocation ################################### # Información de Cluster VMware # ################################### $clusters = Get-Cluster | Sort Name ForEach ($cluster in $clusters) { $vmhosts = Get-VMHost -Location $cluster ForEach ($VMhostView in ($vmhosts | Get-View)) { $TotalHostMemory += $vmhostView.Hardware.MemorySize } #$vmhosts | Sort Name -Descending | % { $server = $_ |get-view; $server.Config.Product | select { $server.name }, Version, Build, FullName }| ConvertTo-Html –body "<H2>$cluster Información del Clúster .</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation # $vmhosts | Sort Name -Descending | % { $server = $_ |get-view; $server.Config.Product | select { $server.name }, Version, Build, FullName }| ConvertTo-Html –body "<H2>$cluster Información del Clúster .</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation #$vmhosts | Sort name -Descending | % { $server = $_ |get-view; $server.Config.Product | select { $server.name }, Version, Build, FullName }| ConvertTo-Html –body "<H2>$cluster Cluster Information.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation $vmhosts | Sort Name -Descending | % { $server = $_ |get-view; $server.Config.Product | select {$server.Name}, Version, Build, FullName }| ConvertTo-Html –body "<H2>$cluster Cluster Information.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation $NumHosts = ($vmhosts | Measure-Object).Count $vms = Get-VM -Location $cluster | Where {$_.PowerState -eq "Powered On"} $NumVMs = $vms.Length $TotalRAM_GB = [math]::Round($TotalHostMemory/1GB,$digits) $TotalVMMemoryMB = $vms | Measure-Object -Property MemoryMB -Sum $AssignedRAM_GB = [math]::Round($TotalVMMemoryMB.Sum/1024,$digits) $PercentageUsed = [math]::Round((($TotalVMMemoryMB.Sum/1024)/($TotalHostMemory/1GB))*100) ConvertTo-Html –body " $NumHosts host(s) ejecutando $NumVMs Máquinas Virtuales" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ConvertTo-Html –body "Total de Recursos de Memoria = $TotalRAM_GB GB" | Out-File -Append $filelocation ConvertTo-Html –body "Cantidad Total de Memoria Asignada = $AssignedRAM_GB GB" | Out-File -Append $filelocation ConvertTo-Html –body "Porcentaje de Recursos de Memoria Asignada = $PercentageUsed %" | Out-File -Append $filelocation Clear-Variable vmhosts -ErrorAction SilentlyContinue Clear-Variable vms -ErrorAction SilentlyContinue Clear-Variable NumVMs -ErrorAction SilentlyContinue Clear-Variable TotalHostMemory -ErrorAction SilentlyContinue Clear-Variable TotalVMMemoryMB -ErrorAction SilentlyContinue } ####################### # Estadísticas # ####################### ConvertTo-Html –title "Estadísticas VMware" –body "<H2>Estadísticas VMware</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -append $filelocation Get-VMHost | Measure-Object | Select Count | ConvertTo-Html –title "Número de Hosts VMware" –body "<H4>Número de Hosts VMware.</H4>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation Get-VM | Measure-Object | Select Count | ConvertTo-Html –title "Número Total de Máquinas Virtuales" –body "<H4>Número Total de Máquinas Virtuales.</H4>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation Get-Cluster | Measure-Object | Select Count | ConvertTo-Html –title "Número de Clusters VMware" –body "<H4>Número de Clusters VMware.</H4>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation Get-Datastore | Measure-Object | Select Count | ConvertTo-Html –title "Número de Datastores" –body "<H4>Número de Datastores.</H4>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ############# # Snapshots # ############# $snap | select vm, name,created,description | ConvertTo-Html –title "Snaphots Activos" –body "<H2>Snaphots Activos.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />"| Out-File -Append $filelocation ################################# # VMware CDROM conectado a VM´s # ################################# Get-vm | where { $_ | get-cddrive | where { $_.ConnectionState.Connected -eq "true" } } | Select Name | ConvertTo-Html –title "CDROMs conectados" –body "<H2>CDROMs conectados.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />"|Out-File -Append $filelocation ######################################### # VMware floppy conectado a VM´s # ######################################### Get-vm | where { $_ | get-floppydrive | where { $_.ConnectionState.Connected -eq "true" } } | select Name |ConvertTo-Html –title "Floppy drives conectados" –body "<H2>Floppy drives conectados.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" |Out-File -Append $filelocation ############################## # Información del Datastore # ############################## function UsedSpace { param($ds) [math]::Round(($ds.CapacityMB - $ds.FreeSpaceMB)/1024,2) } function FreeSpace { param($ds) [math]::Round($ds.FreeSpaceMB/1024,2) } function PercFree { param($ds) [math]::Round((100 * $ds.FreeSpaceMB / $ds.CapacityMB),0) } $Datastores = Get-Datastore $myCol = @() ForEach ($Datastore in $Datastores) { $myObj = "" | Select-Object Datastore, UsedGB, FreeGB, PercFree $myObj.Datastore = $Datastore.Name $myObj.UsedGB = UsedSpace $Datastore $myObj.FreeGB = FreeSpace $Datastore $myObj.PercFree = PercFree $Datastore $myCol += $myObj } $myCol | Sort-Object PercFree | ConvertTo-Html –title "Espacio Disponible del DataStore" –body "<H2>Espacio Disponible del DataStore</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation # Invoke-Item $filelocation ############################################################################# # Obtiene los datos de todos los DataStores y se colocan en Orden Alfabético# ############################################################################# function Get-DSDevice($dsImpl) { $ds = Get-View -Id $dsImpl.Id $esx = Get-View $ds.Host[0].Key $hss = Get-View $esx.ConfigManager.StorageSystem foreach($mount in $hss.FileSystemVolumeInfo.MountInfo){ if($mount.volume.name -eq $ds.Info.Name){ switch($mount.Volume.Type){ "VMFS" { foreach($ext in $mount.Volume.Extent){ if($mount.volume.name -eq $ds.Info.Name){ $device =$ext.DiskName } } } "NFS" { $device = $mount.Volume.RemoteHost + ":" + $mount.Volume.RemotePath } } } } $device } $datastores = get-vmhost | Get-Datastore | Sort-Object Name $myColCurrent = @() foreach ($store in $datastores){ $myObj = "" | Select-Object Name, CapacityGB, UsedGB, PercFree, Type, ID, Accessible $myObj.Name = $store.Name $myObj.CapacityGB = "{0:n2}" -f ($store.capacityMB/1kb) $myObj.UsedGB = "{0:N2}" -f (($store.CapacityMB - $store.FreeSpaceMB)/1kb) $myObj.PercFree = "{0:N}" -f (100 * $store.FreeSpaceMB/$store.CapacityMB) $myObj.Type = $store.Type $temp = Get-View -Id $store.Id $myObj.ID = Get-DSDevice $store $myObj.Accessible = $store.Accessible $myColCurrent += $myObj } # Exporta al HTML $myColCurrent | ConvertTo-Html –title "Información del Datastore" –body "<H2>Información del Datastore.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ############################ # Información de RDM # ############################ $report = @() $vms = Get-VM | Get-View foreach($vm in $vms){ foreach($dev in $vm.Config.Hardware.Device){ if(($dev.gettype()).Name -eq "VirtualDisk"){ if(($dev.Backing.CompatibilityMode -eq "physicalMode") -or ($dev.Backing.CompatibilityMode -eq "virtualMode")){ $row = "" | select VMName, HDDeviceName, HDFileName, HDMode, HDsize $row.VMName = $vm.Name $row.HDDeviceName = $dev.Backing.DeviceName $row.HDFileName = $dev.Backing.FileName $row.HDMode = $dev.Backing.CompatibilityMode $row.HDSize = $dev.CapacityInKB $report += $row } } } } $report | ConvertTo-Html –title "Información de RDM" –body "<H2>Información de RDM.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ##################################### # Estadísticas de todas las VM # ##################################### $Report = @() get-vm | Sort Name -Descending | % { $vm = Get-View $_.ID $vms = "" | Select-Object VMName, Hostname, IPAddress, VMState, TotalCPU, TotalMemory, TotalNics, OverallCpuUsage, MemoryUsage, ToolsStatus, ToolsVersion, MemoryLimit, MemoryReservation, CPUreservation, CPUlimit , "HW Version" $vms.VMName = $vm.Name $vms.Hostname = $vm.guest.hostname $vms.IPAddress = $vm.guest.ipAddress $vms.VMState = $vm.summary.runtime.powerState $vms.TotalCPU = $vm.summary.config.numcpu $vms.TotalMemory = $vm.summary.config.memorysizemb $vms.TotalNics = $vm.summary.config.numEthernetCards $vms.OverallCpuUsage = $vm.summary.quickStats.OverallCpuUsage $vms.MemoryUsage = $vm.summary.quickStats.guestMemoryUsage $vms.ToolsStatus = $vm.guest.toolsstatus $vms.ToolsVersion = $vm.config.tools.toolsversion $vms.MemoryLimit = $vm.resourceconfig.memoryallocation.limit $vms.MemoryReservation = $vm.resourceconfig.memoryallocation.reservation $vms.CPUreservation = $vm.resourceconfig.cpuallocation.reservation $vms.CPUlimit = $vm.resourceconfig.cpuallocation.limit $vms."HW Version"= $vm.Config.Version $Report += $vms } $Report | ConvertTo-Html –title "Estadisticas de todas las Máquinas Virtuales VMware " –body "<H2>Estadisticas de todas las Máquinas Virtuales VMware.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ###################################################### # Información del Data Store utilizado por cada VM # ###################################################### $report = @() $virtualmachines = Get-VM foreach ($vm in $virtualmachines) { $dstores = $vm | Get-Datastore foreach($ds in $dstores){ $row = "" | select VMname, datastore $row.VMname = $vm.name $row.datastore = $ds.Name $report += $row } }$report | ConvertTo-Html –title "Máquinas Virtuales y ubicación concreta en DataStore" –body "<H2>Máquinas Virtuales y ubicación concreta en DataStore.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ############################################################# # Máquinas Virtuales que no sincronizan su hora con los ESX # ############################################################# Get-VM | Get-View | ? { $_.Config.Tools.syncTimeWithHost -eq $false } | Select Name | Sort-object Name | ConvertTo-Html –title "Máquinas Virtuales que no sincronizan su hora con los ESX" –body "<H2>Máquinas Virtuales que no sincronizan su hora con los ESX.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ############################################################## # Porcentaje de espacio libre en las particiones de las VM # ############################################################## Get-VM | Where { $_.PowerState -eq "PoweredOn" } | Get-VMGuest | Select VmName -ExpandProperty Disks | Select VmName, Path, @{ N="PercFree"; E={ [math]::Round( ( 100 * ( $_.FreeSpace / $_.Capacity ) ),0 ) } } | Sort PercFree | ConvertTo-Html –title "Porcentaje de espacio libre en las particiones de las VM" –body "<H2> Porcentaje de espacio libre en las particiones de las VM.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ################################################ # Errores encontrados en las ultimas 24 horas # ################################################ #Get-VIEvent -Start (Get-Date).AddHours(-24) -Type Error | Select-object CreatedTime, FullFormattedMessage | ConvertTo-Html –title "Errores encontrados las últimas 24 horas" –body "<H2>Errores encontrados las últimas 24 horas.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ################################################ # Errores encontrados en los ultimos 7 días # ################################################ #Get-VIEvent -Start (Get-Date).AddHours(-168) -Type Error | Format-Table CreatedTime, FullFormattedMessage -AutoSize | ConvertTo-Html –title "Errores encontrados en los últimos 5 días" –body "<H2>Errores encontrados en los últimos 5 días.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation Get-VIEvent -Start (Get-Date).AddHours(-168) -Type Error | Select-object CreatedTime, FullFormattedMessage | ConvertTo-Html –title "Errores encontrados los últimos 7 días" –body "<H2>Errores encontrados los últimos 7 días.</H2>" -head "<link rel='stylesheet' href='style.css' type='text/css' />" | Out-File -Append $filelocation ############################################# # Salida del fichero HTML Y envío por mail # ############################################# if ($enablemail -match "yes") { $msg = new-object Net.Mail.MailMessage $att = new-object Net.Mail.Attachment($filelocation) $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = $mailfrom $msg.To.Add($mailto) $msg.Subject = “Health Check del Entorno VMware de …” $msg.Body = “Informe Semanal creado por el Departamento de ..para….” $msg.Attachments.Add($att) $smtp.Send($msg) } ##################################################### # Desconexión de la sesión contra el Virtual Center # ##################################################### disconnect-viserver -confirm:$false ################################################################################ # Cerrar el proceso de powershell en todos los hilso de ejecución del servidor # ################################################################################ # EN MI CASO LOS HILOS DE POWERSHELL AL LANZARLO DESDE UNA TAREA PROGRAMADA DEJABA POWERSHELL.EXE EN # #EJECUCIÓN TRAS TERMINAR EL SCRIPT. POR LO TANTO EN EL SCRIPT QUE SE EJECUTABA EL ULTIMO, OBLIGABA QUE EL #PROCESO POWERSHELL.EXE DEL SERVIDOR FUERA ELIMINADO DE RAIZ. DESRENOMBRAR EN CASO DE QUE SE DESEE MATAR #DICHO PROCESO. #stop-process -Name Powershell # ########################## # Final de Script # ########################## |
No hay comentarios:
Publicar un comentario