Tag Archives: Windows

Zabbix Error “an array is expected” with Powershell

When trying to interact with the Zabbix-API via Powershell one might run into the problem, that an API request will not be executed successfully, but an error similar to the following one, will be displayed:

  code message         data                                                           
  ---- -------         ----                                                           
-32602 Invalid params. Invalid parameter "/1/filter/conditions": an array is expected.

Especially when using some code like in the below snippet which uses @(…) and @{…} to define data via arrays and hashtables:

function ZbxUpdateTestAction
{

    $params = @{
        body =  @{
            "jsonrpc"= "2.0"
            "method"= "action.update"
            "params"= @{
                "actionid" = "117"
                "status" = 0
                "filter" = @{
                    "evaltype" = 0
                    "conditions" = @(
                        @{
                            "conditiontype" = 4
                            "operator" = 5
                            "value"= 3
                        }
                        @{
                            "conditiontype" = 0
                            "operator" = 0
                            "value"= 435
                        }
                    )
                }
            }
            "id"= 1
            "auth" = "$api_token"
        } | ConvertTo-Json
        uri = $zbx_api_uri
        headers = @{
            "Content-Type" = "application/json"
            "Authorization" = "Bearer $api_token"
            }
        method = "Post"
    }
    $result = Invoke-WebRequest @params
    return $result.Content | ConvertFrom-Json
}

The above snippet just shows a test function to manually update an action and set conditions to send out alerts for severities of warning or higher for a specific host group.

However – when executed it will fail with the error from snippet 1.

This is because Powershell does the JSON-conversion only to a certain depth. If your structure reaches a deeper level, it will simply stop converting the dict or array which results in the above error.

Troubleshooting it, could be quite a pain in the ass as it’s not that simple to spot and when gradually extending the object it just works fine till you exceed a depth of 2.

To fix this – simple specify the depth for ConvertTo-Json

e.g.

function ZbxUpdateTestAction
{

    $params = @{
        body =  @{
            "jsonrpc"= "2.0"
            "method"= "action.update"
            "params"= @{
                "actionid" = "117"
                "status" = 0
                "filter" = @{
                    "evaltype" = 0
                    "conditions" = @(
                        @{
                            "conditiontype" = 4
                            "operator" = 5
                            "value"= 3
                        }
                        @{
                            "conditiontype" = 0
                            "operator" = 0
                            "value"= 435
                        }
                    )
                }
            }
            "id"= 1
            "auth" = "$api_token"
        } | ConvertTo-Json -Depth 5
        uri = $zbx_api_uri
        headers = @{
            "Content-Type" = "application/json"
            "Authorization" = "Bearer $api_token"
            }
        method = "Post"
    }
    $result = Invoke-WebRequest @params
    return $result.Content | ConvertFrom-Json
}

Compare line 29 between the two snippets

Refs:

Running into “The parameter is incorrect.” / “HRESULT 0x80070057” when managing scheduled tasks via powershell

It took me quite some troubleshooting time, but in the end it’s a quite interessting conclusion.

After trying to create a scheduled task that runs every second Saturday per month, I ran into the following error:

Set-ScheduledTask : The parameter is incorrect.
At C:\ITX\itxWindowsUpdate.ps1:436 char:5
+     Set-ScheduledTask -InputObject $task -User $(Get-LocalUser -Name  ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Set-ScheduledTask], CimException
    + FullyQualifiedErrorId : HRESULT 0x80070057,Set-ScheduledTask

As Windows Powershell is not able to create monthly tasks I used schtasks.exe utility to create the skeleton for the task/minimal task containing the trigger-definition and afterwards manipulate it via powershell to add the missing configuration.

To do so i used Get-ScheduledTask to obtaint he object references for the task and Set-ScheduledTask to write the object again.

Turns out – the task obtained via Get-ScheduledTask contains the trigger defintion for the montly repetition which can’t be handled by powershell and therefor the task itself can not be saved again but results in the above error. 😜

As it seems there are only two ways on how to deal with that problem:
Export the task-definition as an XML and just reimport it via powershell on other systems which require the same configuration (currently untested) or run it daily and deal with the problem within the script.

Lil bit of the debugging-code as a reference for future projects.

Write-Host -ForegroundColor Yellow "Modifying the task"
$action=New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument '-NoProfile -command "& C:\BLUB\WindowsUpdate\WindowsUpdate.ps1 -reboot_machine 0"'
$principal = New-ScheduledTaskPrincipal -LogonType Password -RunLevel Highest -UserId "$($env:COMPUTERNAME)\Administrator"
#$principal = New-ScheduledTaskPrincipal -RunLevel Highest -UserId "$($env:COMPUTERNAME)\Administrator"

#$task=New-ScheduledTask -Action $action -Description "Daily Update Task for Monitoring and Defender Updates" -Trigger $trigger -Settings $settings -Principal $

