Outils pour utilisateurs

Outils du site


blog

Zabbix script python monitor unmonitor autoadd host

Ce script permet :

  • l'ajout automatique d'un nouveau hôte à superviser
  • La désactivation automatique de la supervision d'un hôte

Il prend comme paramètre le nom de l'hôte ou l'adresse IP.

Il servait au “cloud”, dans un contexte de création automatique de VM et destruction automatique après traitement.

zbxunmon.py

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# License: GNU GPL
 
""" Switch Zabbix status to 'Monitored' or 'Not monitored'
zbxunmon.ini
[SERVER]
URL=https://acme.fr/zabbix
USER=api
PWD=P@ssw0rd
"""
 
import socket
import argparse
import configparser
from sys import argv, exit, stderr
from os import environ, path
 
import zabbix_client
 
ficconf=argv[0]
ficconf=ficconf.replace('.py', '')
ficconf=ficconf + '.ini' # Work even if this script's name isn't ended by ".py"
 
config = configparser.ConfigParser()
config.read(ficconf)
zbxconf     = config['SERVER']
zabbix_url  = config['SERVER']['URL']
zabbix_user = zbxconf.get('USER')
zabbix_pwd  = zbxconf.get('PWD')
try:
    environ['http_proxy']=environ['https_proxy']=zbxconf.get('HTTP_PROXY')
except TypeError:
    pass
 
 
# Zabbix 'status' code
MONITORED='0'
NOT_MONITORED='1'
 
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--enable',  action='store_true', help='Enable')
parser.add_argument('-d', '--disable', action='store_true', help='Disable')
parser.add_argument('-i', '--ip',   help='IP Address')
parser.add_argument('-n', '--name', help='Hostname')
args = parser.parse_args()
 
def die(exitcode, *objs):
    """ print on STDERR
    """
    print(*objs, file=stderr)
    try:
        s
    except NameError:
        pass
    else: # If no exception occured, do :
        s.user.logout()
    exit(exitcode)
 
 
 
if (not args.ip and not args.name) and (not args.enable and not args.disable):
    die(1, "{0}: missing arguments\nTry '{0} -h' for more information.".format(argv[0]))
 
ip = args.ip
hostname=args.name
 
def zbx_ip2hostid(s, ip):
    hostinterface=s.hostinterface.get(filter={'ip':ip}, output=['hostid'])
    if len(hostinterface) == 1:
        hostinterface=hostinterface[0]
        return(hostinterface['hostid'])
    else:
        die(7, 'IP not found')
 
def zbx_host2hostid(s, host):
    host=s.host.get(filter={'host':host}, output=['hostid'])
    if len(host) == 1:
        host=host[0]
        return(host['hostid'])
    else:
        die(6, 'Host not found')
 
def zbx_getstatus(hostid):
    host=s.host.get(hostids=hostid, output=['status'])
    if len(host) == 1:
        host=host[0]
        return(host['status'])
    else:
        die(8, "Can't get status")
 
 
s = zabbix_client.ZabbixServerProxy(zabbix_url)
s.user.login(user=zabbix_user, password=zabbix_pwd)
 
if ip:
    hostid=zbx_ip2hostid(s, ip)
elif hostname:
    hostid=zbx_host2hostid(s, hostname)
else:
    die(2, 'Fatal error, ip or hostname need to be provide !')
 
 
# Change Monitor status
if args.disable :
    s.host.update({'hostid': hostid, 'status': NOT_MONITORED})
    if zbx_getstatus(hostid) != NOT_MONITORED:
        die(4, 'Fail to change status to NOT_MONITORED')
elif args.enable :
    s.host.update({'hostid': hostid, 'status': MONITORED})
    if zbx_getstatus(hostid) != MONITORED:
        die(4, 'Fail to change status to MONITORED')
else:
    die(5, 'Fatal error, autodestruction')
 
 
s.user.logout()

zbxunmon.ini

[SERVER]
# If HTTP is used instead of HTTPS password will be sent in clear !
URL=https://acme.fr/zabbix
USER=api
PWD=P@ssw0rd
 
# For GNU/Linux : Empty value for no proxy. Comment this line for default value (env http_proxy or https_proxy)
HTTP_PROXY=

requirements.txt

zabbix-client>=0.1.1
2025/03/24 15:06

Zabbix External Check - Script lancés coté serveur

