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

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

Notes X11

Voir :

Voir aussi :

  • X Display Manager Control Protocol (XDMCP)
  • PipeWire
  • waypipe

Quel est mon gestionnaire de fenetres - what is my window manager running

sudo apt-get install wmctrl
wmctrl -m

Ou plus simplement

printf 'Desktop: %s\nSession: %s\n' "$XDG_CURRENT_DESKTOP" "$GDMSESSION"

Notes install X11 sur RedHat7

yum downgrade glibc glibc-common
yum downgrade plymouth --setopt=protected_multilib=false
 
yum -y groupinstall "X Window System" "Desktop" "Fonts" "General Purpose Desktop"
 
yum install gcc make kernel-headers kernel-devel
 
rpm -qa |grep kernel
uname -r
 
rpm -e kernel-3.10.0-327.28.3.el7.x86_64
 
mount /dev/cdrom /mnt/
./VBoxLinuxAdditions.run
 
#yum install bash-completion
 
systemctl status vboxadd
systemctl status vboxadd-service
systemctl status vboxadd-x11
 
#yum groupinstall 'X Window System' 'GNOME'
yum groupinstall 'Server with GUI'  --skip-broken --setopt=protected_multilib=false
yum downgrade dbus-libs avahi-libs dbus avahi-autoipd
yum groupinstall 'Server with GUI'  --skip-broken --setopt=protected_multilib=false
 
 
yum install open-vm-tools open-vm-tools-desktop
  1. Install xauth: sudo yum install xorg-x11-xauth
  2. Edit the /etc/ssh/sshd_config file, and enter the X11Forwarding variable in Yes.
  3. Restart the sshd service: sudo service sshd restart

WayPipe

Similar to ssh -X

waypipe ssh user@theserver weston-terminal
 
waypipe -c lz4=9 ssh remote-server application-binary

How to make xterm black background by default

Add to ~/.Xdefaults :

xterm*background: black
xterm*foreground: white

or

alias xterm='xterm -bg black -fg white'
2025/03/24 15:06

Wrapper to use su as sudo - Emulating sudo's behaviour with su

Ma proposition

sudo.sh

#!/bin/bash
 
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details
 
ARGS_STRING=''
 
add_arg() {
        ARGS_STRING="${ARGS_STRING} $*"
}
 
echo "!!! WARNING: Using a fake sudo command !!!" >&2
 
while [ "${1-}" != "" ]; do
        case $1 in
        -s)
                shift
                add_arg "-s $1"
                ;;
        -u)
                shift
                add_arg "-p $1"
                ;;
        --)     # End of all options
                shift
                break
                ;;
        *)
                add_arg -c
                add_arg "'$*'"
                shift
                break
                ;;
        esac
        shift
done
 
# echo su "${ARGS_STRING}"
eval su "${ARGS_STRING}"

Autres exemples

Exemple 1

su_wrapper() {
    su -s /bin/bash -c "$(printf "%q " "$@")"
}

ou

su_wrapper() {
    local IFS=' '
    su -c "$*"
}

Source : https://stackoverflow.com/questions/24340664/emulating-sudos-behaviour-with-su

Exemple 2

sudo-su

#! /bin/sh
set -e
 
# A wrapper around su and sudo to implement a basic sudo-style interface with
# su and a basic su-style interface with sudo.
# 
# This can be useful when using tools such as pdebuild(1) that integrate
# privilege escalation only with sudo, or only with su: by having it run
# this program instead, you actually use su, or sudo instead seemlessly.
#
# Copyright (C) Tanguy Ortolo <tanguy+sudo-su@ortolo.eu> 2011
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details. 
 
 
usage()
{
    rc=$1
    echo "Usage: sudo-su COMMAND" >&2
    echo "       su-sudo -c \"COMMAND\"" >&2
    echo "sudo-su uses su to implement a basic sudo-style interface" >&2
    echo "su-sudo uses sudo to implement a basic su-style interface" >&2
    exit $rc
}
 
fake_sudo()
{
    TEMP="$(getopt -s sh -o +h --long help -n "$0" -- "$@")"
    if [ "$?" != 0 ]
    then
        usage $?
    fi
    eval set -- "$TEMP"
    while [ "$1" != "--" ]
    do
        case "$1"
        in
            -h|--help) usage 0 ; shift ;;
        esac
    done
    shift
    if [ "$#" -eq 0 ]
    then
        echo "sudo-su requires a command" >&2
        usage 1
    fi
 
    command=""
    for arg in "$@"
    do
        # To represent single quotes from single-quote mode:
        # leave single-quote mode, enter double-quote mode, write the single quote,
        # leave double-quote mode, enter single-quote mode.
        arg="$(echo "$arg" | sed -e "s/'/'\"'\"'/g")"
        if [ -z "$command" ]
        then
            command="'$arg'"
        else
            command="$command '$arg'"
        fi
    done
 
    exec su -c "$command"
}
 
fake_su()
{
    TEMP="$(getopt -s sh -o hc: --long help,command: -n "$0" -- "$@")"
    if [ "$?" != 0 ]
    then
        usage $?
    fi
    eval set -- "$TEMP"
    while [ "$1" != "--" ]
    do
        case "$1"
        in
            -h|--help) usage 0 ; shift ;;
            -c|--command) command="$2" ; shift 2 ;;
        esac
    done
    shift
    if [ "$#" -ne 0 ]
    then
        echo "We take only a -c option, no argument, sorry" >&2
        usage 1
    fi
    if [ -z "$command" ]
    then
        echo "su-sudo requires a command" >&2
        usage 1
    fi
 
    exec sudo sh -c "$command"
}
 
 
case "$(basename $0)"
in
    sudo*) fake_sudo "$@" ;;
    su*) fake_su "$@" ;;
esac

Sources :

Autres

Proper usage of su :

su -c "$0" "$ZOO_USER" "$@"
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