Outils pour utilisateurs

Outils du site


blog

Python - callback

Introduction

Exemple d'une fonction sans callback

#! /usr/bin/env python3
 
from functools import reduce
 
 
def calcfact(i):
    assert i >= 0
    return reduce(lambda a, b: a * b, range(1, i+1) if i > 1 else [1])
 
 
print(calcfact(3))

Exemple de la même fonction avec callback optionnel

#! /usr/bin/env python3
 
from functools import reduce
 
 
def calcfact_called(i, res):
    print(i, '! = ', res, sep='')
 
 
def calcfact(i, callback=None):
    assert i >= 0
    res = reduce(lambda a, b: a * b, range(1, i+1) if i > 1 else [1])
    if callback is None:
        return res
    else:
        callback(i, res)
 
# Sans Callback
print(calcfact(3))
 
# Avec Callback
calcfact(4, calcfact_called)

Exemple avec async / asyncio / await

#! /usr/bin/env python3
 
import asyncio
 
 
def waitplop_called(i):
    print(i)
 
 
async def waitplop(i, callback=None):
    await asyncio.sleep(i)
    if callback is None:
        return i
    else:
        callback(i)
 
 
async def main():
    async with asyncio.TaskGroup() as tg:
        # Asynchronous with callback
        tg.create_task(waitplop(3, waitplop_called))
        tg.create_task(waitplop(3, waitplop_called))
 
        # Synchronous / sequential without callback
        task1 = await tg.create_task(waitplop(4))
        print(task1)
 
 
asyncio.run(main())
$ time ./plop.py 
3
3
4

real    0m4.120s
user    0m0.095s
sys     0m0.024s
Autre façon de faire un callback avec asyncio

Voir :

#! /usr/bin/env python3
 
import asyncio
 
 
def waitplop_called(task):
    print(task.result())
 
 
async def waitplop(i):
    await asyncio.sleep(i)
    return i
 
 
async def main():
     task = asyncio.create_task(waitplop(3))
     task.add_done_callback(waitplop_called)
     await asyncio.gather(task)
 
 
asyncio.run(main())

Autres

Voir :

# Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
    functools.partial(print, "Future:"))
2025/03/24 15:06

pv Barre de progression pour pipe dd etc...

Source : http://askubuntu.com/questions/215505/how-do-you-monitor-the-progress-of-dd

dd possède l'option status=progress

apt-get install pv

sans pv

dd if=/dev/sdb of=DriveCopy1.dd bs=4096

Avec pv

dd if=/dev/sdb | pv -s 2G | dd of=DriveCopy1.dd bs=4096

Si dd écrit sur /dev/ : ne pas oublier le sync (ou utiliser l'option conv=fsync ou encore ddrescue -y)

sync

Autre

Voir également l'option status=progress à dd

Avec un niveau de compression adapté automatiquement

sudo dd if=/dev/sda | pv | zstd --adapt > image.dd.zst
zstdcat image.dd.zst | pv | sudo dd of=/dev/sda )
2025/03/24 15:06

Script effacer plusieurs fichiers, sauf les n derniers

Voir aussi logrotate

script

purge_keep_only_last_recent.sh

#! /bin/bash
set -o nounset
 
# Parametres
CHEMIN=~/backup/
 
# ADD 1; If KEEP_LAST=5 => Only 4 will be kept
KEEP_LAST=10
 
purge() {
        local FICHIER=$1
 
        NEWER_THAN=$(ls -1t $CHEMIN/$FICHIER | sed -ne "${KEEP_LAST}p")
 
        if [[ ! -z "$NEWER_THAN" ]]
        then
                find $CHEMIN -depth -maxdepth 1 -type f -not -newer $(ls -1t $CHEMIN/$FICHIER | sed -ne "${KEEP_LAST}p") -name "$FICHIER" -delete
        fi
}
 
 
purge 'information_schema-*.sql.gz'
purge 'mysql-*.sql.gz'
purge 'performance_schema-*.sql.gz'
purge 'zabbix-*.sql.gz'

Notes sur "-delete" de find

-delete Effacer les fichiers, et renvoyer vrai si l'effacement a réussi. Si l'effacement échoue, un message d'erreur est envoyé. Si -delete échoue, le statut de sortie de find sera différent de zéro (si jamais il s'interrompt). L'utilisation de l'action -delete active automatiquement l'option -depth.

