Получение данных из Icinga2 с помощью API и powershell
08 Sep 2017
local_offer
Icinga2
local_offer
powershell
Пример запроса с помощью Curl:
curl -k -s -u 'root:icinga' -H 'X-HTTP-Method-Override: GET' -X POST 'https://192.168.0.209:5665/v1/objects/hosts?filter=match(%22*.mkucou.local%22,host.name)'
curl -k -s -u 'root:icinga' -H 'X-HTTP-Method-Override: GET' -X POST 'https://192.168.0.209:5665/v1/objects/services?service=l016.pshome.local!av-product'
Данные о хостах
Функция выборки данных о хостах с помощью powershell:
```powershell
function Get-HostFromIcinga {
param(
[Parameter(Mandatory=$True)]
[string] $hostname
)
#Доверяем всем сертификатам
add-type -TypeDefinition @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
# Начиная с версии v2.11 используется только TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$user = "root"
$pass= "icinga"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$apiurl = 'https://192.168.0.209:5665/v1/objects/hosts?filter=match("' + $hostname + '",host.name)'
#Write-Host $apiurl
$headers = @{}
$headers["Accept"] = "application/json"
$headers["X-HTTP-Method-Override"] = "GET"
$apireq = Invoke-WebRequest -Credential $credential -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Post -UseBasicParsing
$result = $apireq.Content | ConvertFrom-Json
return $result
} #Конец функции Get-HostFromIcinga
```
#Здесь в имени хоста могут быть подстановочные знаки, напрмер "*.mkucou.local"
$result = Get-FromIcinga -hostname "bd2.mkucou.local"
Функия возвращает:
PS C:\scripts> $result.results
attrs : @{__name=bd2.mkucou.local; acknowledgement=0,0; acknowledgement_expiry=0,0; active=True; address=192.168.223.201; address6=; check_attempt=1,0; check_command=cluster-zone; check_interval=300,0; check_period=; check_timeout=; command_endpoint=; display_name=bd2.mkucou.local; downtime_depth=0,0; enable_active_checks=True; enable_event_handler=True; enable_flapping=False; enable_notifications=True; enable_passive_checks=True; enable_perfdata=False; event_command=; flapping=False;flapping_last_change=1504865525,3512890339; flapping_negative=1497,0; flapping_positive=0,0; flapping_threshold=30,0; force_next_check=False; force_next_notification=False; groups=System.Object[]; ha_mode=0,0; icon_image=/icingaweb2/plsatin/img/server_16.png; icon_image_alt=; last_check=1504865525,3512609005; last_check_result=; last_hard_state=0,0; last_hard_state_change=1504104167,9991459846; last_reachable=True; last_state=0,0; last_state_change=1504104167,9991459846; last_state_down=1504103882,1487970352; last_state_type=1,0; last_state_unreachable=0,0; last_state_up=1504865525,3512759209; max_check_attempts=3,0; name=bd2.mkucou.local; next_check=1504865825,3500001431; notes=; notes_url=; original_attributes=; package=_etc; paused=False; retry_interval=30,0; severity=8,0; source_location=; state=0,0; state_type=1,0; templates=System.Object[]; type=Host; vars=; version=1503457435,3594050407; volatile=False; zone=icinga}
joins :
meta :
name : bd2.mkucou.local
type : Host
----------------------------------------------------------------
Перебираем массив атрибутов (attrs) и получаем сведения о хостах:
$arr0 = $result.results.attrs
foreach ($arr in $arr0) {
Write-Host $arr.address
Write-Host $arr.name
Write-Host $arr.vars.os
}
Переменные хоста (host.vars):
PS C:\scripts> $arr.vars
@{bios_serial=8680-8639-2399-4112-2080-7766-06; board_manufacturer=Microsoft Corporation; board_product=Virtual Machine; client_endpoint=bd2.mkucou.local; cluster_zone=bd2.mkucou.local; cpu=Intel(R) Xeon(R) CPU E5-2609 v4 @ 1.70GHz; domain_name=MKUCOU; manufacturer=Microsoft Corporation; model=Virtual Machine; notification=;offhours_downtime=17:00-24:00,00:00-08:00; os=Microsoft Windows Server 2012 Standard SP 0; os_arch=64-N??°?·N?N??????°N?; os_family=Windows; os_type=Windows Server; physical_machine=False; puppet_agent=True; ram=9,23GB; support_ticket=True; veeam_backup_agent=True}
Данные о сервисах
Функция выборки данных о сервисах хоста с помощью powershell:
```powershell
function Get-ServiceFromIcinga {
param(
[Parameter(Mandatory=$True)]
[string] $hostname,
[Parameter(Mandatory=$True)]
[string] $servicename
)
#Доверяем всем сертификатам
add-type -TypeDefinition @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$user = "root"
$pass= "icinga"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$apiurl = 'https://192.168.0.209:5665/v1/objects/services?service=' + $hostname + '!' + $servicename
#Write-Host $apiurl
$headers = @{}
$headers["Accept"] = "application/json"
$headers["X-HTTP-Method-Override"] = "GET"
$apireq = Invoke-WebRequest -Credential $credential -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Post -UseBasicParsing
$result = $apireq.Content | ConvertFrom-Json
return $result
} #Конец функции Get-ServiceFromIcinga
```