Перейти к основному содержанию

iLO — настройка Active Directory аутентификации через PowerShell

PowerShell

Чем больше серверов у системного администратора, тем сложнее ими управлять вручную. Сегодня автоматизируем настройку Active Directory аутентификации в iLO 4 и iLO 5 с помощью PowerShell скриптов.

Для управления iLO с помощью PowerShell скриптов компания Hewlett Packard выпускает и поддерживает набор командлетов под названием Scripting Tools for Windows PowerShell: iLO cmdlets.

Текущая версия пакета 4.3.0.0 от 16 ноября 2023 года может быть использована для конфигурации управления iLO на серверах HPE ProLiant Gen8, Gen9, Gen10, Gen10 Plus, Gen11. iLO cmdlets поддерживает iLO 4, iLO 5 и iLO 6 ProLiant серверы. Для работы командлеты используют RIBCL, REST(Limited) и Redfish интерфейсы iLO. Для работы скриптов понадобится .NET Framework 4.5 - 4.7.1.

Но не стоит думать, что стоит написать скрипт для iLO 5 и он тут же заработает для iLO 4. Я уже убедился, что лучше сделать два разных скрипта для iLO 4 и iLO 5. Однако, сегодня будет именно такой скрипт, чтобы работал и для iLO 4 и для iLO 5.

Устанавливаем .NET и HPEiLOCmdlets. Работаю в ОС Windows 10.

Управление iLO через PowerShell

Примеры PowerShell скриптов можно найти в папке по умолчанию C:\HPEiLOCmdlets\Samples.

ilo

Примеры можно брать как основу для творчества, но в них тоже есть ошибки. Скрипты подписаны цифровой подписью, в процессе отладки вам она не понадобится. У меня в итоге получилось три файла:

  • iLOInput.csv
  • GetAD.ps1
  • SetAD.ps1

ilo

В iLOInput.csv указывается список серверов в виде:

IP,Username,Password
192.168.1.2,admin,password
192.168.1.3,admin,password

Здесь нужно указать IP адрес или DNS имя iLO, логин, пароль.

