Advertising:

Zabbix Sender en Powershell: Difference between revisions

From Zabbix-ES
Jump to navigation Jump to search
No edit summary
No edit summary
Line 12: Line 12:
  '''File:''' scom2zabbix.ps1
  '''File:''' scom2zabbix.ps1


  function ZabbixTrapper {
  <#PSScriptInfo
    param (
.VERSION 1.2
        [string]$Value
.GUID 18bf0803-2626-46f5-b0d0-54e694985078
    )
.AUTHOR saw-friendship
.COMPANYNAME
.COPYRIGHT saw-friendship
.TAGS Zabbix Sender OverTCP Json Send Trap
.LICENSEURI
.PROJECTURI https://sawfriendship.wordpress.com/
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
#>
<#
.DESCRIPTION
  Send-ZabbixTrap send data to zabbix server over TCP without zabbix_sender.exe
    
    
    [string]$Server = '[[ZABBIX SERVER]]'
.LINK
    [int]$Port = '10051'
  https://sawfriendship.wordpress.com/
    [string]$HostName = 'SCOM01'
    [string]$Key = 'scom.traps'
    [string[]]$Header = @('host','key','value')
    [string]$JsonString
    [switch]$OnlyPreview = $false
    
    
    if ( [bool]($HostName -or $Key -or $Value) ) {
.EXAMPLE
            if(! [bool]($HostName -and $Key -and $Value) ) {
  Send-ZabbixTrap -z 172.16.5.2 -p 10051 -s Srv1 -k trap -o OK
                Write-Error 'HostName, Key and Value must not be null';
 
                break
  You can use parameter aliases as in zabbix_sender.exe
            } else {
  z = zabbix server
                $Json = [pscustomobject][ordered]@{
  p = port
                    'request' = 'sender data' ;
  s = host
                    'data' = @([pscustomobject][ordered]@{'host' = $HostName;'key' = $Key;'value' = $Value})
  k = key
                } | ConvertTo-Json -Compress
  o = value
    
    
        }
.EXAMPLE
    } elseif ($InputObject) {
  Send-ZabbixTrap -z 172.16.5.2 -p 10051 -s Srv1 -k trap -o OK -OnlyPreview
        $Json = [pscustomobject][ordered]@{
                    'request' = 'sender data' ;
                    'data' = @(
                        $InputObject | Select-Object -Property @(
                            @{'Name' = 'host'; Expression = {$_.$($Header[0])}},
                            @{'Name' = 'key'; Expression = {$_.$($Header[1])}},
                            @{'Name' = 'value'; Expression = {$_.$($Header[2])}}
                        )
                    )
                } | ConvertTo-Json -Compress
    } elseif ($JsonString) {
        $Json = $JsonString | ConvertFrom-Json | ConvertTo-Json -Compress
    } else {
        Write-Error 'Input data not found';
        break
    }
    
    
    if(!$Json){
  Only generating Json string for preview
        Write-Error 'Can not convert InputData to Json string';
 
        break
.EXAMPLE
    }
  Send-ZabbixTrap -Server 172.16.5.2 -Port 10051 -JsonString $json
 
  Json format example:
 
  [pscustomobject][ordered]@{
    'request' = 'sender data';
    'data' = @(
        1..3 | % {
            [pscustomobject][ordered]@{
                'host' = 'HOST'
                'key' = 'KEY'
                'value' = 'VALUE'
            }
        }
    )
} | ConvertTo-Json
    
    
    if($OnlyPreview){
        $Json | ConvertFrom-Json | ConvertTo-Json;
        break
    }
    
    
    try {
.EXAMPLE
        [byte[]]$Header = @([System.Text.Encoding]::ASCII.GetBytes('ZBXD')) + [byte]1
  Send-ZabbixTrap -Server 172.16.5.2 -Port 10051 -InputObject (Import-Csv -Encoding utf8 -Delimiter ';' -Path $home\srv.csv) -Header ComputerName,Service,Status
        [byte[]]$Length = @([System.BitConverter]::GetBytes($([long]$Json.Length)))
        [byte[]]$Data = @([System.Text.Encoding]::ASCII.GetBytes($Json))
       
        $All = $Header + $Length + $Data
       
    } catch {
        Write-Error 'Can not convert Json string to byte';
        break
    }
    
    
    try {
  The PropertyNames of the input objects must be "host, key, value" or be specified in the header parameter
        $Socket = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
        $Socket.Connect($Server,$Port)
        $Socket.Send($All) | Out-Null
        [byte[]]$Buffer = New-Object System.Byte[] 1000
        [int]$ReceivedLength = $Socket.Receive($Buffer)
        $Socket.Close()
    } catch {
        Write-Error 'TCP-level Error connecting, sending or receiving';
        break
    }
    
    
    $Received = [System.Text.Encoding]::ASCII.GetString(@($Buffer[13 .. ($ReceivedLength - 1)]))
#>
 
    try{
        $Received | ConvertFrom-Json
    } catch {
[CmdletBinding(DefaultParameterSetName="Set0")]
        Write-Warning 'It is not possible to convert the output to a Json string, maybe the server has rejected invalid data'
param(
        $Received
    [alias("z")]
    }
    [string]$Server = '172.16.5.2',
   
    [alias("p")]
    [ValidateRange(1,65535)]
    [int]$Port = '10051',
   
    [parameter(ParameterSetName="Set1")]
    [alias("s")]
    [string]$HostName,
   
    [parameter(ParameterSetName="Set1")]
    [alias("k")]
    [string]$Key,
   
    [parameter(ParameterSetName="Set1")]
    [alias("o")]
    [string]$Value,
   
    [parameter(ParameterSetName="Set2")]$InputObject,
   
    [parameter(ParameterSetName="Set2",HelpMessage='Enter 3 string values for mapping object property to json headers. Default "host","key","value"')]
    [ValidateCount(3,3)]
    [string[]]$Header = @('host','key','value'),
   
    [parameter(ParameterSetName="Set3")]
    [string]$JsonString,
   
    [parameter(HelpMessage='On generating Json-string for preview')]
    [switch]$OnlyPreview
)
if ( [bool]($HostName -or $Key -or $Value) ) {
        if(! [bool]($HostName -and $Key -and $Value) ) {
            Write-Error 'HostName, Key and Value must not be null';
            break
        } else {
            $Json = [pscustomobject][ordered]@{
                'request' = 'sender data' ;
                'data' = @([pscustomobject][ordered]@{'host' = $HostName;'key' = $Key;'value' = $Value})
            } | ConvertTo-Json -Compress
    }
} elseif ($InputObject) {
    $Json = [pscustomobject][ordered]@{
                'request' = 'sender data' ;
                'data' = @(
                    $InputObject | Select-Object -Property @(
                        @{'Name' = 'host'; Expression = {$_.$($Header[0])}},
                        @{'Name' = 'key'; Expression = {$_.$($Header[1])}},
                        @{'Name' = 'value'; Expression = {$_.$($Header[2])}}
                    )
                )
            } | ConvertTo-Json -Compress
} elseif ($JsonString) {
    $Json = $JsonString | ConvertFrom-Json | ConvertTo-Json -Compress
} else {
    Write-Error 'Input data not found';
    break
}
if(!$Json){
    Write-Error 'Can not convert InputData to Json string';
    break
}
if($OnlyPreview){
    $Json | ConvertFrom-Json | ConvertTo-Json;
    break
}
try {
    [byte[]]$Header = @([System.Text.Encoding]::ASCII.GetBytes('ZBXD')) + [byte]1
    [byte[]]$Length = @([System.BitConverter]::GetBytes($([long]$Json.Length)))
    [byte[]]$Data = @([System.Text.Encoding]::ASCII.GetBytes($Json))
   
    $All = $Header + $Length + $Data
   
} catch {
    Write-Error 'Can not convert Json string to byte';
    break
  }
  }
 
   
  Import-Module OperationsManager