Attention : N'oubliez pas que la ligne de commande de find est évaluée
comme une expression. Écrire -delete en premier forcera find à essayer d'effacer tout ce qui se trouve dans les points de départ que vous avez indiqué. Lorsque vous testez une ligne de commande de find qui utilisera -delete, vous devriez préciser l'option -depth afin d'éviter les sur‐ prises plus tard. Puisque -delete entraîne -depth, vous ne pouvez pas utiliser en même temps -prune et -delete.

Source : man find

2025/03/24 15:06

Proxy et apt-get

Pour définir une conf spécifique à apt-get (Adaptez et dé-commenter les lignes voulu)

/etc/apt/apt.conf.d/02proxy

#Acquire::http::Proxy "false";
#Acquire::ftp::Proxy "false";

#Acquire::http::Proxy "http://10.9.3.100:3128";
#Acquire::http::Proxy "http://utilisateur:motdepasse@example.com:port";

Mais nous préférerons à la place définir la conf avec les variables d’environnement

/etc/environment

# http_proxy=http://10.9.3.100:3128
# https_proxy=http://10.9.3.100:3128
ALL_PROXY=http://10.9.3.100:3128
NO_PROXY="localhost,127.0.0.1,.lan"

Notes : /etc/environment s'applique à tous les utilisateurs, à la place on peut utiliser le bashrc.

http_proxy=http://10.9.3.100:3128 apt-get update && apt-get upgrade -y
2025/03/24 15:06

Protéger l’accès à vos applications web grâce à un mot de passe à usage unique OTP

Pour se faire nous utiliserons :

Un logiciel pour vous identifier en générant un mot de passe jetable. Sous Android :

  • andOTP
  • flauth
  • mOTP
  • SecureOTP
apt-get install python3-pip
adduser --group --system --disabled-password --home /opt/auth-otp app-otp
su - app-otp -s /bin/bash
python3 -m pip install --user pyotp
git clone https://github.com/newhouseb/simpleotp
cd simpleotp

main.py

-PORT = 8000
+PORT = 8001
-httpd = socketserver.TCPServer(("", PORT), AuthHandler)
+httpd = socketserver.TCPServer(("127.0.0.1", PORT), AuthHandler)

Après il faut lancer le script Python dans un tmux ou avec Systemd ou encore supervisord.

python3 main.py
python3 -c "import pyotp; print(pyotp.random_base32())" > .totp_secret
chmod 600 .totp_secret

Cong Nginx

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name cockpit.acme.fr;
 
    location /auth {                                                                                                                                                    
            proxy_pass http://127.0.0.1:8001; # This is the TOTP Server                                                                                                 
            proxy_set_header X-Original-URI $request_uri;                                                                                                               
    }                                                                                                                                                                   
 
    # This ensures that if the TOTP server returns 401 we redirect to login                                                                                             
    error_page 401 = @error401;                                                                                                                                         
    location @error401 {                                                                                                                                                
        return 302 /auth/login;                                                                                                                                         
    }                                                                                                                                                                                                                                                                                                                                        
 
    location / {                                                                                                                                                        
        auth_request /auth/check;                                                                                                                                       
 
        # Required to proxy the connection to Cockpit                                                                                                                   
        proxy_pass https://127.0.0.1:9090;                                                                                                                              
        proxy_set_header Host $host;                                                                                                                                    
        proxy_set_header X-Forwarded-Proto $scheme;                                                                                                                     
 
        # Required for web sockets to function                                                                                                                          
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
 
        # Pass ETag header from Cockpit to clients.
        # See: https://github.com/cockpit-project/cockpit/issues/5239
        gzip off;
    }
 
    ssl_certificate /etc/letsencrypt/live/cockpit.acme.fr/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/cockpit.acme.fr/privkey.pem; # managed by Certbot
}
 
server {
    if ($host = cockpit.acme.fr) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
 
 
    listen         80;
    server_name    cockpit.acme.fr;
    return 404; # managed by Certbot
 
 
}

Conf andOTP

Créer un “details” de type “TOTP”, dans “secret”, saisissez le contenu du fichier .totp_secret

Service SystemD

/etc/systemd/system/simple-otp.service

[Unit]
Description=Simple OTP
Wants=network.target
After=network.target nginx.service
 
[Service]
WorkingDirectory=/opt/auth-otp/simpleotp
ExecStart=/usr/bin/python3 /opt/auth-otp/simpleotp/main.py
User=app-otp
Restart=always
 
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start simple-otp
systemctl status simple-otp
systemctl enable simple-otp
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