GetAD.ps1 — выводит текущие настройки AD аутентификации.

  • ####################################################################
    #iLO Active Directory Information
    ####################################################################
    
    <#
    .Synopsis
        This Script gets the AD settings for NTLM auth.
        iLO 4 and iLO 5 supported.
    
    .DESCRIPTION
        This Script gets the Active Directory settings for NTLM auth authentication.
    	
    	The cmdlets used from HPEiLOCmdlets module in the script are as stated below:
    	Enable-HPEiLOLog, Connect-HPEiLO, Disconnect-HPEiLO, Disable-HPEiLOLog, 
    	Get-HPEiLODirectorySettins, Get-HPEiLODirectoryGroup.
    
    .PARAMETER Key
        Specifies the security dashboard settings to be updated in iLO.
    
    .EXAMPLE
        
        PS C:\HPEiLOCmdlets\Prod\> .\GetAD.ps1 
    	
        This script display AD info from iLO.
     
    .INPUTS
    	iLOInput.csv file in the script folder location having iLO IPv4 address, iLO Username and iLO Password.
    
    .OUTPUTS
        None (by default)
    
    .NOTES
    	Always run the PowerShell in administrator mode to execute the script.
    	
        Company : Internet-lab.ru
        Version : 1.0.0.0
        Date    : 2023-01-18 
    
    .LINK
        http://internet-lab.ru
    #>
    
    #Command line parameters
    Param(
        [switch]$IgnoreSecureBoot,
        [switch]$IgnoreSecurityOverrideSwitch,
        [switch]$IgnorePasswordComplexity,
        [switch]$IgnoreIPMIDCMIOverLAN,
        [switch]$IgnoreMinimumPasswordLength,
        [switch]$IgnoreRequireLoginforiLORBSU,
        [switch]$IgnoreAuthenticationFailureLogging,
        [switch]$IgnoreLastFirmwareScanResult,
        [switch]$IgnoreRequireHostAuthentication
    )
    
    try
    {
        $path = Split-Path -Parent $PSCommandPath
        $path = join-Path $path "\iLOInput.csv"
        $inputcsv = Import-Csv $path
    	if($inputcsv.IP.count -eq $inputcsv.Username.count -eq $inputcsv.Password.count -eq 0)
    	{
    		Write-Host "Provide values for IP, Username and Password columns in the iLOInput.csv file and try again."
            exit
    	}
    
        $notNullIP = $inputcsv.IP | Where-Object {-Not [string]::IsNullOrWhiteSpace($_)}
        $notNullUsername = $inputcsv.Username | Where-Object {-Not [string]::IsNullOrWhiteSpace($_)}
        $notNullPassword = $inputcsv.Password | Where-Object {-Not [string]::IsNullOrWhiteSpace($_)}
    	if(-Not($notNullIP.Count -eq $notNullUsername.Count -eq $notNullPassword.Count))
    	{
            Write-Host "Provide equal number of values for IP, Username and Password columns in the iLOInput.csv file and try again."
            exit
    	}
    }
    catch
    {
        Write-Host "iLOInput.csv file import failed. Please check the file path of the iLOInput.csv file and try again."
        Write-Host "iLOInput.csv file path: $path"
        exit
    }
    
    #Clear-Host
    
    # script execution started
    Write-Host "****** Script execution started ******`n" -ForegroundColor Yellow
    #Decribe what script does to the user
    
    Write-Host "This script sets the security dashboard settings to the given value and gets the same.`n"
    
    #Load HPEiLOCmdlets module
    $InstalledModule = Get-Module
    $ModuleNames = $InstalledModule.Name
    
    if(-not($ModuleNames -like "HPEiLOCmdlets"))
    {
        Write-Host "Loading module :  HPEiLOCmdlets"
        Import-Module HPEiLOCmdlets
        if(($(Get-Module -Name "HPEiLOCmdlets")  -eq $null))
        {
            Write-Host ""
            Write-Host "HPEiLOCmdlets module cannot be loaded. Please fix the problem and try again"
            Write-Host ""
            Write-Host "Exit..."
            exit
        }
    }
    else
    {
        $InstallediLOModule  =  Get-Module -Name "HPEiLOCmdlets"
        Write-Host "HPEiLOCmdlets Module Version : $($InstallediLOModule.Version) is installed on your machine."
        Write-host ""
    }
    
    $Error.Clear()
    
    #Enable logging feature
    Write-Host "Enabling logging feature" -ForegroundColor Yellow
    $log = Enable-HPEiLOLog
    $log | fl
    
    if($Error.Count -ne 0)
    { 
    	Write-Host "`nPlease launch the PowerShell in administrator mode and run the script again." -ForegroundColor Yellow 
    	Write-Host "`n****** Script execution terminated ******" -ForegroundColor Red 
    	exit 
    }	
    
    try
    {
    	$ErrorActionPreference = "SilentlyContinue"
    	$WarningPreference ="SilentlyContinue"
    	
        [bool]$isParameterCountEQOne = $false;
    
        foreach ($Key in $MyInvocation.BoundParameters.keys)
        {
            $count = $($MyInvocation.BoundParameters[$Key]).Count        
    
        }
        Write-Host "`nConnecting using Connect-HPEiLO`n" -ForegroundColor Yellow
    
        $connection = @(Connect-HPEiLO -IP $inputcsv.IP -Username $inputcsv.Username -Password $inputcsv.Password -DisableCertificateAuthentication)
    	
    	$Error.Clear()
    	
        if($Connection -eq $null)
        {
            Write-Host "`nConnection could not be established to any target iLO.`n" -ForegroundColor Red
            $inputcsv.IP | fl
            exit;
        }
    
        if($Connection.count -ne $inputcsv.IP.count)
        {
            #List of IP's that could not be connected
            Write-Host "`nConnection failed for below set of targets" -ForegroundColor Red
            foreach($item in $inputcsv.IP)
            {
                if($Connection.IP -notcontains $item)
                {
                    $item | fl
                }
            }
    
            #Prompt for user input
            $mismatchinput = Read-Host -Prompt 'Connection object count and parameter value count does not match. Do you want to continue? Enter Y to continue with script execution. Enter N to cancel.'
            if($mismatchinput -ne 'Y')
            {
                Write-Host "`n****** Script execution stopped ******" -ForegroundColor Yellow
                exit;
            }
        }
    
        foreach($connect in $connection)
        {
            #Displaying Directory Settings
            Write-Host "`nGetting HPE iLO Directory Settins for $($connect.IP)" -ForegroundColor Green
            $output = Get-HPEiLODirectorySetting -Connection $connect
            
            if($output.Status -ne "OK")
            {   
                $message = $output.StatusInfo.Message; 
                Write-Host "`nFailed to get Get-HPEiLODirectorySetting for $($output.IP): "$message -ForegroundColor Red
            }
            else
            {  
                $output[0]
            }  
    
            Write-Host "`nGetting HPE iLO Directory Group for $($connect.IP)" -ForegroundColor Green
            $output = Get-HPEiLODirectoryGroup -Connection $connect
           
            #Displaying Directory Group
            if($output.Status -ne "OK")
            {   
                $message = $output.StatusInfo.Message; 
                Write-Host "`nFailed to get Get-HPEiLODirectoryGroup for $($output.IP): "$message -ForegroundColor Red
            }
            else
            {  
                $output.GroupAccountInfo 
            } 
            
        }
     }
     catch
     {
     }
    finally
    {
        if($connection -ne $null)
        {
            #Disconnect 
    		Write-Host "Disconnect using Disconnect-HPEiLO `n" -ForegroundColor Yellow
    		$disconnect = Disconnect-HPEiLO -Connection $Connection
    		$disconnect | fl
    		Write-Host "All connections disconnected successfully.`n"
        }  
    	
    	#Disable logging feature
    	Write-Host "Disabling logging feature`n" -ForegroundColor Yellow
    	$log = Disable-HPEiLOLog
    	$log | fl
    	
    	if($Error.Count -ne 0 )
        {
            Write-Host "`nScript executed with few errors. Check the log files for more information.`n" -ForegroundColor Red
        }
    	
        Write-Host "`n****** Script execution completed ******" -ForegroundColor Yellow
    }

SetAD.ps1 — изменяет настройки AD аутентификации. Я в скрипте устанавливал только те параметры, которые мне были нужны, вам нужно внести изменения в конфигурационную часть:

<#
####################################################################
#CONFIGURATION
####################################################################
#>

$ConfLDAPDirectoryAuthentication = "DirectoryDefaultSchema"
$ConfGenericLDAPEnabled = "Yes"
$ConfDirectoryServerAddress = "ldap.domain.local"
$ConfDirectoryServerPort = "636"
$ConfUserContextIndex = ,@(1,2)
$ConfUserContextValue = ,@("@domain.local","DC=domain,DC=local")

$ConfGroupName = "smena"
$ConfGroupSID = "S-1-5-21-2606053222-2546427529-1258059324-16321"
$ConfLoginPrivilege = "Yes"
$ConfRemoteConsolePrivilege = "Yes"
$ConfVirtualPowerAndResetPrivilege = "Yes"
$ConfVirtualMediaPrivilege = "Yes"
$ConfHostBIOSConfigPrivilege = "No"
$ConfiLOConfigPrivilege = "No"
$ConfUserConfigPrivilege = "No"
$ConfHostNICConfigPrivilege = "No"
$ConfHostStorageConfigPrivilege = "No"
$ConfSystemRecoveryConfigPrivilege = "No"

<#
####################################################################
#END CONFIGURATION
####################################################################
#>

DirectoryAuthentication может принимать значения:

  • Disabled
  • ExtendedSchema
  • DirectoryDefaultSchema

Долго не мог добиться одновременной работы iLO 4 и iLO 5 пока не обнаружил во встроенной документации этот чудесный текст:

