Powershell to get list of hosts

How can I use Powershell to get a list of hosts from CheckMK - the same as doing a ‘Host Search’ with hostname as blank?

Also, need to be able to work past first search limited to 1,000 entries and get all entries.

If I can get the webpage that is displayed I can parse it to extract out the hostnames.

Hi,
do you mean something like that:
http://CMK/SITE/check_mk/view.py?view_name=allhosts
or
http://CMK/SITE/check_mk/view.py?view_name=allhosts&_username=automation&_secret=YourSecret
or
http://CMK/SITE/check_mk/view.py?view_name=allhosts&_username=automation&_secret=YourSecret&output_format=json

Karl

I want to use PowerShell to query CheckMK to get a list of hostname that would display on the webpage when doing a ‘Host Search’ webpage click.

Currently I go to the webpage and select all (Ctrl-A) then copy and paste results in a text file and then parse the file to extract to hostname.

Hi,
I don’t know Powershell. But I think it’s possible to retrieve information via URLs. You can use the posted URLs in your script. Instead of json, it’s also possible to get python or csv data.

Karl

You can check this link, you will find your solution:

1 Like

This is very promising - thanks.
I have two items though.

  1. I had to add -UseBasicParsing in the line below due to a message about Internet Explorer. I’m not sure if this will affect anything, or more specifically #2 below. I have another script where I interrogate webpages where I had to do this with no other issues.

$result = Invoke-WebRequest -Uri $URI -Method Post -Body $postParams -UseBasicParsing

  1. I’m getting a web response of:
    StatusCode : 200
    StatusDescription : OK
    Content : ERROR: Invalid automation secret for user myusername

I 100% know that the password I’m using is correct.
I assume $mycheckmkuser and $mycheckmsecret are to be set with the username and password I use to log into CheckMK.

I don’t know how to get past this issue.

1 Like

You should use automation user(special for API)

I’m not sure what that is. Where do I look in our NAgios/CheckMK configuration to find it?

Users-create new user and choose option with automation secret

Thanks immensely that worked. I have the results I was looking for.

1 Like

@darusdp If you want, you can Post your solution here for another member :slight_smile:

I kept your coding style but added more error checking and a switch for UseBasicParsing. That code could be incorporated into your other functions

Declaration of a function to get host(s) in check_mk based on RegEx of hostname

function GetCheckmkHost
{
# parameter definition
param(
[Parameter(Position=0, Mandatory=$true)]
[string]$checkmkserver,
[Parameter(Position=1, Mandatory=$true)]
[string]$checkmkinstance,
[Parameter(Position=2, Mandatory=$true)]
[string]$checkmkuser,
[Parameter(Position=3, Mandatory=$true)]
[string]$checkmksecret,
[Parameter(Position=4, mandatory=$true)]
[string]$hostname,
[Parameter(mandatory=$false)]
[bool]$https = $false,
[Parameter(mandatory=$false)]
[switch]$usebasicparsing = $false
)

#######################
# variable definition #
#######################

# declare return variable for the function as hashtable
$return = @{}

# decide wether to use https or not
if ($https)
{
    $URI = "https://"
}
else
{
    $URI = "http://"
}

$URI += "$checkmkserver/$checkmkinstance/check_mk/view.py"

# build the web request for displaying the host with its status
$postParams = @{
_username=$checkmkuser
_secret=$checkmksecret
_transid='-1'
host_regex=$hostname # the hostname to search for
view_name='allhosts'
output_format='json'
}

# execute the web request
try
{
 if ($usebasicparsing)
 {
  $result = Invoke-WebRequest -Uri $URI -Method Post -Body $postParams -UseBasicParsing #DPD 11-24-2020 added -UseBasicParsing
 }
 else
 {
  $result = Invoke-WebRequest -Uri $URI -Method Post -Body $postParams
 }
}
catch
{
 $return.status = 1
 $return.msg = "error while connecting the check_mk api.`r`n$($error[0])"
 # return the error
 Return $return
}

# check if a respones was getting back
if (!$result)
{
    Write-Host "error while connecting the check_mk api."
    Write-Host
    $return.status = 1
    $return.msg = "error while connecting the check_mk api."
    # return the error
    Return $return
}

# check if the web request was successful
if ($result.StatusCode -ne 200 -or $result.Content.StartsWith('ERROR:'))
{
    Write-Host "error in the response from the check_mk api."
    Write-Host
    Write-Host $result
    $return.status = 1
    $return.msg = "error in the response from the check_mk api."
    # return the error
    Return $return
}

# convert the string content of the response into a powershell json object
$json = $result.content | convertfrom-json

# build array of property names
$field = @('')*($json[0].Count)
for ($i=0; $i -lt $json[0].Count; $i++ )
{
 $field[$i] = $json[0][$i]
}

# loop thru all hosts in results to build array of host objects
$hosts = @()
for ($j = 1; $j -lt $json.Count; $j++)
{
 $obj = New-Object PSObject
 for ($i=0; $i -lt $field.Count; $i++)
 {
  Add-Member -InputObject $obj -MemberType NoteProperty -Name $field[$i] -Value $json[$j][$i]
 }
 $hosts += @($obj)
}
$return.status = 0
$return.msg = "found no errors with host $hostname"
$return.host = $hosts
# return the error or the success message
Return $return

}

###########End of function declarations#######################

############

Example

############

connection variables

$mycheckmkserver = “insert checkmk servername”
$mycheckmkinstance = “insert checkmk instance”
$mycheckmkuser = “insert checkmk username using automation secret”
$mycheckmksecret = “insert checkmk automation secret of the username”

host to be checked, set downtime, patched, removed downtime and checked again

$myhost = '.’ # . means all or

execute function to get Checkmk host(s)

$result = GetCheckmkHost -checkmkserver $mycheckmkserver -checkmkinstance $mycheckmkinstance -checkmkuser $mycheckmkuser -checkmksecret $mycheckmksecret -hostname $myhost -usebasicparsing

if host was not healthy, write error and exit

if ($result.status -ne 0)
{
Write-Host “check_mk says the host $myhost is not healthy. Stopping script.”
Write-Output $result.msg
exit
}

#output hostnames to file
foreach ($hostobj in $result.host)
{
Write-Output $hostobj.host
}
exit

1 Like

Thank you @darusdp :slight_smile:

New issue, in checkmkdowntime at:
$URI += “$checkmkserver/$checkmkinstance/check_mk/webapi.py”
#build the web request for checking if the host exists in check_mk
$Body = @{
action=“get_host”
_username=$checkmkuser
_secret=$checkmksecret
request_format=“json”
output_format=“json”
hostname=$hostname
}

$result = Invoke-WebRequest -Uri $URI -Method Post -Body $Body -UseBasicParsing
.
.
.
if ( ($result.content | ConvertFrom-Json).result_code -ne 0 )

$result.content = {“result”: “Hostname is missing”, “result_code”: 1}

Yet, in $Body hostname is set correct. The same hostname that work with function checkmkhealth

Any ideas?

you need something like this:

?_do_confirm=Yes&_do_actions=yes&_transid=-1&view_name=hoststatus&site=&_ack_sticky=on&_ack_otify=off&output_format=JSON&_username=&_secret=&_down_comment=$YOURComment&_down_from_now=From+now+for&_down_minutes=$DurationInMin&host=$hostname

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.