Scheduled Backup

Auflistung von gewünschten Features, Ausschreibung zur Umsetzung
Benutzeravatar
mrinas
Beiträge: 1900
Registriert: Mi Jan 29, 2020 10:12 pm

Re: Scheduled Backup

Beitrag von mrinas »

Hm, password support ist aktuell nicht vorhanden, sollte im Grunde kein grosses Thema sein, vielleicht komm ich hwute abend mal dazu das anzuschauen.
15,2kWp SMA (SB4000TL-21, SB3.0, STP6.0-SE + BYD HVS, EnergyMeter), openWB Standard+, openWB Pro, Peugeot e2008, Tesla Model Y LR.
Benutzeravatar
mrinas
Beiträge: 1900
Registriert: Mi Jan 29, 2020 10:12 pm

Re: Scheduled Backup

Beitrag von mrinas »

burningbecks hat geschrieben: So Jan 30, 2022 3:40 pm Frage zum Windows PowerShell Script von mrinas:
Hat das schonmal irgendjemand mit Username und Passwort zum Laufen gebracht? :?:
Wenn Du magst solltest Du mit diesen paar Codezeilen weiterkommen:

in der #region variable definition, z.b. bei den anderen Variablen ab Zeile 134 dies hier ergänzen und das die eigenen Zugangsdaten anpassen:

Code: Alles auswählen

$user = "admin"
$pw = "password"
$secpasswd = ConvertTo-SecureString $pw -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
Und dann überall wo Invoke-WebRequest aufgerufen wird (Zeilen 197, 212) den Aufruf um

Code: Alles auswählen

-Credential $creds
ergänzen:

Code: Alles auswählen

$Result = Invoke-WebRequest -uri $URIToCall -UseBasicParsing -Credential $creds #create backup
Invoke-WebRequest -Uri $BackupURI -OutFile $LocalBackupPath -Credential $creds # Download backup and store locally
Eine saubere Implementation ist dann nochmal etwas aufwändiger. So spontan fällt mir das hier mal ein: herausfinden ob Auth benötigt wird, Zugangsdaten abfragen und sicher speichern, beim Aufruf Creds einlesen und anwenden, Fehlerbehandlung.

Hoffe dass das so schon mal hilft!
15,2kWp SMA (SB4000TL-21, SB3.0, STP6.0-SE + BYD HVS, EnergyMeter), openWB Standard+, openWB Pro, Peugeot e2008, Tesla Model Y LR.
Benutzeravatar
mrinas
Beiträge: 1900
Registriert: Mi Jan 29, 2020 10:12 pm

Re: Scheduled Backup

Beitrag von mrinas »

philipp123 hat geschrieben: Sa Jan 29, 2022 2:58 pm Mir ist gerade meine SD-Karte abgeraucht. Backup hatte ich ja dank diesem Skript. Danke dafür!

Ein Thema ist mir dabei aufgefallen. Ich habe das Problem bemerkt, dass bei mir die Tagesgraphen nicht mehr 24h gingen. Erst im Nachgang ist mir aufgefallen, dass seit 2 Tagen bei mir die Backups kleiner statt größer wurden. Und hier jetzt meine Idee. Wäre es möglich, auf der Synology zusätzlich zum Backup auch abzufragen, ob das Backup größer als das vom Vortag ist. Wenn kleiner schicke eine Alarmmeldung? Dann könnte man schneller auf eine abrauchende SD-Karte reagieren.
Klassisches Problem, kenne ich noch aus einem früheren Leben - das Sicherung ist nie das Problem, sondern stets die Wiederherstellung.

Die Idee nach einer Plausibilitätsprüfung des Backups finde ich durchaus gut, würde hier empfehlen schlicht auf ungleiche Dateigröße zu vergleichen. Ein Backup welches aufs Bit genau gleich groß ist, ist suspekt. Abweichungen nach oben und unten sind zu erwarten.
15,2kWp SMA (SB4000TL-21, SB3.0, STP6.0-SE + BYD HVS, EnergyMeter), openWB Standard+, openWB Pro, Peugeot e2008, Tesla Model Y LR.
philipp123
Beiträge: 1032
Registriert: Mi Jul 21, 2021 3:00 pm

Re: Scheduled Backup

Beitrag von philipp123 »

mrinas hat geschrieben: Mo Jan 31, 2022 11:04 am Abweichungen nach oben und unten sind zu erwarten.
Die Abweichungen gab es auch während des Crashs, nur halt immer nach unten und die Archive waren korrupt.
LP1: openWB series2 custom mit Phasenumschaltung
LP2: go-e V2
Kostal Plenticore Plus
e-up BJ 2021, SOC mit OVMS
EQB 250 BJ 2023, SOC mit Mercedes ME über Home Assistant
EVU mit Tasmato-Lesekopf auf SmartMeter
9 x Smarthome mit Shellys
burningbecks
Beiträge: 29
Registriert: Mo Nov 09, 2020 5:41 pm
Kontaktdaten:

