<reponame>bpoje/checkmk-python-rest-api
#!/bin/python3

from Checkmk import *
import re as re
import time

#Init checkmk rest api
def init_checkmk(site_name, cmk_rest_url, cafile, username, secret_token_filename):
    # Read secret token from disk
    secret_token = open(secret_token_filename,'r').readline().strip('\n')
    
    bearerAuth = [username, secret_token]
    cmk = Checkmk(cmk_rest_url,cafile,bearerAuth,site_name)
    #print (cmk.server_url())

    return cmk

def test_get_host(cmk):
    #Get specific host
    print('----------------------')
    print(' get host:')
    print('----------------------')

    #host_id = 'dc-awx'
    host_id = 'my-test'
    host = cmk.host_get(host_id,effective_attributes=True,display_req=False,display_res=False)

    if (host != None):
        etag = host[1]
        host = host[0]
        host.output()
        print(f'etag: {etag}')
    else:
        print(f'No host {host_id} found!\n')

def test_get_all_hosts(cmk):
    #Get all hosts
    print('----------------------')
    print(' get all host:')
    print('----------------------')
    hosts = cmk.host_get_all(display_req=False,display_res=False)
    
    if (hosts != None):
        print (f'Number of hosts: {len(hosts)}\n')
    
        #regex search pattern
        pattern = re.compile('^.*[A-Z]+.*$', re.UNICODE)
    
        # Output all hosts
        for host in hosts:
            host.output(1)
    
        # Output all hosts with any upper case letters
        #for host in hosts:
        #    if (pattern.search(host.id) != None):
        #        host.output(1)
        
        # Output all hosts in linux folder
        #for host in hosts:
        #    if (host.folder.lower() == 'linux'):
        #        host.output(1)

def test_create_host(cmk):
    print('----------------------')
    print(' define a host:')
    print('----------------------')
    
    #Host that exists
    #new_host = Host(id='dc-repo',title='my-test',folder='/linux',ipaddress='10.15.146.250')
    
    #Non existing host using static ip
    new_host = Host(id='my-test',title='my-test',folder='/linux',ipaddress='10.15.146.250')

    #Non existing host (ip from hostname)
    #new_host = Host(id='my-test',title='my-test',folder='/linux')

    new_host.output(1)
    
    print('----------------------')
    print(' create host:')
    print('----------------------')
    create_result = cmk.create_host(new_host,send=True,display_req=False,display_res=False)
    if (type(create_result.create_return) == Create_fail):
        create_result.output(show_header=True)
        print('fail')
    else:
        create_result.output(show_header=True)
        print('ok')

def test_activate_changes(cmk, apply_foreign_changes):
    print('----------------------')
    print(' activate changes:')
    print('----------------------')

    change_result = cmk.activate_changes(force_foreign_changes=apply_foreign_changes,send=True,display_req=False,display_res=False)
    if (type(change_result.changes_return) == Changes_fail):
        change_result.output(show_header=False)
        print('fail')
    else:
        change_result.output(show_header=False)
        print('ok')

def test_discover_services(cmk):
    print('----------------------')
    print(' discover services:')
    print('----------------------')

    new_host = Host(id='my-test',folder='/linux')

    # mode is one of the enum values: 'new', 'remove', 'fix_all', 'refresh', 'only_host_labels'
    discover_result = cmk.discover_services(new_host,mode='fix_all',send=True,display_req=True,display_res=True)
    if (type(discover_result.discover_return) == Discover_fail):
        discover_result.output(show_header=True)
        print('fail')
    else:
        discover_result.output(show_header=True)
        print('ok')

def test_delete_host(cmk):
    # Delete hosts
    new_hostx = Host(id='my-test',folder='/linux')
    
    print('----------------------')
    print(' delete host:')
    print('----------------------')
    delete_result = cmk.delete_host(new_hostx,send=True,display_req=False,display_res=False)
    if (type(delete_result.delete_return) == Delete_fail):
        delete_result.output(show_header=False)
        print('fail')
    else:
        delete_result.output(show_header=False)
        print('ok')

def test_get_all_folders(cmk):
    print('----------------------')
    print(' get all folders:')
    print('----------------------')
    get_all_folders_result = cmk.get_all_folders('~',recursive=True,show_hosts=True,send=True,display_req=False,display_res=False)
    if (type(get_all_folders_result.get_all_folders_return) == GetAllFolders_fail):
        get_all_folders_result.output(show_header=True)
        print('fail')
    else:
        get_all_folders_result.output(show_header=True)
        print('ok')

def test_get_hosts_in_folder(cmk):
    print('----------------------')
    print(' get hosts in folder:')
    print('----------------------')

    folder = '~'
    print(f'folder: {folder}')

    hosts = cmk.show_all_hosts(folder,send=True,display_req=False,display_res=False)
    if (hosts != None):
        for host in hosts:
            host.output(1)

def test_remove_host_tag(cmk):
    print('----------------------')
    print(' remove host tag:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    tag_group = 'tag_pumpa'

    update_result = cmk.remove_host_tag(update_host,tag_group,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

def test_update_host_tag(cmk):
    print('----------------------')
    print(' update host tag:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    tag_group = 'tag_pumpa'
    tag_group_value = 'bs4040'

    update_result = cmk.update_host_tag(update_host,tag_group,tag_group_value,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

#Remove ipaddress (resolve ip from hostname)
def test_remove_host_ipaddress(cmk):
    print('----------------------')
    print(' remove host ipaddress:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    update_result = cmk.remove_host_ipaddress(update_host,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

def test_update_host_ipaddress(cmk):
    print('----------------------')
    print(' update host ipaddress:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    new_ip='192.168.1.14'

    update_result = cmk.update_host_ipaddress(update_host,new_ip,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

#Update host with custom request body
def test_update_with_body(cmk):
    print('----------------------')
    print(' update with manual request body:')
    print('----------------------')

    #Which host to modify?
    update_host = Host(id='my-test',folder='/linux')

    #New values
    new_ip = '192.168.1.123'
    tag_group = 'tag_pumpa'
    tag_group_value = 'bs0050'

    #----------------------------------------------
    #Example 1:
    #  Change checkmk host parameter (don't change other parameters):
    #  {"update_attributes": {"tag_pumpa": "bs0050"}}
    data={}
    data['update_attributes'] = {}
    data['update_attributes'][tag_group] = tag_group_value
    data = js.dumps(data)
    #----------------------------------------------
    #Example 2:
    #  Remove checkmk parameter (don't change other parameters):
    #  {"remove_attributes": ["tag_pumpa_type"]}
    #data={}
    #data['remove_attributes'] = [ tag_group, ]
    #data = js.dumps(data)
    #----------------------------------------------
    #Example 3:
    #  Change all checkmk host parameters
    #  (any parameters not defined in body will be cleared)
    #  {"attributes": {"ipaddress": "192.168.1.123"}}
    #data={}
    #data['attributes'] = {}
    #data['attributes']['ipaddress'] = new_ip
    #data = js.dumps(data)
    #----------------------------------------------

    #Find etag
    etag=cmk.get_etag(update_host)

    print(f'etag: {etag}')
    print(f'data: {data}')

    #Execute update
    update_result = cmk.update_host(update_host,data,etag,send=True,display_req=False,display_res=False)
    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        #print(update_result.status_code)
        #print(update_result.update_return.title)
        #print(update_result.update_return.response_header)
        print('fail')
    else:
        update_result.output(show_header=True)
        #print(update_result.status)
        print('ok')

# Test
site_name = 'nadzor'
cmk_rest_url = 'https://checkmk.example.com/site1/check_mk/api/1.0'
cafile = 'config/corp_ca.pem'
username = 'automation'
secret_token_filename = f'../config/secret/secret-{site_name}.token'

#Init checkmk rest api
cmk = init_checkmk(site_name, cmk_rest_url, cafile, username, secret_token_filename)

#Example:
#Delete, create "my-test" host in CheckMK, set its tag and activate changes

test_get_host(cmk)
test_delete_host(cmk)
test_activate_changes(cmk,apply_foreign_changes=True)
#test_get_host(cmk)
#test_get_all_hosts(cmk)
test_create_host(cmk)
test_activate_changes(cmk,apply_foreign_changes=True)
test_discover_services(cmk)
#test_delete_host(cmk)
#test_activate_changes(cmk,apply_foreign_changes=True)
#test_get_all_folders(cmk)
#test_get_hosts_in_folder(cmk)

#Changed ip and added tag in examples below:
test_get_host(cmk)
test_update_host_tag(cmk)
test_get_host(cmk)
test_remove_host_ipaddress(cmk)
test_get_host(cmk)
test_update_host_ipaddress(cmk)
test_get_host(cmk)
test_remove_host_tag(cmk)
test_get_host(cmk)
#test_update_with_body(cmk)
test_get_host(cmk)

#Sleep to give server some time to process changes
time.sleep(1)
test_activate_changes(cmk,apply_foreign_changes=True)

#Note: GUI can show pending changes for a while, but should eventually disappear.
#To see changes in web GUI you need to refresh the page.

#!/bin/python3

from Checkmk import *
import re as re
import time

#Init checkmk rest api
def init_checkmk(site_name, cmk_rest_url, cafile, username, secret_token_filename):
    # Read secret token from disk
    secret_token = open(secret_token_filename,'r').readline().strip('\n')
    
    bearerAuth = [username, secret_token]
    cmk = Checkmk(cmk_rest_url,cafile,bearerAuth,site_name)
    #print (cmk.server_url())

    return cmk

def test_get_host(cmk):
    #Get specific host
    print('----------------------')
    print(' get host:')
    print('----------------------')

    #host_id = 'dc-awx'
    host_id = 'my-test'
    host = cmk.host_get(host_id,effective_attributes=True,display_req=False,display_res=False)

    if (host != None):
        etag = host[1]
        host = host[0]
        host.output()
        print(f'etag: {etag}')
    else:
        print(f'No host {host_id} found!\n')

def test_get_all_hosts(cmk):
    #Get all hosts
    print('----------------------')
    print(' get all host:')
    print('----------------------')
    hosts = cmk.host_get_all(display_req=False,display_res=False)
    
    if (hosts != None):
        print (f'Number of hosts: {len(hosts)}\n')
    
        #regex search pattern
        pattern = re.compile('^.*[A-Z]+.*$', re.UNICODE)
    
        # Output all hosts
        for host in hosts:
            host.output(1)
    
        # Output all hosts with any upper case letters
        #for host in hosts:
        #    if (pattern.search(host.id) != None):
        #        host.output(1)
        
        # Output all hosts in linux folder
        #for host in hosts:
        #    if (host.folder.lower() == 'linux'):
        #        host.output(1)

def test_create_host(cmk):
    print('----------------------')
    print(' define a host:')
    print('----------------------')
    
    #Host that exists
    #new_host = Host(id='dc-repo',title='my-test',folder='/linux',ipaddress='10.15.146.250')
    
    #Non existing host using static ip
    new_host = Host(id='my-test',title='my-test',folder='/linux',ipaddress='10.15.146.250')

    #Non existing host (ip from hostname)
    #new_host = Host(id='my-test',title='my-test',folder='/linux')

    new_host.output(1)
    
    print('----------------------')
    print(' create host:')
    print('----------------------')
    create_result = cmk.create_host(new_host,send=True,display_req=False,display_res=False)
    if (type(create_result.create_return) == Create_fail):
        create_result.output(show_header=True)
        print('fail')
    else:
        create_result.output(show_header=True)
        print('ok')

def test_activate_changes(cmk, apply_foreign_changes):
    print('----------------------')
    print(' activate changes:')
    print('----------------------')

    change_result = cmk.activate_changes(force_foreign_changes=apply_foreign_changes,send=True,display_req=False,display_res=False)
    if (type(change_result.changes_return) == Changes_fail):
        change_result.output(show_header=False)
        print('fail')
    else:
        change_result.output(show_header=False)
        print('ok')

def test_discover_services(cmk):
    print('----------------------')
    print(' discover services:')
    print('----------------------')

    new_host = Host(id='my-test',folder='/linux')

    # mode is one of the enum values: 'new', 'remove', 'fix_all', 'refresh', 'only_host_labels'
    discover_result = cmk.discover_services(new_host,mode='fix_all',send=True,display_req=True,display_res=True)
    if (type(discover_result.discover_return) == Discover_fail):
        discover_result.output(show_header=True)
        print('fail')
    else:
        discover_result.output(show_header=True)
        print('ok')

def test_delete_host(cmk):
    # Delete hosts
    new_hostx = Host(id='my-test',folder='/linux')
    
    print('----------------------')
    print(' delete host:')
    print('----------------------')
    delete_result = cmk.delete_host(new_hostx,send=True,display_req=False,display_res=False)
    if (type(delete_result.delete_return) == Delete_fail):
        delete_result.output(show_header=False)
        print('fail')
    else:
        delete_result.output(show_header=False)
        print('ok')

def test_get_all_folders(cmk):
    print('----------------------')
    print(' get all folders:')
    print('----------------------')
    get_all_folders_result = cmk.get_all_folders('~',recursive=True,show_hosts=True,send=True,display_req=False,display_res=False)
    if (type(get_all_folders_result.get_all_folders_return) == GetAllFolders_fail):
        get_all_folders_result.output(show_header=True)
        print('fail')
    else:
        get_all_folders_result.output(show_header=True)
        print('ok')

def test_get_hosts_in_folder(cmk):
    print('----------------------')
    print(' get hosts in folder:')
    print('----------------------')

    folder = '~'
    print(f'folder: {folder}')

    hosts = cmk.show_all_hosts(folder,send=True,display_req=False,display_res=False)
    if (hosts != None):
        for host in hosts:
            host.output(1)

def test_remove_host_tag(cmk):
    print('----------------------')
    print(' remove host tag:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    tag_group = 'tag_pumpa'

    update_result = cmk.remove_host_tag(update_host,tag_group,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

def test_update_host_tag(cmk):
    print('----------------------')
    print(' update host tag:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    tag_group = 'tag_pumpa'
    tag_group_value = 'bs4040'

    update_result = cmk.update_host_tag(update_host,tag_group,tag_group_value,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

#Remove ipaddress (resolve ip from hostname)
def test_remove_host_ipaddress(cmk):
    print('----------------------')
    print(' remove host ipaddress:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    update_result = cmk.remove_host_ipaddress(update_host,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

def test_update_host_ipaddress(cmk):
    print('----------------------')
    print(' update host ipaddress:')
    print('----------------------')

    update_host = Host(id='my-test',folder='/linux')

    new_ip='192.168.1.14'

    update_result = cmk.update_host_ipaddress(update_host,new_ip,send=True,display_req=False,display_res=False)

    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        print('fail')
    else:
        update_result.output(show_header=True)
        print('ok')

#Update host with custom request body
def test_update_with_body(cmk):
    print('----------------------')
    print(' update with manual request body:')
    print('----------------------')

    #Which host to modify?
    update_host = Host(id='my-test',folder='/linux')

    #New values
    new_ip = '192.168.1.123'
    tag_group = 'tag_pumpa'
    tag_group_value = 'bs0050'

    #----------------------------------------------
    #Example 1:
    #  Change checkmk host parameter (don't change other parameters):
    #  {"update_attributes": {"tag_pumpa": "bs0050"}}
    data={}
    data['update_attributes'] = {}
    data['update_attributes'][tag_group] = tag_group_value
    data = js.dumps(data)
    #----------------------------------------------
    #Example 2:
    #  Remove checkmk parameter (don't change other parameters):
    #  {"remove_attributes": ["tag_pumpa_type"]}
    #data={}
    #data['remove_attributes'] = [ tag_group, ]
    #data = js.dumps(data)
    #----------------------------------------------
    #Example 3:
    #  Change all checkmk host parameters
    #  (any parameters not defined in body will be cleared)
    #  {"attributes": {"ipaddress": "192.168.1.123"}}
    #data={}
    #data['attributes'] = {}
    #data['attributes']['ipaddress'] = new_ip
    #data = js.dumps(data)
    #----------------------------------------------

    #Find etag
    etag=cmk.get_etag(update_host)

    print(f'etag: {etag}')
    print(f'data: {data}')

    #Execute update
    update_result = cmk.update_host(update_host,data,etag,send=True,display_req=False,display_res=False)
    if (type(update_result.update_return) == Update_fail):
        update_result.output(show_header=True)
        #print(update_result.status_code)
        #print(update_result.update_return.title)
        #print(update_result.update_return.response_header)
        print('fail')
    else:
        update_result.output(show_header=True)
        #print(update_result.status)
        print('ok')

# Test
site_name = 'nadzor'
cmk_rest_url = 'https://checkmk.example.com/site1/check_mk/api/1.0'
cafile = 'config/corp_ca.pem'
username = 'automation'
secret_token_filename = f'../config/secret/secret-{site_name}.token'

#Init checkmk rest api
cmk = init_checkmk(site_name, cmk_rest_url, cafile, username, secret_token_filename)

#Example:
#Delete, create "my-test" host in CheckMK, set its tag and activate changes

test_get_host(cmk)
test_delete_host(cmk)
test_activate_changes(cmk,apply_foreign_changes=True)
#test_get_host(cmk)
#test_get_all_hosts(cmk)
test_create_host(cmk)
test_activate_changes(cmk,apply_foreign_changes=True)
test_discover_services(cmk)
#test_delete_host(cmk)
#test_activate_changes(cmk,apply_foreign_changes=True)
#test_get_all_folders(cmk)
#test_get_hosts_in_folder(cmk)

#Changed ip and added tag in examples below:
test_get_host(cmk)
test_update_host_tag(cmk)
test_get_host(cmk)
test_remove_host_ipaddress(cmk)
test_get_host(cmk)
test_update_host_ipaddress(cmk)
test_get_host(cmk)
test_remove_host_tag(cmk)
test_get_host(cmk)
#test_update_with_body(cmk)
test_get_host(cmk)

#Sleep to give server some time to process changes
time.sleep(1)
test_activate_changes(cmk,apply_foreign_changes=True)

#Note: GUI can show pending changes for a while, but should eventually disappear.
#To see changes in web GUI you need to refresh the page.
#!/bin/python3 #Init checkmk rest api # Read secret token from disk #print (cmk.server_url()) #Get specific host #host_id = 'dc-awx' #Get all hosts #regex search pattern # Output all hosts # Output all hosts with any upper case letters #for host in hosts: #    if (pattern.search(host.id) != None): #        host.output(1) # Output all hosts in linux folder #for host in hosts: #    if (host.folder.lower() == 'linux'): #        host.output(1) #Host that exists #new_host = Host(id='dc-repo',title='my-test',folder='/linux',ipaddress='10.15.146.250') #Non existing host using static ip #Non existing host (ip from hostname) #new_host = Host(id='my-test',title='my-test',folder='/linux') # mode is one of the enum values: 'new', 'remove', 'fix_all', 'refresh', 'only_host_labels' # Delete hosts #Remove ipaddress (resolve ip from hostname) #Update host with custom request body #Which host to modify? #New values #---------------------------------------------- #Example 1: #  Change checkmk host parameter (don't change other parameters): #  {"update_attributes": {"tag_pumpa": "bs0050"}} #---------------------------------------------- #Example 2: #  Remove checkmk parameter (don't change other parameters): #  {"remove_attributes": ["tag_pumpa_type"]} #data={} #data['remove_attributes'] = [ tag_group, ] #data = js.dumps(data) #---------------------------------------------- #Example 3: #  Change all checkmk host parameters #  (any parameters not defined in body will be cleared) #  {"attributes": {"ipaddress": "192.168.1.123"}} #data={} #data['attributes'] = {} #data['attributes']['ipaddress'] = new_ip #data = js.dumps(data) #---------------------------------------------- #Find etag #Execute update #print(update_result.status_code) #print(update_result.update_return.title) #print(update_result.update_return.response_header) #print(update_result.status) # Test #Init checkmk rest api #Example: #Delete, create "my-test" host in CheckMK, set its tag and activate changes #test_get_host(cmk) #test_get_all_hosts(cmk) #test_delete_host(cmk) #test_activate_changes(cmk,apply_foreign_changes=True) #test_get_all_folders(cmk) #test_get_hosts_in_folder(cmk) #Changed ip and added tag in examples below: #test_update_with_body(cmk) #Sleep to give server some time to process changes #Note: GUI can show pending changes for a while, but should eventually disappear. #To see changes in web GUI you need to refresh the page.