Ankündigung

Einklappen
Keine Ankündigung bisher.

stop/start smarthome.service via .py script

Einklappen
X
 
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

    stop/start smarthome.service via .py script

    Hi,

    Ich habe meine VM soweit am Laufen mit 1.10 und Bookworm bzw. SV3.4. Danke nochmal an alle die mich dabei unterstützt haben.
    Eine Sache die ich noch realisieren möchte, ist ein regelmäßiges Backup meine smarthome.db.

    Dazu läuft aktuell eine .py via crontab einmal täglich (derzeit noch eine Dummy.db), dass die Datei auf eine NFS Freigabe kopiert.
    Sinnvollerweise sollte shng jedoch vorher gestoppt und danach wieder gestartet werden.
    'sudo systemctl stop smarthome.service' liefert aber eine Fehlermeldung wenn ich diesen in meine .py integriere.

    Kann mir dabei jemand helfen?


    Code:
    #!/usr/bin/env python
    
    from __future__ import print_function
    from __future__ import unicode_literals
    
    import sqlite3
    import shutil
    import time
    import os
    
    DESCRIPTION = """
                  Create a timestamped SQLite database backup, and
                  clean backups older than a defined number of days
                  """
    
    sudo systemctl stop smarthome.service
    print("smarthome stopped")
    
    # How old a file needs to be in order
    NO_OF_DAYS = 5
    
    
    def sqlite3_backup(dbfile, backupdir):
        """Create timestamped database copy"""
    
        if not os.path.isdir(backupdir):
            raise Exception("Backup directory does not exist: {}".format(backupdir))
    
        backup_file = os.path.join(backupdir, os.path.basename(dbfile) +
                                   time.strftime("_%Y-%m-%d"))
    
        connection = sqlite3.connect(dbfile)
        cursor = connection.cursor()
    
        # Lock database before making a backup
        cursor.execute('begin immediate')
        # Make new backup file
        shutil.copyfile(dbfile, backup_file)
        print("\nCreating {}".format(backup_file))
        # Unlock database
        connection.rollback()
    
    
    def clean_data(backup_dir):
        """Delete files older than NO_OF_DAYS days"""
    
        print("Cleaning up old backups")
        for filename in os.listdir(backup_dir):
            backup_file = os.path.join(backup_dir, filename)
            if os.path.isfile(backup_file):
                if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
                    os.remove(backup_file)
                    print("Deleting {}...".format(backup_file))
    #
    if __name__ == "__main__":
        db_file = "/usr/local/smarthome/var/db/smarthomeng____.db"
        backup_dir = "/mnt/FuxlHomeBackupDB"
        sqlite3_backup(db_file, backup_dir)
        clean_data(backup_dir)
    
        print("Backup update has been successful.")
    
    sudo systemctl start smarthome.service
    print("smarthome started")​
    Code:
    0 4 * * * /usr/bin/python3 /usr/local/smarthome/tools/BackupScript.py >> /usr/local/smarthome/var/log/smarthome-dbbackup.log 2>&1
    mfg
    Markus

    #2
    Du bist dabei Python Syntax und den Syntax der Linux Shell zu mischen. Du musst Dich schon für eines von beiden entscheiden.

    Entweder formulierst Du das ganze Skript als Bash Skript oder Du startest aus Deinem Python Skript eine (Bash)-Shell, in der Du den Service stoppst/startest.

    Schau mal hier und hier.
    Viele Grüße
    Martin

    There is no cloud. It's only someone else's computer.

    Kommentar


      #3
      Msinn Vielen Dank für den Hinweis. es läuft nun.

      Das Einzige was ich mich noch frage, ist ob es noch ein 'time.sleep' dazwischen braucht. zb. nach dem stoppen oder während dem Kopiervorgang?
      Oder wartet ab bis jeder einzelne Schritt abgeschlossen ist?

      P.S.: ist es eigentlich möglich noch zusätzlich eine Telegramm Message abzuschicken am ende des Scripts?
      Kann ich auf das Plugin zugreifen?


      Stop.sh
      Code:
      #!/bin/bash
      #Stop smarthome service
      sudo systemctl stop smarthome.service
      echo 'smarthome stopped'
      ​
      Start.sh
      Code:
      #!/bin/bash
      #Start smarthome service
      sudo systemctl start smarthome.service
      echo 'smarthome started'​
      ​
      Code:
      #!/usr/bin/env python
      
      from __future__ import print_function
      from __future__ import unicode_literals
      
      import sqlite3
      import shutil
      import time
      import os
      import subprocess
      
      DESCRIPTION = """
                    Create a timestamped SQLite database backup, and
                    clean backups older than a defined number of days
                    """
      
      #smarthome STOP
      subprocess.call("/usr/local/smarthome/tools/Stop.sh", shell=True)
      
      # How old a file needs to be in order
      NO_OF_DAYS = 4
      
      
      def sqlite3_backup(dbfile, backupdir):
          """Create timestamped database copy"""
      
          if not os.path.isdir(backupdir):
              raise Exception("Backup directory does not exist: {}".format(backupdir))
      
          backup_file = os.path.join(backupdir, os.path.basename(dbfile) +
                                     time.strftime("_%Y-%m-%d"))
      
          connection = sqlite3.connect(dbfile)
          cursor = connection.cursor()
      
          # Lock database before making a backup
          cursor.execute('begin immediate')
          # Make new backup file
          shutil.copyfile(dbfile, backup_file)
          print("\nCreating {}".format(backup_file))
          # Unlock database
          connection.rollback()
      
      
      def clean_data(backup_dir):
          """Delete files older than NO_OF_DAYS days"""
      
          print("Cleaning up old backups")
          for filename in os.listdir(backup_dir):
              backup_file = os.path.join(backup_dir, filename)
              if os.path.isfile(backup_file):
                  if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
                      os.remove(backup_file)
                      print("Deleting {}...".format(backup_file))
      #
      if __name__ == "__main__":
          db_file = "/usr/local/smarthome/var/db/smarthomeng____.db"
          backup_dir = "/mnt/FuxlHomeBackupDB"
          sqlite3_backup(db_file, backup_dir)
          clean_data(backup_dir)
      
          print("Backup update has been successful.")
      
      #smarthome START
      subprocess.call("/usr/local/smarthome/tools/Start.sh", shell=True)
      Zuletzt geändert von fuxl66; 13.02.2024, 13:29. Grund: P.S.:

      Kommentar


        #4
        Zitat von fuxl66 Beitrag anzeigen
        Das Einzige was ich mich noch frage, ist ob es noch ein 'time.sleep' dazwischen braucht. zb. nach dem stoppen oder während dem Kopiervorgang?
        Oder wartet ab bis jeder einzelne Schritt abgeschlossen ist?
        ​Hierzu ist die Python Doku Dein Freund. Dort ist subprocess beschrieben.


        Zitat von fuxl66 Beitrag anzeigen
        P.S.: ist es eigentlich möglich noch zusätzlich eine Telegramm Message abzuschicken am ende des Scripts?
        Kann ich auf das Plugin zugreifen?
        Dein Python Skript läuft außerhalb der SamrtHomeNG Umgebung und kann daher natürlich nicht auf SmartHomeNG "Innereien" (wie Plugins oder Items) zugreifen.
        Viele Grüße
        Martin

        There is no cloud. It's only someone else's computer.

        Kommentar

        Lädt...
        X