Re: Scheduled Backup

Beitrag von burningbecks »

mrinas hat geschrieben: Mo Jan 31, 2022 10:50 amWenn Du magst solltest Du mit diesen paar Codezeilen weiterkommen:
...
Jau, damit läuft's. Danke :!:

Musste allerdings das "exit" nach "Backupjob $BackupTaskName already exists, nothing to do" usw. rausnehmen. Sonst kam es nicht zum Backup.
Jedenfalls nicht, wenn ich's probehalber per Batch-Datei mit

Code: Alles auswählen

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass D:\BACKUP\OpenWB\Get-OpenWBBackup.ps1 -OpenWBIP 192.xxx.yyy.zzz
starte.

Sieht jetzt bei mir jetzt so aus:

Code: Alles auswählen

# openWB Scheduled Backup by mrinas
# https://openwb.de/forum/viewtopic.php?p=35525#p35525
# https://github.com/snaptec/openWB/wiki/Backup-(Sicherung)-einer-openWB---manuell-oder-automatisch
# ENTER USERNAME IN LINE 138 and PASSWORD IN LINE 139 !!
  
<#
  .SYNOPSIS
  Creates ad-hoc and scheduled backup of openWB wallbox.
  .DESCRIPTION
    This script will create a backup of the openWB wallbox and store the backup in a folder while keeping older versions. The script can also register a scheduled task to automate the backup creation. 
    Starting the script without any parameters will 1) ask for the IP of the openWB, 2) check if a scheduled task already exists. A new task will be registered if needed and an immediate backup will be created. Script will not perform any action if backup job already exists. 
    Start script with -RunOnce parameter to perform an immediate backup without creating the scheduled task.
  .PARAMETER LocalBackupFolder
  Specifies local path to store backups. Defaults to script location
  .PARAMETER OpenWBIP
  IP of openWB, required parameter.
  .PARAMETER VerboseLogFileName
  Logfile for Verbose output, defaults to VerboseOutput.Log if not specified
  .PARAMETER AppendToLogfile
  Appends to existing verbose log file, defaults to override.
  .PARAMETER RunOnce
  Execute backup directly, skip creation of scheduled task.
    .EXAMPLE
  PS> .\Get-OpenWBBackup.ps1
  Checks for scheduled task, creates one if it doesn't exist already. openWB backup will be executed every 4 weeks, Monday at 09:00 local time. Reruns if time is missed. After creating the task an immediate backup is created. 
  Skips all actions if a scheduled task already exists.
  .EXAMPLE
  PS> .\Get-OpenWBBackup.ps1 -OpenWBIP 192.168.178.200 -RunOnce
  Performs an immediate backup of OpenWB 192.168.178.200 and skips creation of scheduled task.
  
  .NOTES
  MIT License
  Copyright (c) 2021 Martin Rinas
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
#>
[CmdletBinding()] #few examples how a script accepts input parameters
param
(
    [Parameter(Mandatory=$false)]
    [ValidateScript({Test-Path $_ })]
    [string]$LocalBackupFolder,
    [Parameter(Mandatory=$true,HelpMessage="Please enter IP of openWB")]
    [string]$OpenWBIP,
    [Parameter(Mandatory=$false)]
    [string] $VerboseLogFileName = 'VerboseOutput.Log',
    [switch]$AppendToLogfile,
    [switch]$RunOnce
)



#region function definition
function Write-VerboseLog{
    <#
        .SYNOPSIS
        Writes messages to Verbose output and Verbose log file
        .DESCRIPTION
        This fuction will direct verbose output to the console if the -Verbose 
        paramerter is specified.  It will also write output to the Verboselog.
        .EXAMPLE
        Write-VerboseLog -Message 'This is a single verbose message'
        .EXAMPLE
        # Write-VerboseLog -Message ('This is a more complex version where we want to include the value of a variable: {0}' -f ($MyVariable | Out-String) )
    #>
    param(
      [String]$Message  
    )
  
    $VerboseMessage = ('{0} Line:{1} {2}' -f (Get-Date), $MyInvocation.ScriptLineNumber, $Message)
    Write-Verbose -Message $VerboseMessage
    Add-Content -Path $VerboseLogFileName -Value $VerboseMessage
  }