Because of iLO5 issue, if you modify port number (change the default number 636) then Start-HPEiLODirectorySettingTest will fail as iLO updates the Directory server address with port number as in it.(like IP:PORT format). The workaround is if you want to modify port number of directory server LDAP then first input the required port number for set cmdlet then in second call try without port number just with directory server settings.

  • ####################################################################
    #iLO Configure Active Directory Information 
    ####################################################################
    
    <#
    .Synopsis
        This Script sets the AD settings for NTLM auth.
        iLO 4 and iLO 5 supported.
    
    .DESCRIPTION
        This Script sets the Active Directory settings for NTLM auth authentication.
    	
    	The cmdlets used from HPEiLOCmdlets module in the script are as stated below:
    	Enable-HPEiLOLog, Connect-HPEiLO, Disconnect-HPEiLO, Disable-HPEiLOLog, 
    	Set-HPEiLODirectorySettins, Add-HPEiLODirectoryGroup, Set-HPEiLODirectoryGroup.
    
    .PARAMETER Key
        Specifies the security dashboard settings to be updated in iLO.
    
    .EXAMPLE
        
        PS C:\HPEiLOCmdlets\Prod\> .\SetAD.ps1 
    	
        This script display AD info from iLO.
     
    .INPUTS
    	iLOInput.csv file in the script folder location having iLO IPv4 address, iLO Username and iLO Password.
    
    .OUTPUTS
        None (by default)
    
    .NOTES
    	Always run the PowerShell in administrator mode to execute the script.
    
        Company : Internet-lab.ru
        Version : 1.0.0.0
        Date    : 2023-01-18 
    
    .LINK
        http://internet-lab.ru
    #>
    
    #Command line parameters
    Param(
        [switch]$IgnoreSecureBoot,
        [switch]$IgnoreSecurityOverrideSwitch,
        [switch]$IgnorePasswordComplexity,
        [switch]$IgnoreIPMIDCMIOverLAN,
        [switch]$IgnoreMinimumPasswordLength,
        [switch]$IgnoreRequireLoginforiLORBSU,
        [switch]$IgnoreAuthenticationFailureLogging,
        [switch]$IgnoreLastFirmwareScanResult,
        [switch]$IgnoreRequireHostAuthentication
    )
    
    <#
    ####################################################################
    #CONFIGURATION
    ####################################################################
    #>
    
    $ConfLDAPDirectoryAuthentication = "DirectoryDefaultSchema"
    $ConfGenericLDAPEnabled = "Yes"
    $ConfDirectoryServerAddress = "ldap.domain.local"
    $ConfDirectoryServerPort = "636"
    $ConfUserContextIndex = ,@(1,2)
    $ConfUserContextValue = ,@("@domain.local","DC=domain,DC=local")
    
    $ConfGroupName = "smena"
    $ConfGroupSID = "S-1-5-21-2606053222-2546427529-1258059324-16321"
    $ConfLoginPrivilege = "Yes"
    $ConfRemoteConsolePrivilege = "Yes"
    $ConfVirtualPowerAndResetPrivilege = "Yes"
    $ConfVirtualMediaPrivilege = "Yes"
    $ConfHostBIOSConfigPrivilege = "No"
    $ConfiLOConfigPrivilege = "No"
    $ConfUserConfigPrivilege = "No"
    $ConfHostNICConfigPrivilege = "No"
    $ConfHostStorageConfigPrivilege = "No"
    $ConfSystemRecoveryConfigPrivilege = "No"
    
    <#
    ####################################################################
    #END CONFIGURATION
    ####################################################################
    #>
    
    try
    {
        $path = Split-Path -Parent $PSCommandPath
        $path = join-Path $path "\iLOInput.csv"
        $inputcsv = Import-Csv $path
    	if($inputcsv.IP.count -eq $inputcsv.Username.count -eq $inputcsv.Password.count -eq 0)
    	{
    		Write-Host "Provide values for IP, Username and Password columns in the iLOInput.csv file and try again."
            exit
    	}
    
        $notNullIP = $inputcsv.IP | Where-Object {-Not [string]::IsNullOrWhiteSpace($_)}
        $notNullUsername = $inputcsv.Username | Where-Object {-Not [string]::IsNullOrWhiteSpace($_)}
        $notNullPassword = $inputcsv.Password | Where-Object {-Not [string]::IsNullOrWhiteSpace($_)}
    	if(-Not($notNullIP.Count -eq $notNullUsername.Count -eq $notNullPassword.Count))
    	{
            Write-Host "Provide equal number of values for IP, Username and Password columns in the iLOInput.csv file and try again."
            exit
    	}
    }
    catch
    {
        Write-Host "iLOInput.csv file import failed. Please check the file path of the iLOInput.csv file and try again."
        Write-Host "iLOInput.csv file path: $path"
        exit
    }
    
    Clear-Host
    
    # script execution started
    Write-Host "****** Script execution started ******`n" -ForegroundColor Yellow
    #Decribe what script does to the user
    
    Write-Host "This script sets the security dashboard settings to the given value and gets the same.`n"
    
    #Load HPEiLOCmdlets module
    $InstalledModule = Get-Module
    $ModuleNames = $InstalledModule.Name
    
    if(-not($ModuleNames -like "HPEiLOCmdlets"))
    {
        Write-Host "Loading module :  HPEiLOCmdlets"
        Import-Module HPEiLOCmdlets
        if(($(Get-Module -Name "HPEiLOCmdlets")  -eq $null))
        {
            Write-Host ""
            Write-Host "HPEiLOCmdlets module cannot be loaded. Please fix the problem and try again"
            Write-Host ""
            Write-Host "Exit..."
            exit
        }
    }
    else
    {
        $InstallediLOModule  =  Get-Module -Name "HPEiLOCmdlets"
        Write-Host "HPEiLOCmdlets Module Version : $($InstallediLOModule.Version) is installed on your machine."
        Write-host ""
    }
    
    $Error.Clear()
    
    #Enable logging feature
    Write-Host "Enabling logging feature" -ForegroundColor Yellow
    $log = Enable-HPEiLOLog
    $log | fl
    
    if($Error.Count -ne 0)
    { 
    	Write-Host "`nPlease launch the PowerShell in administrator mode and run the script again." -ForegroundColor Yellow 
    	Write-Host "`n****** Script execution terminated ******" -ForegroundColor Red 
    	exit 
    }	
    
    try
    {
    	$ErrorActionPreference = "SilentlyContinue"
    	$WarningPreference ="SilentlyContinue"
    	
        [bool]$isParameterCountEQOne = $false;
    
        foreach ($Key in $MyInvocation.BoundParameters.keys)
        {
            $count = $($MyInvocation.BoundParameters[$Key]).Count        
    
        }
        Write-Host "`nConnecting using Connect-HPEiLO`n" -ForegroundColor Yellow
    
        $connection = @(Connect-HPEiLO -IP $inputcsv.IP -Username $inputcsv.Username -Password $inputcsv.Password -DisableCertificateAuthentication)
    	
    	$Error.Clear()
    
        if($Connection -eq $null)
        {
            Write-Host "`nConnection could not be established to any target iLO.`n" -ForegroundColor Red
            $inputcsv.IP | fl
            exit;
        }
    
        if($Connection.count -ne $inputcsv.IP.count)
        {
            #List of IP's that could not be connected
            Write-Host "`nConnection failed for below set of targets - $($Connection.count)" -ForegroundColor Red
            foreach($item in $inputcsv.IP)
            {
                if($Connection.IP -notcontains $item)
                {
                    $item | fl
                }
            }
    
            #Prompt for user input
            $mismatchinput = Read-Host -Prompt 'Connection object count and parameter value count does not match. Do you want to continue? Enter Y to continue with script execution. Enter N to cancel.'
            if($mismatchinput -ne 'Y')
            {
                Write-Host "`n****** Script execution stopped ******" -ForegroundColor Yellow
                exit;
            }
        }
    
        foreach($connect in $connection)
        {
            #Set Directory Settings
            Write-Host "`nSetting HPE iLO Directory Settings for $($connect.IP)" -ForegroundColor Green
    
            #Clear Context
            $ClearUserContextIndex = ,@(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
            $ClearUserContextValue = ,@("","","","","","","","","","","","","","","")
            $output = Set-HPEiLODirectorySetting -Connection $connect `
                -UserContextIndex $ClearUserContextIndex `
                -UserContext $ClearUserContextValue
            $Error.Clear()
            #$output.StatusInfo
    
            #Set Settings with new context
            $output = Set-HPEiLODirectorySetting -Connection $connect `
                -DirectoryServerAddress $ConfDirectoryServerAddress `
                -DirectoryServerPort $ConfDirectoryServerPort
            $Error.Clear()
            #$output.StatusInfo
    
            #Because of iLO5 issue, if you modify port number (change the default number 636) then Start-HPEiLODirectorySettingTest
            #will fail as iLO updates the Directory server address with port number as in it.(like IP:PORT format).
            #The workaround is if you want to modify port number of directory server LDAP
            #then first input the required port number for set cmdlet 
            #then in second call try without port number just with directory server settings.
            $output = Set-HPEiLODirectorySetting -Connection $connect `
                -LDAPDirectoryAuthentication $ConfLDAPDirectoryAuthentication `
                -GenericLDAPEnabled $ConfGenericLDAPEnabled `
                -DirectoryServerAddress $ConfDirectoryServerAddress `
                -UserContextIndex $ConfUserContextIndex `
                -UserContext $ConfUserContextValue
            $Error.Clear()
            #$output.StatusInfo
    
            Write-Host "`nDirectory Settings OK" -ForegroundColor Cyan
            
            #Add  Directory Group
            Write-Host "`nAdding HPE iLO Directory Group for $($connect.IP)" -ForegroundColor Green
    
            #Add Empty Directory Group if not exist
            $output = Add-HPEiLODirectoryGroup -Connection $connect `
                -GroupName $ConfGroupName `
                -GroupSID $ConfGroupSID
            $Error.Clear()
            #$output.StatusInfo
    
            #Set role for iLO4 and iLO5
            $output = Set-HPEiLODirectoryGroup -Connection $connect `
                -GroupName $ConfGroupName `
                -GroupSID $ConfGroupSID `
                -LoginPrivilege $ConfLoginPrivilege `
                -RemoteConsolePrivilege $ConfRemoteConsolePrivilege `
                -VirtualMediaPrivilege $ConfVirtualMediaPrivilege `
                -VirtualPowerAndResetPrivilege $ConfVirtualPowerAndResetPrivilege `
                -iLOConfigPrivilege $ConfiLOConfigPrivilege `
                -UserConfigPrivilege $ConfUserConfigPrivilege
            $Error.Clear()
            #$output.StatusInfo
    
            #Set additional role for iLO5
            $output = Set-HPEiLODirectoryGroup -Connection $connect `
                -GroupName $ConfGroupName `
                -HostBIOSConfigPrivilege $ConfHostBIOSConfigPrivilege `
                -HostNICConfigPrivilege $ConfHostNICConfigPrivilege `
                -HostStorageConfigPrivilege $ConfHostStorageConfigPrivilege `
                -SystemRecoveryConfigPrivilege $ConfSystemRecoveryConfigPrivilege
            $Error.Clear()
            #$output.StatusInfo
    
            Write-Host "`nDirectory Group OK" -ForegroundColor Cyan
    
        }
     }
     catch
     {
     }
    finally
    {
        if($connection -ne $null)
        {
            #Disconnect 
    		Write-Host "Disconnect using Disconnect-HPEiLO `n" -ForegroundColor Yellow
    		$disconnect = Disconnect-HPEiLO -Connection $Connection
    		$disconnect | fl
    		Write-Host "All connections disconnected successfully.`n"
        }  
    	
    	#Disable logging feature
    	Write-Host "Disabling logging feature`n" -ForegroundColor Yellow
    	$log = Disable-HPEiLOLog
    	$log | fl
    	
    	if($Error.Count -ne 0 )
        {
            Write-Host "`nScript executed with few errors. Check the log files for more information.`n" -ForegroundColor Red
        }
    	
        Write-Host "`n****** Script execution completed ******" -ForegroundColor Yellow
    }

ilo

Ссылки

Разрешить запуск скриптов PowerShell

Управление iLO через PowerShell

Скрипты в виде архива добавил в Сборку для системного администратора.

Цены

 

Похожие материалы

Установка HP Proliant DL20 Gen9 в стойку глубиной 60 см с помощью болгарки

Габариты сервера HP Proliant DL20 Gen9 позволяют ему разместиться в стойке глубиной 60 см. Но вот незадача, — рельсы не входят! Будем впихивать с помощью болгарки.

Теги

День, когда я менял диски... местами

Сегодня по плану я еду в ЦОД менять диски местами. Два NVMe диска в одном сервере поменяются местами с двумя дисками другого сервера, тип, брэнд и объёмы дисков одинаковые. Вы спросите зачем? Вот и я думал, что не придётся, а пришлось. Поехали.

Теги