$task=$(Get-ScheduledTask -TaskName $task_name -TaskPath \BLUB\)
#$task.Actions=$action
$task.Description="TEST_test"
#$task.Principal=$principal
#Register-ScheduledTask -TaskName $task_name -InputObject $task -TaskPath BLUB -User $(Get-LocalUser -Name Administrator) -Password $password
$task | Set-ScheduledTask -User $(Get-LocalUser -Name Administrator) -Password $password
#-User $(Get-LocalUser -Name Administrator) -Password $password 
#Set-ScheduledTask -TaskPath "BLUB" -TaskName $task_name -Action $action -Principal $principal
#-Principal $principal
# -User $(Get-LocalUser -Name Administrator) 

PowerShell AD Snippet

Simple snippet to get a list when the passwort of a service user was set the last time.

Get-ADUser -Filter 'Name -like "svc*"' -Properties * | select Name,@{name ="pwdLastSet"; expression={[datetime]::FromFileTime($_.pwdLastSet)}}

Requires the Active Directory Powershell module to run.

Command must also be run in an elevated powershell session (Run as Administrator)

Otherwise the pwdLastSet attribute will not be obtained!

Sid To Username

Param
(
    [parameter(
        Mandatory=$true,
        HelpMessage="User SID"
        )
    ]
    [String]
    [alias("sid")]
    $user_sid
)
$objSID = New-Object System.Security.Principal.SecurityIdentifier $user_sid 
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount]) 
$objUser.Value

Windwos telephone activiation – shortcut

When using the telephone activiation select the option that MS sends you a link to an activation page. http://md.vivr.io/XxX0c0C Use the link and the following commands on the computer to extracte the activaition ID from the system, paste it on the webinterface and copy the confirmation ID back to the system. To paste the activiation ID on the Microsoft Website use the cscript command to print the ID to the command prompt, copy it to Keepass in the autotype field and use the autotype option to paste the blocks. To strip the response NPP + the follwoing regex can be used: [A-Z]|\t|\n -> Strips all upper case characters, tabstops and CRs

 

Tools Needed:

  • KeePass (or any other autotype tool)
  • Notepad++
    NPP-Regex for search and replace: [A-Z]|\t|\n

 

Commands:

#Install Productkey
slmgr /ipk <ProductKey>

#Display activation ID
cscript C:\Windows\System32\slmgr.vbs /dti

From <https://social.technet.microsoft.com/Forums/windows/de-DE/3ead2d77-00fc-4c06-b4c0-82eae0ebc2bc/save-slmgr-dli-output-to-text-file?forum=w7itproinstall>

#install confirmation ID from Microsoft
slmgr /atp <Confirmation ID>

#Check Status
slmgr /dlv

OR
slmgr /dli

From <http://www.thewindowsclub.com/view-licensing-status-activation-id-windows-slmg

Flashing NextThing C.H.I.P. with a Raspberry Pi