function Register-OpenWBBackupTask
{
    param
    (
        [Parameter(Mandatory=$true,HelpMessage='Full path to the backup script')]
        [ValidateScript({Test-Path $_ })]
        [String]$ScriptPath,
        [Parameter(Mandatory=$true,HelpMessage='Name of backuptask')]
        [string]$TaskName,
        [Parameter(Mandatory=$true,HelpMessage='IP of OpenWB')]
        [string]$IPAddr

    )
    try 
    {
        $null = Get-ScheduledTask -TaskName $TaskName -ErrorAction stop
        Write-VerboseLog -Message ('Scheduled Task: {0} does already exist. Please delete first if you want to re-create' -f ($TaskName | Out-String) )
        Write-Error "Task $TaskName already exists. Will not re-create, please delete manually in Task Scheduler if you want to re-create. Exiting."
        break
    }
    catch 
    {
        # Scheduled Task does not exist. Creating.
        Write-VerboseLog -Message ('Scheduled task: {0} does not exist, creating.'-f ($TaskName | Out-String) )
        $WorkingDir = Split-Path $ScriptPath -Parent
        Write-VerboseLog -Message ('Setting Working directory to: {0}' -f($WorkingDir | out-string))
        $Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-ExecutionPolicy Bypass -File  `"$ScriptPath`" -RunOnce -openWBIP $IPAddr" -WorkingDirectory $WorkingDir
        $Trigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 4 -At '09:00' -DaysOfWeek Monday
        $Principal = New-ScheduledTaskPrincipal -LogonType Interactive -Id Author -UserId $env:USERNAME -RunLevel Limited -ProcessTokenSidType Default
        $Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Hours 1) -StartWhenAvailable -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries
        $ScheduledTask = New-ScheduledTask -Action $Action -Principal $Principal -Settings $Settings -Trigger $Trigger -Description 'OpenWB BackupJob'
        Register-ScheduledTask $TaskName -InputObject $ScheduledTask -ErrorAction Stop
    }

}

#endregion

#region variable definition
if ([string]::IsNullOrEmpty($LocalBackupFolder))
{
    $LocalBackupFolder = (Split-path $MyInvocation.MyCommand.Path -parent)
    Write-VerboseLog -Message ('LocalBackupFolder was empty, set to {0}' -f ($LocalBackupFolder))
}

if([string]::IsNullOrEmpty($ScriptLocation))
{
    $ScriptLocation = (Split-path $MyInvocation.MyCommand.Path -parent)
    Write-VerboseLog -Message ('ScriptLocation was empty, set to {0}' -f ($ScriptLocation))
}

$user = "yourusernamehere"
$pw = "yourpasswordhere"
$secpasswd = ConvertTo-SecureString $pw -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$LocalBackupFileName = ("OpenWB-backup-" + (get-date -format u) + ".tar.gz").Replace(":","-")
$LocalBackupPath = $LocalBackupFolder + '\' + $LocalBackupFileName
$OpenWBBackupPath = '/openWB/web/settings/backup.php'
$URIToCall = "http://" + $OpenWBIP + $OpenWBBackupPath
$BackupTaskName = 'openWB Backup'
$ScriptName = $MyInvocation.MyCommand

#endregion

#region main script
if (!$AppendToLogfile)
{
    $null = New-Item -Path $VerboseLogFileName -ItemType File -Force
    Write-VerboseLog -Message 'Script started'
    Write-VerboseLog -Message ('Parameters: {0}' -f ($MyInvocation | Out-String) )
}
else 
{
    Write-VerboseLog -Message 'Script started, appending to existing log'
}

if ($RunOnce)
{
    Write-VerboseLog 'Skip scheduled task and executy directly'
}
else
{
    # check for and create scheduled task
    Write-VerboseLog -message ('Checking for existence of scheduled task: {0} and creating if needed. ' -f ($BackupTaskName) )
    
    try 
    {
        $null = Get-ScheduledTask -TaskName $BackupTaskName -ErrorAction stop
        Write-VerboseLog -Message ('Scheduled Task: {0} does already exist. ' -f ($BackupTaskName) )
        $BackupTaskExists = $True
    }
    catch 
    {
        Write-VerboseLog -Message ('Scheduled Task: {0} does not exist. ' -f ($BackupTaskName) )
        $BackupTaskExists = $False
    }

    if ($BackupTaskExists)
    {
        Write-VerboseLog -Message ('nothing to do.' -f ($BackupTaskName) )
        Write-Host "Backupjob $BackupTaskName already exists, nothing to do. Skipping..."
        #exit
    }
    else
    {
        Write-VerboseLog -Message ('BackupTask: {0} does not already exist, creating.' -f ($BackupTaskName) )    
        Write-Host "Creating scheduled backup task for openWB"
        $FullScriptPath = $ScriptLocation + '\' + $ScriptName
        Write-VerboseLog -Message ('Full script location: {0}' -f ($FullScriptPath| Out-String))
        Register-OpenWBBackupTask -TaskName $BackupTaskName -ScriptPath $FullScriptPath -IPAddr $OpenWBIP
        Write-Host "Creating one backup immediately."
    }
}

Write-VerboseLog -Message ('Using this as backup path to store file: {0}' -f ($LocalBackupPath | Out-String) )

Write-Host "Starting backup of openWB"
Write-VerboseLog -Message ('Triggering openWB backup creation by calling: {0}' -f ($URIToCall | Out-String) )
$Result = Invoke-WebRequest -uri $URIToCall -UseBasicParsing -Credential $creds  #create backup

if ($Result.StatusCode -eq '200') # New backup created?
{
    try 
    {
        #$OpenWBBackupDownloadPath = '/openWB/web/backup/backup.tar.gz' # We could also use $Result.Links.href to dynamically fetch location if we wanted to. Does require extra handling if more than one link is provided
        if ($Result.Links.Count -gt 1)
        {
            Write-VerboseLog -Message ('More than one link found in response: {0}' -f ($result.links | Out-String) )
            throw "More than one link found in response, cannot proceed."
        }
        $OpenWBBackupDownloadPath = $Result.Links.href
        $BackupURI = "http://" + $OpenWBIP + $OpenWBBackupDownloadPath
        Write-VerboseLog -Message ( 'Backup generated, downloading from: {0} to : {1}' -f ($BackupURI | Out-String), ($LocalBackupPath | Out-String) )
        Invoke-WebRequest -Uri $BackupURI -OutFile $LocalBackupPath -Credential $creds # Downlaod backup and store locally
        Write-Host "Created backup at $LocalBackupPath" # we're done here
        Write-VerboseLog -Message 'Download completed.'
    }  
    catch 
    {
        Write-VerboseLog 'Backup created bout could not be downloaded'
        Write-Host "Backup created but couldn't be downloaded." 
    }
}
else 
{
    Write-VerboseLog -Message ( 'Unexpected return code when asking for backup: {0} {1}' -f ($result.StatusCode | Out-String), ($Result.StatusDescription | Out-String ) )
    Write-Host 'Unexpected return code when asking for backup:' ($Result.StatusCode) ($Result.StatusDescription)   
}
#endregion
Modifikationen meinerseits in Zeile 187/188 davon.
BMW i3s, go-eCharger Gemini (22kW FIX).
openWB Standalone + EVU Kit v2 MID als Lastmanager.
Benutzeravatar
mrinas
Beiträge: 1900
Registriert: Mi Jan 29, 2020 10:12 pm

Re: Scheduled Backup

Beitrag von mrinas »

burningbecks hat geschrieben: Mo Jan 31, 2022 8:21 pm Musste allerdings das "exit" nach "Backupjob $BackupTaskName already exists, nothing to do" usw. rausnehmen. Sonst kam es nicht zum Backup.
Jedenfalls nicht, wenn ich's probehalber per Batch-Datei mit

Code: Alles auswählen

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass D:\BACKUP\OpenWB\Get-OpenWBBackup.ps1 -OpenWBIP 192.xxx.yyy.zzz
starte.
Ja, das ist das erwartete Verhalten. Um das Backup tatsächlich auszuführen muss der Parameter -RunOnce mitgegeben werden. So ist auch der geplante Task angelegt.

Hintergrund ist folgender: Ich wollte die Nutzung so einfach wie möglich gestalten: Skript herunterladen, einmal ausführen, von da an läuft alles automatisch.

Ein Aufruf ohne 'RunOnce' prüft ob der geplante Task exisiert und registriert diesen. Der Parameter RunOnce sorgt dafür dass diese Prüfung nicht durchgeführt wird sondern sofort das Backup gestartet wird.
15,2kWp SMA (SB4000TL-21, SB3.0, STP6.0-SE + BYD HVS, EnergyMeter), openWB Standard+, openWB Pro, Peugeot e2008, Tesla Model Y LR.
burningbecks
Beiträge: 29
Registriert: Mo Nov 09, 2020 5:41 pm
Kontaktdaten:

Re: Scheduled Backup

Beitrag von burningbecks »

Alles klar - dann sollten Andere (die nicht in deinem Code herumpfuschen :mrgreen: ) ja kein Problem haben.

Hab' selbst Null Erfahrung mit PowerShell und dem ganzen -ExecutionPolicy Bypass Kram.
Einfache Batch-Dateien und den Taskplaner manuell bedienen krieg' ich gerade noch so hin. Und da hat's dann ja anscheinend den Unterschied zwischen Aufruf von Hand und deinem Automatismus gegeben.

Ziehe das nachher mal gerade.
...und dann bin ich gespannt, ob nächsten Monat alles wie von Geisterhand automatisch erscheint. ^^
BMW i3s, go-eCharger Gemini (22kW FIX).
openWB Standalone + EVU Kit v2 MID als Lastmanager.
Benutzeravatar
mrinas
Beiträge: 1900
Registriert: Mi Jan 29, 2020 10:12 pm

Re: Scheduled Backup

Beitrag von mrinas »

Ja, so gehts ja vielen dass man sich damit nicht auskennt, und häufig ja auch nicht muss.

Die Grundidee an meinem Skript hier ist wirklich dass man das nur einmal manuell aufruft und dann nichts mehr machen muss. Backup findet dann automatisch immer zum 1. des Monats statt, wobei verpasste Ausführungen zum nächstmöglichen Termin wiederholt werden. z.b. weil der Rechner aus war.
15,2kWp SMA (SB4000TL-21, SB3.0, STP6.0-SE + BYD HVS, EnergyMeter), openWB Standard+, openWB Pro, Peugeot e2008, Tesla Model Y LR.
Mafaldo
Beiträge: 141
Registriert: Sa Okt 03, 2020 4:48 pm

Re: Scheduled Backup

Beitrag von Mafaldo »

mrinas hat geschrieben: Fr Feb 04, 2022 9:51 am Ja, so gehts ja vielen dass man sich damit nicht auskennt, und häufig ja auch nicht muss.
yep, da steh ich grad im Regen. Wenn ich es von der Aufgabenplanung starte kommt kurz die PowerShell
und der Schriftzug "Starting backup openwb" erscheint, dann ist die Shell wieder weg.
Auch das automatische läuft so ab.

Das Log:

Code: Alles auswählen

PS C:\WINDOWS\system32> c:\util\owb_Backup\Get-OpenWBBackup.ps1

Cmdlet Get-OpenWBBackup.ps1 an der Befehlspipelineposition 1                                                            Geben Sie Werte für die folgenden Parameter an:                                                                         (Geben Sie !? ein, um Hilfe zu erhalten.)                                                                               OpenWBIP: 192.168.178.109                                                                                               Creating scheduled backup task for openWB

TaskPath                                       TaskName                          State
--------                                       --------                          -----
\                                              openWB Backup                     Ready
Creating one backup immediately.
Starting backup of openWB
Created backup at C:\util\owb_Backup\OpenWB-backup-2022-02-24 22-22-25Z.tar.gz

Starte ich das script direkt in der Shell mit Parameter -RunOnce läuft es sauber durch.
Ich weiß nicht wo das zweite http herkommt, liegt hier vielleicht der Fehler?
Bei den policies hatte ich für die Ausführung lokaler scripte schon bypass eingestellt.
Zuletzt geändert von Mafaldo am Do Feb 24, 2022 9:35 pm, insgesamt 2-mal geändert.
openWB Standard 2.0 - Zoe R240 12/16 - 18 kWp auf dem Dach, Plenticore Plus, Pico IQ, KSEM
Benutzeravatar
mrinas
Beiträge: 1900
Registriert: Mi Jan 29, 2020 10:12 pm

Re: Scheduled Backup

Beitrag von mrinas »

Ah ja, freut mich direkt dass mein Logging hilft den Fehler zu finden.

Du hast dem Script die gesamte Adresse der openWB, mit samt http:// mitgegeben, gefragt war eigentlich nur die IP-Adresse ohne http:// - Das führt nun dazu dass beim Backup die Adresse ungültig ist:

Code: Alles auswählen

BoundParameters       : {[RunOnce, True], [OpenWBIP, http://192.168.178.xxx]}
24.02.2022 19:07:03 Line:196 Triggering openWB backup creation by calling: http://http://192.168.178.109/openWB/web/settings/backup.php
Lösch' den geplanten Task bitte und ruf' das Script erneut auf, diesmal nur die IP (192.168.178.xxx) mitgeben, ohne http:// - Dann sollte das laufen.

Und ich hab' eine Hausaufgabe, die Eingabe überprüfen um beide Fälle sauber zu regeln.
15,2kWp SMA (SB4000TL-21, SB3.0, STP6.0-SE + BYD HVS, EnergyMeter), openWB Standard+, openWB Pro, Peugeot e2008, Tesla Model Y LR.
Antworten