Aller au contenu
Nikko

Backup Via Scene Lua

Recommended Posts

@pepite: sous Windows (10 en tout cas mais à mon avis depuis bien longtemps), tu peux aussi le faire en ligne de commande avec certutil:

 

  • Tu écris le couple login:pass sous un fichier infile.txt, mais sans espace ou CR à la fin
  • Depuis un shell, dans le même répertoire que infile.txt: certutil -encode infile.txt outfile.txt
  • Tu as ton ensemble en base 64 dans outfile.txt

Et bien sûr le résultat est le même quel que soit l'OS:

 

certutil_03.pngbase64_linux.png

 

 

Bref des méthodes il en existe des tas ;-)

 

 

 

  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

Nickel. vous ètes trop forts. merci nikko pour les 2 scènes de backup et merci pepite pour la scène d'encodage. :13:

Partager ce message


Lien à poster
Partager sur d’autres sites

petite, j'ai copié collé ton code dans un scene, mais dans le debug j'ai rien ?

le print m'affiche rien. comprends pas

Partager ce message


Lien à poster
Partager sur d’autres sites

bon j'ai fait comme cela et j'arrive a récupérer le mdp

local test = enc('login:pwd')
fibaro:debug(test)

 

Partager ce message


Lien à poster
Partager sur d’autres sites

bon j'ai fait comme cela et j'arrive a récupérer le mdp

local test = enc('login:pwd')
fibaro:debug(test)

 

Modifié par Sakkhho

Partager ce message


Lien à poster
Partager sur d’autres sites

oui ca fonctionne bien, c'était le "print" qui marchait pas  chez moi

 

Partager ce message


Lien à poster
Partager sur d’autres sites

Y'a moyen de backuper sur un share réseau? Qui pourrait m'aiguiller sachant que j'ai les accès adéquats nécessaires...

Partager ce message


Lien à poster
Partager sur d’autres sites

Venant de basculer sur le dernier frimware, merci pour cette correction.

Mise en place, tester, et fonctionnel

Super boulot, comme toujours

 

Partager ce message


Lien à poster
Partager sur d’autres sites
Y'a moyen de backuper sur un share réseau? Qui pourrait m'aiguiller sachant que j'ai les accès adéquats nécessaires...

Oui je pense que cela est possible

Envoyé de mon SM-G901F en utilisant Tapatalk

Partager ce message


Lien à poster
Partager sur d’autres sites

Question ?

Y a t'il une utilité de garder les backups liés à des versions de firm ancien.

Si un recovery est nécéssaire, on part de la 4.31 initiale ( Clé) puis il va nous proposer de se mettre a jour

directement sur la dernière stable ou en passant  par les stables intermédiaires ?

Apres cette mise à jour sur la dernière stable seul les backups compatibles seront utiles, les vieux, compatibles avec des versions antérieures peuvent être supprimés ?

Je n'ai jamais fait je préfère me renseigner avant.

 

Modifié par henri-allauch

Partager ce message


Lien à poster
Partager sur d’autres sites

Oui je pense que cela est possible

Envoyé de mon SM-G901F en utilisant Tapatalk


Une piste? Je sèche et je suis conscient qu'on peut pas trop partager ouvertement sur ce point sur le forum... en MP peut-être?

Partager ce message


Lien à poster
Partager sur d’autres sites

Après MAJ en 4.110 j'avais oublie dé mettre à jour Backup et DeleteBackup ;-)

Encore merci @Nikko

Partager ce message


Lien à poster
Partager sur d’autres sites

Bonsoir, que devons nous changer pour que sa fonctionne de nouveau en vers 4.114

Fonctionne plus depuis la .110 je crois?

Merci

Envoyé de mon SM-G920W8 en utilisant Tapatalk

Partager ce message


Lien à poster
Partager sur d’autres sites

Bonjour,

 

je vous relance pour le Delete, je ne suis pas sur de bien comprendre ce que je dois mettre dans ma scène pour que sa fonctionne, je suis rendu en version 4.131B

 

Merci de votre aide et bonne journée,

Partager ce message


Lien à poster
Partager sur d’autres sites

Salut @Plap3014

 

Voila la scène de backup fonctionnelle pour moi, suite aux modifications de nikko, il faut que tu encode ton couple login@toto.fr:motdepasse en base 64, regarde dans un des posts, il y'a le code pour le faire

--[[
%% properties
%% events
%% globals
--]]
-- BACKUP
-- ID des mobiles,tablettes pour notification
local portable = {} -- {XX, XX}
 
-- Message Descriptif du Backup
local descriptif = 'Backup HC2 du '..os.date("%d/%m/%y - %HH%M")
-- Password admin encodé en base64
local password = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
 
function sendPush(message)
    if #portable > 0 then
        for _,v in ipairs(portable) do
            fibaro:call(v,'sendPush', message)
        end
    end
end
--[[function sendPush(message)
    if #portable > 0 then
            fibaro:setGlobal('FreeSms', message)
    end
end]]--
 
local url = 'http://127.0.0.1/api/service/backups'
local datas = '{"action":"create","params":{"name":"'..descriptif..'"}}'
local httpClient = net.HTTPClient()
httpClient:request(url , {
        success = function(response)
                    if tonumber(response.status) == 201 or tonumber(response.status) == 202 then
                        print("Backup Created at " .. os.date())
                        sendPush(descriptif .. ' effectué')
                    else
                        print("Error " .. response.status)
                        sendPush('Erreur lors de la création du Backup')
                    end
                end,
        error = function(err)
                    print('error = ' .. err)
                end,
        options = {
                method = 'POST',
                headers = {
                        ["content-type"] = 'application/json',
                        ["Authorization"] = 'Basic '..password
                          },
                data = datas
            }
});

 

Partager ce message


Lien à poster
Partager sur d’autres sites

Merci,

 

mais le backup fonctionne bien chez moi, c'est le delete qui fonctionne plus, as-tu quelque chose?

 


Envoyé de mon SM-G920W8 en utilisant Tapatalk
 

Modifié par Plap3014

Partager ce message


Lien à poster
Partager sur d’autres sites

Salut @Plap3014

 

Pardon, je n'avais pas bien suivi ;-)

 

J'ai aussi et fonctionnel

--[[
%% properties
%% events
%% globals
--]]
 
--DELETE BACKUP
-- Flag dryrun; Si true, la requete sur api pour effacer le backup n'est pas effectuée
local dryrun = false
 
-- Password admin encodé en base64
local password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
function sortBackup(data)
    local backups = json.decode(data)
    -- Vérification de présence Backup
    if (backups and type(backups == 'table') and #backups > 0) then
        if #backups > 1 then print(#backups .. ' Backups présents') else print('1 Backup présent') end
    
        for i in ipairs(backups) do
            fibaro:debug('ID: '..backups[i]['id']..' | TIMESTAMP: '..backups[i]['timestamp']..' | DESCRIPTION: '..backups[i]['description'])
        end
    else
        print('Pas de backup ou erreur lors de la récupération de la liste')
        fibaro:abort()
    end
    
    -- Pour chaque Backup on stock le timestamp de la date de réalisation dans une table
    -- On classe ensuite les timestamps par ordre croissant
    local timestamp = {}
    for i in ipairs(backups) do
        table.insert(timestamp, backups[i]['timestamp'])
    end
    table.sort(timestamp)

    -- Le 1er timestamp de la table est le plus petit donc le plus ancien en epochtime
    -- Dans la table de backup on recherche le backup ayant ce timestamp
    local id = false
    for i in ipairs(backups) do
        if (tonumber(backups[i]['timestamp']) == tonumber(timestamp[1])) then id = backups[i]['id'] end
    end
    if id then 
        print("ID du backup le plus ancien: "..id) 
        deleteBackup(id)
    else
        print("Erreur lors de la récupération de l'ID")
        fibaro:abort()
    end
end
function deleteBackup(id)
    -- Requete via API pour effacer le backup le plus ancien
    if (not dryrun) and (id) then
        print('Effacement du backup '..id..' en cours. Cela peut prendre 30s')
        local url = 'http://127.0.0.1/api/service/backups/'..id
        local httpClient = net.HTTPClient()
        httpClient:request(url , {
            success = function(response)
                        if tonumber(response.status) == 200 then
                            print("Backup deleted at " .. os.date())
                        else
                            print("Error " .. response.status)                      
                        end
                    end,
            error = function(err)
                        print('error = ' .. err)
                    end,
            options = {
                    method = 'DELETE',
                    headers = {
                        ["content-type"] = 'application/x-www-form-urlencoded;',
                        ["authorization"] = 'Basic '..password
                            },
                    data = 'id='..id
                }
        })
    end
end
-- Récupération de la list des backups
local GETClient = net.HTTPClient()
if dryrun then print('Mode DryRun -> La requète pour effacer ne sera pas éxécutée') end
GETClient:request('http://127.0.0.1/api/service/backups', {
    success = function(response)
                if tonumber(response.status) == 200 then
                    sortBackup(response.data)
                else
                    print("Error " .. response.status)                      
                   end
                end,
    error = function(err)
                print('error = ' .. err)
            end,
    headers = {
                ["content-type"] = 'application/x-www-form-urlencoded;',
                ["authorization"] = 'Basic '..password
                }                       
    });

 

Partager ce message


Lien à poster
Partager sur d’autres sites

Sorry for post in english and text in scenes, but it's faster to write for me. I need my modification  because of many (biggest or smallest)  problem each  time when I upgrade HC2 with new firmware. And the problem not happen direct after upgrade, but  hours or days after (like my last problem with corrupt z-wave databases or 503 error after restart) .

For restore backup when I have 503 error without chance to login I use REST client for POST http://HC2IP/api/service/backups/ with payload {"action":"restore","params":{"id":928}}. "id" I take form GET http://HC2IP/api/service/backups

 

Small modification of backup and delete:

1. Autodelete only autobackup (created by backup_store.lua scene)

2. Autodelete no oldest backup but delete backups by days from today.

Note: Scenes not use any variables stored in HC2, they parse data by backup destricption

 

In backup_store.lua you have this new parameters:

backup_symbol = '!' -- this symbol is added on beginning of description on backup time. Scenes use this for identify autobackup and for not delete manual or upgrade time backups without this symbol (in example on attached printscreen I use ‘p’ on place of '!')

 

backup_stay = '025' -- days for store backup from 001 to 999 days (obligatory with loading zeros). When for ex. you change this parameters for 1 backup from 030 to 025 and after this return to 030, only this one have different store time from another backups.

 

In backup_delete.lua

backup_symbol = '!' -- most important to be same to backup_symbol defined in backup_store.lua

 

default_stay = 'no' -- use individual backup store time from description. Set 'yes' if you decide to ignore individual time to store backup defined in backup__store.lua and registered in backup description

 

backup_stay = '030' -- if you decide to set default_stay to 'yes' backup_delete.lua use this for check number of day after witch the backup will be delete. The backup_delete.lua use this parameter too for backup with description who start by '!' but without [NNN] for number of store day (ex. for temporary backup created manually, they be delete after this number of day)

 

Structure of backup description used by scenes:

![025] any character/any text

! - first symbol identify backup created and used by scenes, obligatory for treatment by this two scenes

[025] - number of days for store backup, not obligatory, if not exist the backup_stay defined in backup_delete.lua are used.

 

 

backup_delate.lua

--[[
%% properties
%% events
%% globals
--]]


-- Flag dryrun; Si true, la requete sur api pour effacer le backup n'est pas effectuée
local dryrun = true

--[[ 
modification to delete only backup file created by autobackup scene
(selected by '!' in descrption on first positon) and oldes more that 90 days 
Backups created manualy (without '!') are not deleted by this scene
--]]
local backup_stay = 10 -- time in day for store autobackup file if not use time in description ore no time in description
local default_stay = 'no' -- if 'yes' use [backup_stay] for all autobackup file, if 'no' use number of days stored in desciption of backup
local backup_symbol = '!' -- only delete after day stored in [backup_time] backup with this symbol on first postion in decription text. Need the same as in auto backup scene

-- Password admin encodé en base64
local password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
print('Current parameters:')
print('only backups with description start by ['..backup_symbol..'] are processed')
print('and deleted after: '..backup_stay..' day(s) if not dedicated information in description')
if  default_stay == 'yes' then print('Number of days for store backup is overwriten by '.. tostring(backup_stay) ..' day(s)') end

function sortBackup(data)
	local backups = json.decode(data)
	-- Vérification de présence Backup
	if (backups and type(backups == 'table') and #backups > 0) then
		if #backups > 1 then print(#backups .. ' Backups présents') else print('1 Backup présent') end
	
		for i in ipairs(backups) do
			--fibaro:debug('<font color="red">ID: '..backups[i]['id']..' | TIME: '..os.date("%Y/%m/%d %H:%M:%S", backups[i]['timestamp'])..' | DESCRIPTION: '..backups[i]['description'])
			--print(os.date("%Y/%m/%d %H:%M:%S", backups[i]['timestamp']))
			--print(os.time())
      		--print(os.time() - tonumber(backups[i]['timestamp']))
      		delta=os.time() - tonumber(backups[i]['timestamp'])
      		todelete=string.sub(backups[i]['description'],1,1) -- =='!'
				if default_stay == 'no' and string.sub(backups[i]['description'],2,2) == '[' then -- obsłużyć gdy nie trafi na []
      			
        		backup_stay_tmp=tonumber(string.sub(backups[i]['description'],3,5))
        		else
        		backup_stay_tmp=backup_stay
        		end
--      		print(tostring(backup_stay_tmp)..string.sub(backups[i]['description'],2,2))
--			print(string.sub(backups[i]['description'],1,1)) -- =='!'
    		if delta <= backup_stay_tmp*60*60*24 and (string.sub(backups[i]['description'],1,1)) == backup_symbol then
			fibaro:debug('<font color="orange">ID: '..backups[i]['id']..' | TIME: '..os.date("%Y/%m/%d %H:%M:%S", backups[i]['timestamp'])..' | DESC: '..backups[i]['description'])
        	fibaro:debug("^^^ To delete in ".. backup_stay_tmp-tostring(math.floor(delta/60/60/24)).." day from today ^^^")
      		elseif
      		delta > backup_stay_tmp*60*60*24 and (string.sub(backups[i]['description'],1,1)) == backup_symbol then
			fibaro:debug('<font color="red">ID: '..backups[i]['id']..' | TIME: '..os.date("%Y/%m/%d %H:%M:%S", backups[i]['timestamp'])..' | DESC: '..backups[i]['description'])
        	print("^^^ Deleted this time ^^^")
			deleteBackup(backups[i]['id'])
        	else
        	fibaro:debug('<font color="green">ID: '..backups[i]['id']..' | TIME: '..os.date("%Y/%m/%d %H:%M:%S", backups[i]['timestamp'])..' | DESC: '..backups[i]['description'])
      		end
    	end
	else
		print('Pas de backup ou erreur lors de la récupération de la liste')
		fibaro:abort()
	end
	
	-- Pour chaque Backup on stock le timestamp de la date de réalisation dans une table
	-- On classe ensuite les timestamps par ordre croissant
	local timestamp = {}
	for i in ipairs(backups) do
		table.insert(timestamp, backups[i]['timestamp'])
	end
	table.sort(timestamp)


	-- Le 1er timestamp de la table est le plus petit donc le plus ancien en epochtime
	-- Dans la table de backup on recherche le backup ayant ce timestamp
    --[[
	local id = false
	for i in ipairs(backups) do
		if (tonumber(backups[i]['timestamp']) == tonumber(timestamp[1])) then id = backups[i]['id'] end
	end

	if id then 
		print("ID du backup le plus ancien: "..id) 
		deleteBackup(id)
	else
		print("Erreur lors de la récupération de l'ID")
		fibaro:abort()
	end
	--]]
end

function deleteBackup(id)
	-- Requete via API pour effacer le backup le plus ancien
	if (not dryrun) and (id) then
		print('Effacement du backup '..id..' en cours. Cela peut prendre 30s')
		local url = 'http://127.0.0.1/api/service/backups/'..id
		local httpClient = net.HTTPClient()
		httpClient:request(url , {
			success = function(response)
						if tonumber(response.status) == 200 then
							print("Backup deleted at " .. os.date())
						else
							print("Error " .. response.status)						
						end
					end,
			error = function(err)
						print('error = ' .. err)
					end,
			options = {
					method = 'DELETE',
					headers = {
						["content-type"] = 'application/x-www-form-urlencoded;',
						["authorization"] = 'Basic '..password
							},
					data = 'id='..id
				}
		})
	end
end

-- Récupération de la list des backups
local GETClient = net.HTTPClient()
if dryrun then print('Mode DryRun -> La requète pour effacer ne sera pas éxécutée') end
GETClient:request('http://127.0.0.1/api/service/backups', {
	success = function(response)
				if tonumber(response.status) == 200 then
					sortBackup(response.data)
				else
					print("Error " .. response.status)						
                   end
                end,
	error = function(err)
				print('error = ' .. err)
            end,
	headers = {
				["content-type"] = 'application/x-www-form-urlencoded;',
				["authorization"] = 'Basic '..password
				}				      	
	});
	

 

backup_store.lua

 

--[[
%% properties
%% events
%% globals
--]]
     
-- ID des mobiles,tablettes pour notification
local portable = { 892 }
local backup_symbol = '!' -- for auto delete only backups with this symbol on irst postion in description
local backup_stay = '025' -- numbers of days to store autobackups (from 001 to 999 with loading zeros)
print('Current parameters:')
print('delete after: '..backup_stay..' day(s), only backups with description start by ['..backup_symbol..']')
fibaro:sleep(10*1000)

function sendPush(message)
    if #portable > 0 then
        for _,v in ipairs(portable) do
            fibaro:call(v,'sendPush', message)
        end
    end
end

-- Message Descriptif du Backup
local descriptif = backup_symbol..'['..backup_stay..'] Autobackup - '..os.date("%d/%m/%y - %HH%M")

-- Password admin encodé en base64
local password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

local url = 'http://127.0.0.1/api/service/backups'
local datas = '{"action":"create","params":{"name":"'..descriptif..'"}}'


local httpClient = net.HTTPClient()
httpClient:request(url , {
		success = function(response)
					if tonumber(response.status) == 201 or tonumber(response.status) == 202 then
						print("Backup Created at " .. os.date())
        				sendPush(descriptif .. ' effectué')				
                    else
						print("Error " .. response.status)
         				sendPush('Erreur lors de la création du Backup - '.. response.status)
                    end
                end,
        error = function(err)
					print('error = ' .. err)
                end,
        options = {
				method = 'POST',
                headers = { 
						["content-type"] = 'application/json',
						["Authorization"] = 'Basic '..password
                          },
                data = datas
			}
});

on image backup2 parameter  dryrun = true

on image backup3 parameter  dryrun = false

bakup1.PNG

backup3.PNG

backup2.PNG

  • Upvote 2

Partager ce message


Lien à poster
Partager sur d’autres sites

I have "small" problem, when in run backup_delate.lua. If I have more that 1 backup to delete in one run, script delete only one backup (oldest - it's ok) from selected by criteria for deletion (red debug info) for other chosen backup HC2 return error 404. For delete next one and next (if exist) I need rerun the scene. But if I create for function deleteBackup(id) separate scene and I call it with parameter (id) from backup_delete.lua of course with sleep(45) between the next ID all work fine.

 

..//..

if... then

fibaro:startScene(999, {{id_del = backups['id']}})

fibaro:sleep(45)

end

..//..

 

For me is look like situation when backup_delate.lua block called http://127.0.0.1/api/service/backups/'..id until the scene end.

Any from You have the same problem? Any idea?

Partager ce message


Lien à poster
Partager sur d’autres sites

I have confirmation from Fibaro that "httpClient:request(url..." blocks handle until the scene is over not to end of called http work and /api/service/backups/'..id  can only be launched once at the same time. Therefore, to delete more than one file, you must call the external scene who delete backups

In this case I updated code of backup-delete.lua and added backup-batch. All necessary parameters are passed automatically to backup-batch.lua, You only need edit parameters in backup-create.lua and backup-delete.lua.

I added for batch process NotificationService with popups on web page like in situation with to many scenes run at same time

backup-popups.PNG.e0509d533660425a3f3c751c5d93f43b.PNG

backup-batch.lua

 

 

backup-delete.lua

backup-create.lua

Modifié par drboss
  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

Very good job drboss

Envoyé de mon Nexus 5X en utilisant Tapatalk

Partager ce message


Lien à poster
Partager sur d’autres sites

Merci @pepite Je rattrape le temps quand je n'avais aucun accès à HC2. ( Des chirurgiens opéraient ma colonne vertébrale ;-(  Et je n'ai pas eu accès à l'ordinateur, juste un téléphone :-((((((((

 

Partager ce message


Lien à poster
Partager sur d’autres sites

×