Today I somehow bricked my CHIP (I think it wasn’t the wised idea to set the system-target to network_online) as I didn’t get access via serial connection or ssh.
It wasn’t that much of a problem as I wanted to set up the CHIP as a headless system.
So the journey begins (http://docs.getchip.com/chip.html#installing-c-h-i-p-sdk) with setting up Virtual Box + Extension pack and installing vagrant on my Windows 10 (Git was already installed).

After everything was installed I started the VM wich was setup by vagrant and ran the chip-update-firmware.sh script to start the upgrade, but it failed with “Waiting for fel……………………………TIMEOUT”.
The reason was, that regardless of the USB-rules in the Vagrantfile, the CHIP was not available in the VM. Easy to check with “lsusb”. No Big deal – As the VM is available in the VirtualBox Manager we can boot it up from there and just attach the CHIP-USB-Device to the VM.

waiting for fel…OK -> 🙂
BUT:
waiting for fastboot……………………………TIMEOUT
-> 🙁

So, it seems that after the reboot of the CHIP windows is not recognizing it the right way and also has some problems to pass it through to the VM.

I dind’t find a fix for that problem, but reportedly a physical Ubuntu installation should would (regarding to some forum post on the NextThing BBS). Too bad I only have Fedora on a laptop, but no Ubuntu – but I had a Raspberry which i was currently not using, so I gave it a try and it worked out quite nice.

I used a “Jessy lite” and installed the following packages:

[pastacode lang=”bash” manual=”sudo%20apt-get%20install%20android-tools-fastboot%C2%A0u-boot-tools%20u-boot%20cbootimage%C2%A0uuid-dev%20libacl1-dev%20liblzo2-dev%C2%A0libusb-1.0-0-dev%20libusb%2B%2B-dev%20libusb-1.0-0%20libusb-dev%20git%0Agit%20clone%20https%3A%2F%2Fgithub.com%2FNextThingCo%2FCHIP-SDK%0Acd%C2%A0CHIP-SDK%0Asudo%20.%2Fsetup_ubuntu1404.sh%0Acd%C2%A0CHIP-Tools%0Asudo%20.%2Fchip-legacy-update.sh%20-f%20-s” message=”Install packages and flash the CHIP” highlight=”” provider=”manual”/]
(I don’t think that all the packages are needed, but i got some errors and hence installed everything I thought fix those errors)
After that & a reboot of my CHIP i was able to access it again with:

screen /dev/ttyACM0 115200

 

Powershell/PowerCLI very slow execution Time

Sometimes a PowerCLI-script can take quite some time till everything is executed. For example the PowerShell scripts used by Zabbix to gather the vCenter alarms into Zabbix (BlogPost) need some tuning to run fine.

So why are scripts running slow in some cases?
It seems to occur primary on systems which do not have a connection to the internet. As a matter of fact – most of the systems I’m setting up “lose” internet connection sooner, or later. :/

What exactly causes the problem?
While investigating that problem i found an interesting feature which seems to cause the problem – certificate checks!
There is an IE-setting which is named “Check for publisher’s certificate revocation ” and can be found at: Intenet Options -> Advanced -> Section: Security ->Disable: Check for publisher’s certificate revocation.

Disabling the certificate checks improves the execution time by about 60%.

certificate-check enabled:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 41
Milliseconds      : 536
Ticks             : 415369143
TotalDays         : 0.000480751322916667
TotalHours        : 0.01153803175
TotalMinutes      : 0.692281905
TotalSeconds      : 41.5369143
TotalMilliseconds : 41536.9143

 

certificate-check disabled:

Days : 0
Hours : 0
Minutes : 0
Seconds : 16
Milliseconds : 262
Ticks : 162628208
TotalDays : 0.000188227092592593
TotalHours : 0.00451745022222222
TotalMinutes : 0.271047013333333
TotalSeconds : 16.2628208
TotalMilliseconds : 16262.8208

 

If the script is run from a normal user account everything should be fine and we have an improved execution time, BUT …

… if the script is run from an Service (and as a matter of fact I’m using the Zabbix agent service to run the script) we got a problem.
With default settings the Zabbix Agent is installed to run as nt authority\system, so if the IE-setting is changed for the current user, its working for this user, but not for the system user. 🙁
So a quick and dirty workaround could be to disable the setting for the system user.
ATTENTION: Running the Zabbix Agent as a system user is OK for a DEV-environment, but should not be used in an production environment. For production a dedicated service user should be used.

I disabled it by becoming a system user with

[pastacode lang=”bash” message=”” highlight=”” provider=”manual”]

PSEXEC -i -s -d CMD

[/pastacode]

and launching the IE from the command prompt. Afterwards I was able to disable the setting via the above method.

Otherwise the Key could also be found in the registry at:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\WinTrust\Trust Providers\Software Publishing\State
0x00023e00 / 146944 Check OFF
0x00023c00 / 146432 Check ON

A simple PS-Script to disable the setting would be:

[pastacode lang=”bash” message=”PowerShell to disable Publisher certificate checks” highlight=”” provider=”manual”]

Write-Host "Disable Check for publisher’s certificate Revocation"
set-ItemProperty -path "REGISTRY::\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\WinTrust\Trust Providers\Software Publishing\" -name State -value 146944

[/pastacode]

 

UNIX/DOS-encoding – ^M

Ever had the problem that you tried running a script on a linux-machine and got an error message like the following one?
-bash: ./getRaidFromIrmc.php: /usr/bin/php^M: bad interpreter: No such file or directory

The ^M indicatees that e file you are trying to run is DOS-encoded. This means that its using a CHAR 13 instead of CHAR 10 for a line break and Linux does not like that kind of line break. That often happens if you are writing a script or config file on a Windows machine and transfer it to a Linux machine.
If you try to run/parse the file in linux -> wrong encoding and BAM

The first time I ran into this problem was while deploying a RHEL machine with a faulty kickstart file, but if you know what the problem is it’s quite easy to fix it. Just run “dos2unix” over your file and everything should work again as it should work.

If you often have to modify Linux-files on widows machines I’ld recommend you to use Notepadd++, because it has a feature implemented to set the correct EOL-conversion and lots of more cool and useful plugins like the built in FTP/SFTP-plugin.

Windows performance counters and zabbix

There already quite a lot of blog posts out there which describe how to add performance counters to zabbix. In fact – its not that hard – the tricky thing is, to have one template which gets performance counters from systems wich have different languages installed.

In this case it’s a good idea to use the index of a counter. Indexes of all performance counters can be obtained from teh registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ Windows NT\CurrentVersion\Perflib
In this path there should be a key named “009” (would be englisch, “007” german) or similar, which contains all the key-value pairs.
The easiest way is to copy everything to an editor and look up the keys you need.

I tried to verify the counter ids by using them with “typeperf” – eg: typeperf \234(_Total)\202 but most times the result was:
Error: No valid counters.
If i used the names instead of the keys everything worked fine.

Atm I still don’t know what the reason for this error is, but, if you try it with  zabbix_get everything works fine.
zabbix_get -s server-01 -k “perf_counter[\234(_Total)\202]”
0.000000

Further details about performance counters in Zabbix can be found at:
https://www.packtpub.com/books/content/monitoring-windows-zabbix-18