143 lines
4.6 KiB
Python
143 lines
4.6 KiB
Python
import requests
|
|
import json
|
|
import urllib3
|
|
import csv
|
|
import socket
|
|
import sys
|
|
|
|
# Kikapcsoljuk az SSL figyelmeztetéseket
|
|
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
|
|
|
# --- KONFIGURÁCIÓ ---
|
|
URL = "http://10.102.1.201:8080/monitoring/check_mk/api/1.0"
|
|
USERNAME = "cmkadmin"
|
|
PASSWORD = "cmkadmin123"
|
|
|
|
# CSV fájl elérési útja, a szkript új helyéhez viszonyítva (Docker/checkmk_aps/)
|
|
CSV_FILE_PATH = "hosts_for_checkmk.csv"
|
|
|
|
session = requests.Session()
|
|
session.auth = (USERNAME, PASSWORD)
|
|
session.headers.update({"Accept": "application/json", "Content-Type": "application/json"})
|
|
|
|
def resolve_hostname_to_ip(hostname):
|
|
"""Feloldja a hosztnevet IP címre. Ha már IP cím, visszaadja azt."""
|
|
try:
|
|
socket.inet_pton(socket.AF_INET, hostname)
|
|
return hostname # Már IP cím
|
|
except socket.error:
|
|
# Ha nem IP cím, próbáljuk meg feloldani
|
|
try:
|
|
return socket.gethostbyname(hostname)
|
|
except socket.gaierror:
|
|
print(f" [WARNING] Could not resolve hostname: {hostname}")
|
|
return None
|
|
|
|
def add_host(name, ip, parents=None):
|
|
"""
|
|
Hozzáad egy hosztot a Checkmk-hoz.
|
|
Minden hoszt a gyökér mappába kerül.
|
|
"""
|
|
checkmk_folder_path_slug = "/" # Mindig a gyökér mappa
|
|
|
|
print(f"Adding host: {name} ({ip}) to root folder '/''...")
|
|
|
|
attributes = {
|
|
"ipaddress": ip,
|
|
"tag_agent": "no-agent", # Csak pingeljen, ne keressen agentet
|
|
}
|
|
|
|
if parents:
|
|
attributes["parents"] = parents
|
|
|
|
payload = {
|
|
"host_name": name,
|
|
"folder": checkmk_folder_path_slug, # Folder must be the slugified full path
|
|
"attributes": attributes
|
|
}
|
|
|
|
response = session.post(
|
|
f"{URL}/domain-types/host_config/collections/all",
|
|
json=payload
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
print(f" [OK] Host '{name}' successfully added.")
|
|
elif response.status_code == 400 and "already exists" in response.text:
|
|
print(f" [INFO] Host '{name}' already exists.")
|
|
else:
|
|
print(f" [ERROR] Failed to add {name}: {response.status_code} - {response.text}")
|
|
print(f" [DEBUG] Payload: {json.dumps(payload)}")
|
|
|
|
def activate_changes():
|
|
"""
|
|
Aktiválja a Checkmk-ban lévő függőben lévő változásokat.
|
|
"""
|
|
print("Fetching pending changes to get ETag...")
|
|
|
|
etag_session = requests.Session()
|
|
etag_session.auth = (USERNAME, PASSWORD)
|
|
etag_session.headers.update({"Accept": "application/json"})
|
|
|
|
resp = etag_session.get(f"{URL}/domain-types/activation_run/collections/pending_changes")
|
|
if resp.status_code != 200:
|
|
print(f" [ERROR] Could not fetch pending changes: {resp.text}")
|
|
return
|
|
|
|
etag = resp.headers.get("ETag")
|
|
|
|
# Ha nincs ETag vagy nincs függőben lévő változás, ne csináljunk semmit
|
|
if not etag or not resp.json().get('value'): # ellenőrizzük, hogy 'value' nem üres-e
|
|
print(" [INFO] No pending changes to activate.")
|
|
return
|
|
|
|
print(f"Activating changes with ETag: {etag}")
|
|
|
|
# Az aktiváláshoz be kell állítani az If-Match fejlécet
|
|
activation_headers = {
|
|
"Accept": "application/json",
|
|
"Content-Type": "application/json",
|
|
"If-Match": etag
|
|
}
|
|
|
|
response = session.post(
|
|
f"{URL}/domain-types/activation_run/actions/activate-changes/invoke",
|
|
headers=activation_headers,
|
|
json={"redirect": False, "sites": ["monitoring"]}
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
print(" [OK] Changes activated successfully.")
|
|
else:
|
|
print(f" [ERROR] Failed to activate changes: {response.status_code} - {response.text}")
|
|
|
|
if __name__ == "__main__":
|
|
hosts_to_import = []
|
|
|
|
try:
|
|
with open(CSV_FILE_PATH, mode='r', newline='', encoding='utf-8') as file:
|
|
reader = csv.DictReader(file)
|
|
for row in reader:
|
|
hostname = row['Host'].strip()
|
|
|
|
ip_address = resolve_hostname_to_ip(hostname)
|
|
|
|
if ip_address:
|
|
hosts_to_import.append({
|
|
"name": hostname,
|
|
"ip": ip_address,
|
|
})
|
|
else:
|
|
print(f"Skipping host '{hostname}' due to unresolved IP address.")
|
|
except FileNotFoundError:
|
|
print(f"ERROR: CSV file not found at {CSV_FILE_PATH}")
|
|
sys.exit(1)
|
|
|
|
# Nincs mappalétrehozás, minden a gyökérbe kerül
|
|
|
|
# Hosztok hozzáadása a Checkmk-hoz
|
|
for host in hosts_to_import:
|
|
add_host(host['name'], host['ip']) # Nincs 'folder_display' paraméter
|
|
|
|
activate_changes()
|