Exemple supervision date expiration certificat

NB : pour que les modif soient prises en compte il fait attendre. Le fait de redémarer le service zabbix-server n'est pas suffisant

/etc/zabbix/zabbix_server.conf

ExternalScripts=/etc/zabbix/externalscripts
usermod -s bash zabbix
mkdir /etc/zabbix/externalscripts
service zabbix-server restart

/etc/zabbix/externalscripts/ssl-cert-check-zabbixwrap.sh

#! /bin/bash
 
ssl-cert-check $* |sed -e 's/^.*days=//

Create item with key field : ssl-cert-check-zabbixwrap.sh[“-s 171.33.77.65 -p 443”]

En cas de pb

Configuration / Hosts / Items Colone “Error”, Survol de la souris pour afficher l'erreur.

et

tail -F /var/log/zabbix-server/zabbix_server.log
2025/03/24 15:06

Yum force pb erreur le fichier de l'installation entre en conflit avec le fichier du paquet

Comment faire un yum --force en trichant un peu

Pb

le fichier /var/www de l'installation de httpd-2.4.6-40.el7.centos.1.x86_64 entre en conflit avec le fichier du paquet plop-1.8.8-2.noarch
Solution

Solution possible : Refaire proprement le package plop

ou forcer ! Nous allons utiliser dnf download ou yumdownloader (packet yum-utils)

# yum install yum-utils
# yumdownloader httpd
 
dnf download httpd
rpm -Uvh --force httpd-2.4.6-40.el7.centos.1.x86_64.rpm

Pour que ça marche, il faut faire la même chose avec toutes les dépendances

# yumdownloader --resolve httpd-tools
# yumdownloader httpd-tools
dnf download httpd-tools
rpm -Uvh --force httpd-2.4.6-40.el7.centos.1.x86_64.rpm httpd-tools-2.4.6-40.el7.centos.1.x86_64.rpm
2025/03/24 15:06

Xorg.conf généré par nvidia-xconfig

Voir :

nvidia-xconfig
nvidia-xconfig -a

/etc/X11/xorg.conf

# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig:  version 440.64

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "Files"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Unknown"
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "nvidia"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "nvidia"
    Monitor        "Monitor0"
    DefaultDepth    24
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Faire fonctionner la carte intégrée pour l'écran

Voir LinuxFr - Utiliser la carte graphique NVIDIA et la carte INTEL intégrée

PS : Xorg est obligé de créer un “Screen” par carte graphique, et qu'un Screen n'est pas un écran physique

/etc/X11/xorg.conf

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen1"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "Files"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Unknown"
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "nvidia"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    #Option         "ConstrainCursor" "off"
    Option         "UseDisplayDevice" "none"
    Option         "ProbeAllGpus" "false"
    Option         "AllowEmptyInitialConfiguration"
    #Option         "IgnoreDisplayDevices" "CRT"
EndSection

Section "Device"
    Identifier     "Intel"
    BusID          "PCI:0:2:0"
    Driver         "modesetting"
    VendorName     "Intel Corporation"
    #BoardName      "Display controller"
    #ModelName      "Device 3e98"
    #Option         "AccelMethod" "SNA"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Intel"
    Monitor        "Monitor0"
    DefaultDepth    24
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Section "Screen"
    Identifier     "Screen1"
    Device         "nvidia"
EndSection
$ lspci | grep 'Display controller: Intel Corporation Device' | awk -F'[:. ]' '{print $1, $2, $3}' | sed -r 's|0([0-9]) |\1:|g'
0:2:0

https://github.com/Bumblebee-Project/Bumblebee/blob/master/conf/xorg.conf.nvidia

xorg.conf

Section "ServerLayout"
    Identifier  "Layout0"
    Option      "AutoAddDevices" "false"
    Option      "AutoAddGPU" "false"
EndSection

Section "Device"
    Identifier  "DiscreteNvidia"
    Driver      "nvidia"
    VendorName  "NVIDIA Corporation"

#   If the X server does not automatically detect your VGA device,
#   you can manually set it here.
#   To get the BusID prop, run `lspci | egrep 'VGA|3D'` and input the data
#   as you see in the commented example.
#   This Setting may be needed in some platforms with more than one
#   nvidia card, which may confuse the proprietary driver (e.g.,
#   trying to take ownership of the wrong device). Also needed on Ubuntu 13.04.
#   BusID "PCI:01:00:0"

