Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Aller plus loin avec Python

APERTO-NOTA

Watchdog et Paramiko

🐶 Watchdog

Watchdog est une bibliothèque Python qui permet de surveiller les changements dans un répertoire ou un fichier en temps réel.

À quoi ça sert ?

🔐 Paramiko

Paramiko est une bibliothèque Python qui permet de se connecter à un serveur distant via SSH.

À quoi ça sert ?

Installation

pip install watchdog paramiko

Exercice

Solution to Exercise 1 #
import time
import paramiko
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os

# Configuration
remote_file_path = "/home/tempo/requirements.txt"
local_directory = "./"
local_file_path = os.path.join(local_directory, "toto.txt")
hostname = "aperto-nota.fr"
port = 22
username = "tempo"
password = "usertempo"

# Téléchargement du fichier via SSH
def telecharger_fichier():
    try:
        transport = paramiko.Transport((hostname, port))
        transport.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(transport)

        sftp.get(remote_file_path, local_file_path)

        sftp.close()
        transport.close()
        print("Fichier téléchargé avec succès.")
    except Exception as e:
        print(f"Erreur lors du téléchargement : {e}")

# Surveillance du fichier local
class SurveillanceHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if event.src_path == local_file_path:
            print(f"Le fichier {event.src_path} a été modifié.")

if __name__ == "__main__":
    telecharger_fichier()

    event_handler = SurveillanceHandler()
    observer = Observer()
    observer.schedule(event_handler, path=local_directory, recursive=False)
    observer.start()
    print("Surveillance du fichier en cours...")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()