$AlertsJson = New-Object System.Collections.Generic.List[System.Object]
[string]$Severity_raw = ''
[string]$Priority_raw = ''
  try {
  try {
    # $alerts = Get-SCOMAlert -Severity 2 | Select-Object Id, Name, Severity, Priority, MonitoringObjectPath, Description, TimeRaised, ResolutionState | ? {$_.ResolutionState -ne 255} | Sort-Object TimeRaised -Descending
    $Socket = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
    $alerts = Get-SCOMAlert | Select-Object Id, Name, Severity, Priority, MonitoringObjectPath, Description, TimeRaised, ResolutionState | ? {$_.ResolutionState -ne 255 -and ($_.Severity -eq 1 -or $_.Severity -eq 2)} | Sort-Object TimeRaised -Descending
    $Socket.Connect($Server,$Port)
    if (-Not ($alerts -eq $null)){
    $Socket.Send($All) | Out-Null
        foreach ($alert in $alerts) {
    [byte[]]$Buffer = New-Object System.Byte[] 1000
            if ($alert.Severity -eq 0)    { $Severity_raw = 'Informational'; }
     [int]$ReceivedLength = $Socket.Receive($Buffer)
            elseif ($alert.Severity -eq 1) { $Severity_raw = 'Warning';      }
    $Socket.Close()
            elseif ($alert.Severity -eq 2) { $Severity_raw = 'Critical';     }
} catch {
       
    Write-Error 'TCP-level Error connecting, sending or receiving';
            if ($alert.Priority -eq 0)    { $Priority_raw = 'Low';    }
    break
            elseif ($alert.Priority -eq 1) { $Priority_raw = 'Medium'; }
}
            elseif ($alert.Priority -eq 2) { $Priority_raw = 'High';  }
 
$Received = [System.Text.Encoding]::ASCII.GetString(@($Buffer[13 .. ($ReceivedLength - 1)]))
            if ($alert.ResolutionState -eq 0)      { $ResolutionState_raw = 'Nueva Alerta';    }
            elseif ($alert.ResolutionState -eq 255) { $ResolutionState_raw = 'Cerrada'; }
try{
            elseif ($alert.ResolutionState -eq 249) { $ResolutionState_raw = 'ACK - Se esta trabajando en ella';  }
    $Received | ConvertFrom-Json
            elseif ($alert.ResolutionState -eq 248) { $ResolutionState_raw = 'ACK - Asignado a ingeniería';  }
            elseif ($alert.ResolutionState -eq 247) { $ResolutionState_raw = 'ACK - En espera de evidencia';   }                                 
            elseif ($alert.ResolutionState -eq 254) { $ResolutionState_raw = 'ACK - Resuelto';  }
            elseif ($alert.ResolutionState -eq 250) { $ResolutionState_raw = 'ACK - Programado';  }
           
            $AlertsJson.Add(@{"id"=$alert.Id;"device"=$alert.MonitoringObjectPath;"name"=$alert.Name;"severity"=$alert.Severity;"severity_raw"=$Severity_raw;"priority"=$alert.Priority;"priority_raw"=$Priority_raw;"description"=$alert.Description;"resolutionstate"=$alert.ResolutionState;"resolutionstate_raw"=$ResolutionState_raw;});
        }
    }
    ZabbixTrapper(ConvertTo-Json -InputObject $AlertsJson -Compress);
  } catch {
  } catch {
    Write-Error 'Error al enviar los datos';
    Write-Warning 'It is not possible to convert the output to a Json string, maybe the server has rejected invalid data'
    break
    $Received
  }
  }

Revision as of 08:17, 24 September 2021

File: scom2zabbix.cmd
@ECHO OFF 
set LOGFILE=C:\zabbix\scom2zabbix.log

call :sub >%LOGFILE%
exit /b

:sub
"C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe" -File C:\zabbix\bin\scom2zabbix.ps1
File: scom2zabbix.ps1
<#PSScriptInfo
.VERSION 1.2
.GUID 18bf0803-2626-46f5-b0d0-54e694985078
.AUTHOR saw-friendship
.COMPANYNAME
.COPYRIGHT saw-friendship
.TAGS Zabbix Sender OverTCP Json Send Trap
.LICENSEURI
.PROJECTURI https://sawfriendship.wordpress.com/
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
#>

<#
.DESCRIPTION
 Send-ZabbixTrap send data to zabbix server over TCP without zabbix_sender.exe
 
.LINK
 https://sawfriendship.wordpress.com/
 
.EXAMPLE
 Send-ZabbixTrap -z 172.16.5.2 -p 10051 -s Srv1 -k trap -o OK
  
 You can use parameter aliases as in zabbix_sender.exe
 z = zabbix server
 p = port
 s = host
 k = key
 o = value
 
.EXAMPLE
 Send-ZabbixTrap -z 172.16.5.2 -p 10051 -s Srv1 -k trap -o OK -OnlyPreview
 
 Only generating Json string for preview
  
.EXAMPLE
 Send-ZabbixTrap -Server 172.16.5.2 -Port 10051 -JsonString $json
  
 Json format example:
  
 [pscustomobject][ordered]@{
    'request' = 'sender data';
    'data' = @(
        1..3 | % {
            [pscustomobject][ordered]@{
                'host' = 'HOST'
                'key' = 'KEY'
                'value' = 'VALUE'
            }
        }
    )
} | ConvertTo-Json
 
 
.EXAMPLE
 Send-ZabbixTrap -Server 172.16.5.2 -Port 10051 -InputObject (Import-Csv -Encoding utf8 -Delimiter ';' -Path $home\srv.csv) -Header ComputerName,Service,Status
 
 The PropertyNames of the input objects must be "host, key, value" or be specified in the header parameter
 
#> 



[CmdletBinding(DefaultParameterSetName="Set0")]
param(
    [alias("z")]
    [string]$Server = '172.16.5.2',
    
    [alias("p")]
    [ValidateRange(1,65535)]
    [int]$Port = '10051',
    
    [parameter(ParameterSetName="Set1")]
    [alias("s")]
    [string]$HostName,
    
    [parameter(ParameterSetName="Set1")]
    [alias("k")]
    [string]$Key,
    
    [parameter(ParameterSetName="Set1")]
    [alias("o")]
    [string]$Value,
    
    [parameter(ParameterSetName="Set2")]$InputObject,
    
    [parameter(ParameterSetName="Set2",HelpMessage='Enter 3 string values for mapping object property to json headers. Default "host","key","value"')]
    [ValidateCount(3,3)]
    [string[]]$Header = @('host','key','value'),
    
    [parameter(ParameterSetName="Set3")]
    [string]$JsonString,
    
    [parameter(HelpMessage='On generating Json-string for preview')]
    [switch]$OnlyPreview
)

if ( [bool]($HostName -or $Key -or $Value) ) {
        if(! [bool]($HostName -and $Key -and $Value) ) {
            Write-Error 'HostName, Key and Value must not be null';
            break
        } else {
            $Json = [pscustomobject][ordered]@{
                'request' = 'sender data' ;
                'data' = @([pscustomobject][ordered]@{'host' = $HostName;'key' = $Key;'value' = $Value})
            } | ConvertTo-Json -Compress

    }
} elseif ($InputObject) {
    $Json = [pscustomobject][ordered]@{
                'request' = 'sender data' ;
                'data' = @(
                    $InputObject | Select-Object -Property @(
                        @{'Name' = 'host'; Expression = {$_.$($Header[0])}},
                        @{'Name' = 'key'; Expression = {$_.$($Header[1])}},
                        @{'Name' = 'value'; Expression = {$_.$($Header[2])}}
                    )
                )
            } | ConvertTo-Json -Compress
} elseif ($JsonString) {
    $Json = $JsonString | ConvertFrom-Json | ConvertTo-Json -Compress
} else {
    Write-Error 'Input data not found';
    break
}

if(!$Json){
    Write-Error 'Can not convert InputData to Json string';
    break
}

if($OnlyPreview){
    $Json | ConvertFrom-Json | ConvertTo-Json;
    break
}

try {
    [byte[]]$Header = @([System.Text.Encoding]::ASCII.GetBytes('ZBXD')) + [byte]1
    [byte[]]$Length = @([System.BitConverter]::GetBytes($([long]$Json.Length)))
    [byte[]]$Data = @([System.Text.Encoding]::ASCII.GetBytes($Json))
    
    $All = $Header + $Length + $Data
    
} catch {
    Write-Error 'Can not convert Json string to byte';
    break
}

try {
    $Socket = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
    $Socket.Connect($Server,$Port)
    $Socket.Send($All) | Out-Null
    [byte[]]$Buffer = New-Object System.Byte[] 1000
    [int]$ReceivedLength = $Socket.Receive($Buffer)
    $Socket.Close()
} catch {
    Write-Error 'TCP-level Error connecting, sending or receiving';
    break
}

$Received = [System.Text.Encoding]::ASCII.GetString(@($Buffer[13 .. ($ReceivedLength - 1)]))

try{
    $Received | ConvertFrom-Json
} catch {
    Write-Warning 'It is not possible to convert the output to a Json string, maybe the server has rejected invalid data'
    $Received
}