#   Setting ProbeAllGpus to false prevents the new proprietary driver
#   instance spawned to try to control the integrated graphics card,
#   which is already being managed outside bumblebee.
#   This option doesn't hurt and it is required on platforms running
#   more than one nvidia graphics card with the proprietary driver.
#   (E.g. Macbook Pro pre-2010 with nVidia 9400M + 9600M GT).
#   If this option is not set, the new Xorg may blacken the screen and
#   render it unusable (unless you have some way to run killall Xorg).
    Option "ProbeAllGpus" "false"

    Option "NoLogo" "true"
    Option "UseEDID" "false"
    Option "UseDisplayDevice" "none"
EndSection

https://gist.githubusercontent.com/mokkabonna/7ebf99590e42fcee9dfe/raw/6963a2e2ff6255a2ee251435953eba27cc9f5275/gistfile1.txt

xorg.conf

Section "ServerLayout"
    Identifier "layout"
    Screen 0 "nvidia"
    #Inactive "intel" # Not supported ?
EndSection

Section "Device"
    Identifier "intel"
    Driver "intel"
    BusID "PCI:0@0:2:0"
    Option "AccelMethod" "SNA"
EndSection

Section "Screen"
    Identifier "intel"
    Device "intel"
EndSection

Section "Device"
    Identifier "nvidia"
    Driver "nvidia"
    BusID "PCI:2@0:0:0"
    Option "ConstrainCursor" "off"
EndSection

Section "Screen"
    Identifier "nvidia"
    Device "nvidia"
    Option "AllowEmptyInitialConfiguration" "on"
    Option "IgnoreDisplayDevices" "CRT"
EndSection

https://gist.githubusercontent.com/dvejmz/879eebb607b9069b536b/raw/df2ec920573326cd05f95452d5af87a4d055e6e4/sample-xorg.conf

xorg.conf

Section "ServerLayout"
	Identifier "layout"
	Screen 0 "nvidia"
	#Inactive "intel" # Not supported ?
EndSection

Section "Device"
	Identifier "nvidia"
	Driver "nvidia"
	BusID "PCI:1:0:0"
EndSection

Section "Screen"
	Identifier "nvidia"
	Device "nvidia"
	Option "AllowEmptyInitialConfiguration" "Yes"
EndSection

Section "Device"
	Identifier "intel"
	Driver "modesetting"
	Option "AccelMethod" "none"
EndSection

Section "Screen"
	Identifier "intel"
	Device "intel"
EndSection
2025/03/24 15:06

XML xpath parse

Il existe deux langages de requêtes XML : XPath et XQuery.

Voir aussi :

Lint

xmllint --noout fic.xml

xpath

virsh dumpxml VM1 |xpath -q -e "/domain/devices/disk[@type='file']/source/@file[1]"

Ansible

Exemple

/etc/ImageMagick-6/policy.xml

<policymap>
  <policy domain="resource" name="memory" value="256MiB"/>
  <policy domain="resource" name="map" value="512MiB"/>
  <policy domain="resource" name="width" value="16KP"/>
  <policy domain="resource" name="height" value="16KP"/>
  <policy domain="resource" name="area" value="128MB"/>
  <policy domain="resource" name="disk" value="1GiB"/>
  <!-- <policy domain="resource" name="time" value="3600"/> -->
  <policy domain="delegate" rights="none" pattern="URL" />
  <policy domain="delegate" rights="none" pattern="HTTPS" />
  <policy domain="delegate" rights="none" pattern="HTTP" />
  <policy domain="path" rights="none" pattern="@*"/>
</policymap>

Nous voulons ajouter

`/etc/ImageMagick-6/policy.xml

<policymap>
  <policy domain="resource" name="time" value="5"/>
</policymap>

Conf Ansible

- name: install deps for ansible xml module
  apt: name='{{ packages }}'
  vars:
    packages:
      - python-lxml  # For Ansible xml
      - python3-lxml # For Ansible xml

- name: /etc/ImageMagick-6/policy.xml - change timeout
  xml:
    path: /tmp/policy.xml
    xpath: /policymap/policy[@domain='resource' and @name='time']
    attribute: value
    value: "5"
2025/03/24 15:06
blog.txt · Dernière modification : de 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki