refs #1593 add UEFILib and python scripts

pull/8/head
Natalia Serrano 2025-02-25 15:00:19 +01:00
parent fa788953c1
commit 4ebe08288a
14 changed files with 2874 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#!/usr/bin/env python3
import os
import sys
def main():
os.system('poweroff')
sys.exit(0)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,196 @@
#!/usr/bin/python3
import os
import sys
import subprocess
import ogGlobals
import SystemLib
import CacheLib
import FileSystemLib
import DiskLib
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
## (ogGlobals se encarga)
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
open (ogGlobals.OGLOGSESSION, 'w').close()
open (ogGlobals.OGLOGCOMMAND, 'w').close()
open (ogGlobals.OGLOGCOMMAND+'.tmp', 'w').close()
# Registro de inicio de ejecución
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {sys.argv}')
# Solo ejecutable por OpenGnsys Client.
#path = os.getenv('PATH')
#if path:
# os.environ['PATH'] = f"{path}:{os.path.dirname(__name__)}"
prog = os.path.basename(__name__)
#____________________________________________________________________
#
# El parámetro $2 es el que aporta toda la información y el $1 se queda obsoleto
# Formato de entrada:
# dis=Número de disco
# *=caracter de separación
# che=Vale 0 o 1
# *=caracter de separación
# $tch=tamaño cache
# != caracter de separación
#
# Y un numero indeterminado de cadenas del tipo siguuenteseparadas por el caracter '$':
# par=Número de particion*cod=Código de partición*sfi=Sistema de ficheros*tam=Tamaño de la partición*ope=Operación
# @= caracter de separación
#____________________________________________________________________
# Captura de parámetros (se ignora el 1er parámetro y se eliminan espacios y tabuladores).
#param='dis=1*che=0*tch=70000000!par=1*cpt=NTFS*sfi=NTFS*tam=11000000*ope=0%'
#param = ''.join(sys.argv[2:]).replace(' ', '').replace('\t', '')
param = sys.argv[2]
# Activa navegador para ver progreso
coproc = subprocess.Popen (['/opt/opengnsys/bin/browser', '-qws', 'http://localhost/cgi-bin/httpd-log.sh'])
# Leer los dos bloques de parámetros, separados por '!'.
tbprm = param.split ('!')
pparam = tbprm[0] # General disk parameters
sparam = tbprm[1] # Partitioning and formatting parameters
# Toma valores de disco y caché, separados por "*".
# Los valores están en las variables $dis: disco, $che: existe cache (1, 0), $tch: Tamaño de la cache.
tbprm = pparam.split ('*')
dis = ptt = tch = None
for item in tbprm:
if '=' not in item: continue
k, v = item.split ('=', 1)
if k not in ['dis', 'tch', 'ptt']: ## 'ptt' added, unused 'che' removed
print (f'ignoring unknown disk parameter ({k})')
continue
if 'dis' == k: dis = int (v)
elif 'ptt' == k: ptt = v
elif 'tch' == k: tch = v
# Error si no se define el parámetro de disco (dis).
if dis is None: sys.exit (ogGlobals.OG_ERR_FORMAT)
if ptt is None: ptt = 'MSDOS'
if tch is None: tch = '0'
# Toma valores de distribución de particiones, separados por "%".
tbp = [] # Valores de configuración (parámetros para ogCreatePartitions)
tbf = {} # Tabla de formateo
tbprm = sparam.split('%')
maxp=0
for item in tbprm:
if not item: continue ## por si nos pasan un '%' al final de todo
# Leer datos de la partición, separados por "*".
par = cpt = sfi = tam = None
ope = 0
for c in item.split ('*'):
if '=' not in c: continue
k, v = c.split ('=', 1)
if k not in ['par', 'cpt', 'sfi', 'tam', 'ope']:
print (f'ignoring unknown partition parameter ({k})')
continue
if 'par' == k: par = int (v)
elif 'cpt' == k: cpt = v
elif 'sfi' == k: sfi = v
elif 'tam' == k: tam = v
elif 'ope' == k: ope = int (v)
missing_params = []
if par is None: missing_params.append ('par')
if cpt is None: missing_params.append ('cpt')
if sfi is None: missing_params.append ('sfi')
if tam is None: missing_params.append ('tam')
if missing_params:
print (f'partition data ({item}) missing required parameters ({' '.join (missing_params)})')
sys.exit (1)
# Componer datos de particionado.
if 'CACHE' != cpt: tbp.append (f'{cpt}:{tam}')
print (f'nati: par ({par}) ope ({ope})')
if ope:
print (f'nati: par ({par}) ope ({ope}): dentro del if')
# Si se activa operación de formatear, componer datos de formateo.
if cpt not in ['EMPTY', 'EXTENDED', 'LINUX-LVM', 'LVM', 'ZPOOL']:
tbf[par] = sfi
# Obtener la partición mayor.
if par > maxp: maxp = par
#____________________________________________________
#
# Proceso
#____________________________________________________
print (f'nati: dis ({dis}) ptt ({ptt}) tch ({tch}) || tbp ({tbp}) tbf ({tbf})')
# Tamaño actual de la cache
CACHESIZE=CacheLib.ogGetCacheSize()
# Desmonta todas las particiones y la caché
SystemLib.ogEcho (['session', 'log'], None, f'[10] {ogGlobals.lang.MSG_HELP_ogUnmountAll}')
FileSystemLib.ogUnmountAll (dis)
CacheLib.ogUnmountCache()
# Elimina la tabla de particiones
cur_ptt = DiskLib.ogGetPartitionTableType (dis)
if not cur_ptt or ptt != cur_ptt:
DiskLib.ogDeletePartitionTable (dis)
SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable)
# Crea tabla de particiones MSDOS (NOTA: adaptar para tablas GPT).
DiskLib.ogCreatePartitionTable (dis, ptt)
# Inicia la cache.
print (f'nati: evaluating if CACHE in sparam ({sparam})')
if 'CACHE' in sparam:
print (f'nati: dentro del if')
SystemLib.ogEcho (['session', 'log'], None, f'[30] {ogGlobals.lang.MSG_HELP_ogCreateCache}')
SystemLib.ogEcho (['session', 'log'], None, f' initCache {tch}')
SystemLib.ogExecAndLog ('command', CacheLib.initCache, tch)
# Definir particionado.
SystemLib.ogEcho (['session', 'log'], None, f'[50] {ogGlobals.lang.MSG_HELP_ogCreatePartitions}')
SystemLib.ogEcho (['session', 'log'], None, f' ogCreatePartitions {dis} {' '.join (tbp)}')
res = SystemLib.ogExecAndLog ('command', DiskLib.ogCreatePartitions, dis, tbp)
if not res:
coproc.kill()
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_GENERIC, f'ogCreatePartitions {dis} {' '.join (tbp)}')
sys.exit (1)
SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable)
# Formatear particiones
SystemLib.ogEcho (['session', 'log'], None, f'[70] {ogGlobals.lang.MSG_HELP_ogFormat}')
retval = 0
for p in range (1, maxp+1):
print (f'nati: p ({p})')
if p not in tbf: continue
if 'CACHE' == tbf[p]:
if CACHESIZE == tch: # Si el tamaño es distinto ya se ha formateado.
SystemLib.ogEcho (['session', 'log'], None, ' ogFormatCache')
retval = SystemLib.ogExecAndLog ('command', CacheLib.ogFormatCache)
else:
print (f'nati: p ({p}) no es cache, la formateamos')
SystemLib.ogEcho (['session', 'log'], None, f' ogFormatFs {dis} {p} {tbf[p]}')
retval = SystemLib.ogExecAndLog ('command', FileSystemLib.ogFormatFs, dis, str(p), tbf[p])
if retval:
coproc.kill()
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_GENERIC, f'ogFormatFs {dis} {p} {tbf[p]}')
sys.exit (1)
# Registro de fin de ejecución
SystemLib.ogEcho (['session', 'log'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}')
#___________________________________________________________________
#
# Retorno
#___________________________________________________________________
coproc.kill()
sys.exit (0)

View File

@ -0,0 +1,8 @@
#!/usr/bin/env python3
import os
def reboot_system():
os.system('reboot')
if __name__ == "__main__":
reboot_system()

View File

@ -0,0 +1,579 @@
import os.path
import re
import subprocess
import shutil
import ogGlobals
import SystemLib
import FileSystemLib
import DiskLib
import FileLib
import InventoryLib
#!/bin/bash
# Libreria provisional para uso de UEFI
# Las funciones se incluirán las librerías ya existentes
#/**
# ogNvramActiveEntry
#@brief Activa entrada de la NVRAM identificada por la etiqueta o el orden
#@param Num_order_entry | Label_entry Número de orden o la etiqueta de la entrada a borrar.
#@return (nada)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTUEFI UEFI no activa.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#*/ ##
#ogNvramActiveEntry ('2')
#ogNvramActiveEntry ('Windows Boot Manager')
def ogNvramActiveEntry (entry):
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
numentries = []
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
try:
foo = int (entry, 16) ## raises ValueError if entry doesn't look like hexadecimal
num = f'{foo:04x}'.upper()
for l in efibootmgr_out.splitlines():
words = l.split()
if len(words) < 2: continue
if num in words[0]:
numentries.append (words[0][4:8])
except ValueError:
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if words[1] == entry:
numentries.append (words[0][4:8])
if not numentries:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'NVRAM entry "{entry}"')
return
if 1 != len(numentries):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, f'more than one entry found')
return
subprocess.run (['efibootmgr', '-a', '-b', numentries[0]], capture_output=True, text=True)
#/**
# ogNvramAddEntry
#@brief Crea nueva entrada en el gestor de arranque (NVRAM), opcionalmente la incluye al final del orden de arranque.
#@param Str_Label_entry Número de disco o etiqueta de la entrada a crear.
#@param Str_BootLoader Número de partición o cargador de arranque.
#@param Bool_Incluir_Arranque Incluir en el orden de arranque (por defecto FALSE) (opcional)
#@return (nada)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTUEFI UEFI no activa.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#*/ ##
#ogNvramAddEntry ('1', '2', True)
#ogNvramAddEntry ('grub', '/EFI/grub/grubx64.efi', True)
#ogNvramAddEntry ('Windows', '/EFI/Microsoft/Boot/bootmgfw.efi')
def ogNvramAddEntry (bootlbl, bootldr, nvram_set=False):
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
esp = DiskLib.ogGetEsp()
if not esp:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'ESP')
return
efidisk, efipar = esp.split()
try:
foo = int(bootlbl) + int(bootldr) ## raises ValueError if bootlbl/bootldr don't look like numbers
bootlabel = f'Part-{int(bootlbl):02d}-{int(bootldr):02d}'
bootloader = f'/EFI/{bootlabel}/Boot/ogloader.efi'
except ValueError:
bootlabel = bootlbl
bootloader = bootldr
ogNvramDeleteEntry (bootlabel)
dev = DiskLib.ogDiskToDev (efidisk)
subprocess.run (['efibootmgr', '-C', '-d', dev, '-p', efipar, '-L', bootlabel, '-l', bootloader])
if nvram_set:
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if words[1] == bootlabel:
numentry = words[0][4:8]
order = ogNvramGetOrder()
ogNvramSetOrder (order + [numentry])
#/**
# ogCopyEfiBootLoader int_ndisk str_repo path_image
#@brief Copia el cargador de arranque desde la partición EFI a la de sistema.
#@param int_ndisk nº de orden del disco
#@param int_part nº de partición
#@return (nada, por determinar)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#@note Si existe el cargador en la partición de sistema no es válido
#*/ ##
def ogCopyEfiBootLoader (disk, par):
mntdir = FileSystemLib.ogMount (disk, par)
if not mntdir:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, f'{disk} {par}')
return None
esp = DiskLib.ogGetEsp()
if not esp:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'EFI partition')
return
esp_disk, esp_par = esp.split()
efidir = FileSystemLib.ogMount (esp_disk, esp_par)
if not efidir:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, 'ESP')
return
bootlabel = f'Part-{int(disk):02d}-{int(par):02d}'
osversion = InventoryLib.ogGetOsVersion (disk, par)
print (f'bootlabel ({bootlabel})')
print (f'osversion ({osversion})')
if 'Windows 1' in osversion:
loader = None
for i in f'{efidir}/EFI/Microsoft/Boot/bootmgfw.efi', f'{efidir}/EFI/{bootlabel}/Boot/bootmgfw.efi':
if os.path.exists (i):
loader = i
if not loader:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTOS, f'{disk} {par} ({osversion}, EFI)')
return None
if (os.path.isdir (f'{mntdir}/ogBoot')):
shutil.rmtree (f'{mntdir}/ogBoot')
dirloader = os.path.realpath (os.path.dirname (loader) + '/..')
shutil.copytree (f'{dirloader}/Boot', f'{mntdir}/ogBoot')
#/**
# ogNvramDeleteEntry
#@brief Borra entrada de la NVRAM identificada por la etiqueta o el orden
#@param Num_order_entry | Label_entry Número de orden o la etiqueta de la entrada a borrar.
#@return (nada)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTUEFI UEFI no activa.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado (entrada en NVRAM).
#*/ ##
#ogNvramDeleteEntry ('2')
#ogNvramDeleteEntry ('Windows Boot Manager')
def ogNvramDeleteEntry (entry):
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
numentries = []
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
try:
foo = int (entry, 16) ## raises ValueError if entry doesn't look like hexadecimal
num = f'{foo:04x}'.upper()
for l in efibootmgr_out.splitlines():
words = l.split()
if len(words) < 2: continue
if num in words[0]:
numentries.append (words[0][4:8])
except ValueError:
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if words[1] == entry:
numentries.append (words[0][4:8])
if not numentries:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'NVRAM entry "{entry}"')
return
if 1 != len(numentries):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, f'more than one entry found')
return
subprocess.run (['efibootmgr', '-B', '-b', numentries[0]], capture_output=True, text=True)
#/**
# ogNvramGetCurrent
#@brief Muestra la entrada del gestor de arranque (NVRAM) que ha iniciado el equipo.
#@return Entrada con la que se ha iniciado el equipo
#@exception OG_ERR_NOTUEFI UEFI no activa.
#*/ ##
def ogNvramGetCurrent():
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
bootentry = '9999'
ret = None
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if 'BootCurrent' in words[0]:
bootentry = words[1]
continue
if bootentry in words[0]:
num = words[0][4:8].strip ('0') or '0'
ret = f'{num} {words[1]}'
return ret
# ogNvramGetNext
#@brief Muestra la entrada del gestor de arranque (NVRAM) que se utilizará en el próximo arranque.
#@return Entrada que se utilizará en el próximo arranque
#@exception OG_ERR_NOTUEFI UEFI no activa.
#*/ ##
def ogNvramGetNext():
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
ret = None
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if 'BootNext' in words[0]:
ret = words[1]
return ret
# ogNvramGetOrder
#@brief Muestra el orden de las entradas del gestor de arranque (NVRAM)
#@return Array, orden de las entradas
#@exception OG_ERR_NOTUEFI UEFI no activa.
#*/ ##
def ogNvramGetOrder():
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
ret = []
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
words = l.split()
if len(words) < 2: continue
if 'BootOrder:' == words[0]:
ret = words[1].split (',')
return ret
#/**
# ogNvramGetTimeout
#@brief Muestra el tiempo de espera del gestor de arranque (NVRAM)
#@return Timeout de la NVRAM
#@exception OG_ERR_NOTUEFI UEFI no activa.
#*/ ##
def ogNvramGetTimeout():
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
ret = None
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if 'Timeout:' == words[0]:
ret = words[1]
return ret
#/**
# ogGrubUefiConf int_ndisk int_part str_dir_grub
#@brief Genera el fichero grub.cfg de la ESP
#@param int_ndisk nº de orden del disco
#@param int_part nº de partición
#@param str_dir_grub prefijo del directorio de grub en la partición de sistema. ej: /boot/grubPARTITION
#@return (nada, por determinar)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#@TODO Confirmar si el fichero "$EFIDIR/EFI/$BOOTLABEL/grub.cfg" es necesario.
#*/ ##
#/**
# ogNvramInactiveEntry
#@brief Inactiva entrada de la NVRAM identificada por la etiqueta o el orden
#@param Num_order_entry | Label_entry Número de orden o la etiqueta de la entrada a borrar.
#@return (nada)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#@exception OG_ERR_NOTUEFI UEFI no activa.
#*/ ##
#ogNvramInactiveEntry ('2')
#ogNvramInactiveEntry ('Windows Boot Manager')
def ogNvramInactiveEntry (entry):
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
numentries = []
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
try:
foo = int (entry, 16) ## raises ValueError if entry doesn't look like hexadecimal
num = f'{foo:04x}'.upper()
for l in efibootmgr_out.splitlines():
words = l.split()
if len(words) < 2: continue
if num in words[0]:
numentries.append (words[0][4:8])
except ValueError:
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if words[1] == entry:
numentries.append (words[0][4:8])
if not numentries:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'NVRAM entry "{entry}"')
return
if 1 != len(numentries):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, f'more than one entry found')
return
subprocess.run (['efibootmgr', '-A', '-b', numentries[0]], capture_output=True, text=True)
#/**
# ogNvramList
#@brief Lista las entradas de la NVRAN (sólo equipos UEFI)
#@return Multiline string: entradas de la NVRAM con el formato: orden etiqueta [* (si está activa) ]
#@exception OG_ERR_NOTUEFI UEFI no activa.
#*/ ##
def ogNvramList():
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
ret = ''
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if re.search ('Boot[0-9]', words[0]):
active = '*' if '*' in words[0] else ''
num = words[0][4:8].strip ('0') or '0'
ret += '{:>4s} {} {}\n'.format (num, words[1], active)
return ret
#/**
# ogNvramPxeFirstEntry
#@brief Sitúa la entrada de la tarjeta de red en el primer lugar en la NVRAM.
#@return (nada)
#@exception OG_ERR_NOTUEFI UEFI no activa.
#*/ ##
def ogNvramPxeFirstEntry():
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
num = ''
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
if re.search ('IP[vV]{0,1}4', l):
num = l[4:8].strip ('0') or '0'
numentry = f'{int(num):04x}'.upper()
o = ogNvramGetOrder()
if not o:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, f'ogNvramGetOrder returned an empty list')
return
# Si la entrada es la primera nos salimos.
if numentry == o[0]:
return True
# Si la entrada ya existe la borramos.
order = [numentry] + list (filter (lambda x: x if x!=numentry else [], o))
ogNvramSetOrder (order)
return True
#/**
# ogRestoreEfiBootLoader int_ndisk str_repo
#@brief Copia el cargador de arranque de la partición de sistema a la partición EFI.
#@param int_ndisk nº de orden del disco
#@param int_part nº de partición
#@return (nada, por determinar)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado (partición de sistema o EFI).
#@exception OG_ERR_NOTOS sin sistema operativo.
#*/ ##
def ogRestoreEfiBootLoader (disk, par):
mntdir = FileSystemLib.ogMount (disk, par)
if not mntdir:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, f'{disk} {par}')
return
esp = DiskLib.ogGetEsp()
if not esp:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'EFI partition')
return
esp_disk, esp_par = esp.split()
efidir = FileSystemLib.ogMount (esp_disk, esp_par)
if not efidir:
FileSystemLib.ogFormat (esp_disk, esp_par, 'FAT32')
efidir = FileSystemLib.ogMount (esp_disk, esp_par)
if not efidir:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, 'ESP')
return
osversion = InventoryLib.ogGetOsVersion (disk, par)
if 'Windows 1' in osversion:
bootlabel = f'Part-{int(disk):02d}-{int(par):02d}'
loader = FileLib.ogGetPath (file=f'{mntdir}/ogBoot/bootmgfw.efi')
if not loader:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTOS, f'{disk} {par} ({osversion}, EFI)')
return
efi_bl = f'{efidir}/EFI/{bootlabel}'
if os.path.exists (efi_bl):
shutil.rmtree (efi_bl)
os.makedirs (efi_bl, exist_ok=True)
shutil.copytree (os.path.dirname (loader), f'{efi_bl}/Boot', symlinks=True)
shutil.copy (loader, f'{efi_bl}/Boot/ogloader.efi')
if '' != FileLib.ogGetPath (file=f'{efidir}/EFI/Microsoft'):
os.rename (f'{efidir}/EFI/Microsoft', f'{efidir}/EFI/Microsoft.backup.og')
return
#/**
# ogRestoreUuidPartitions
#@brief Restaura los uuid de las particiones y la tabla de particiones
#@param int_ndisk nº de orden del disco
#@param int_nfilesys nº de orden del sistema de archivos
#@param REPO|CACHE repositorio
#@param str_imgname nombre de la imagen
#@return (nada)
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_NOTFOUND No encontrado fichero de información de la imagen (con uuid)
#*/ ##
#/**
# ogNvramSetNext
#@brief Configura el próximo arranque con la entrada del gestor de arranque (NVRAM) identificada por la etiqueta o el orden.
#@param Num_order_entry | Label_entry Número de orden o la etiqueta de la entrada a borrar.
#@return (nada)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTUEFI UEFI no activa.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#*/ ##
#ogNvramSetNext ('2')
#ogNvramSetNext ('Windows Boot Manager')
def ogNvramSetNext (entry):
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
numentries = []
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
try:
foo = int (entry, 16) ## raises ValueError if entry doesn't look like hexadecimal
num = f'{foo:04x}'.upper()
for l in efibootmgr_out.splitlines():
words = l.split()
if len(words) < 2: continue
if num in words[0]:
numentries.append (words[0][4:8])
except ValueError:
for l in efibootmgr_out.splitlines():
words = l.split (maxsplit=1)
if len(words) < 2: continue
if words[1] == entry:
numentries.append (words[0][4:8])
if not numentries:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'NVRAM entry "{entry}"')
return
if 1 != len(numentries):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, f'more than one entry found')
return
subprocess.run (['efibootmgr', '-n', numentries[0]], capture_output=True, text=True)
#/**
# ogNvramSetOrder
#@brief Configura el orden de las entradas de la NVRAM
#@param Orden de las entradas separadas por espacios
#@return (nada)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTUEFI UEFI no activa.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado (entrada NVRAM).
#*/ ##
#ogNvramSetOrder (['1', '3'])
def ogNvramSetOrder (order):
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
try:
for i in order:
foo = int (i, 16)
except ValueError:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, 'ogNvramSetOrder ([array or hex values])')
return
# Entradas de la NVRAM actuales
numentries = []
efibootmgr_out = subprocess.run (['efibootmgr'], capture_output=True, text=True).stdout
for l in efibootmgr_out.splitlines():
words = l.split()
if len(words) < 2: continue
if re.search ('Boot[0-9a-fA-F]{4}', words[0]):
numentries.append ('0' + words[0][4:8])
new_order = []
for o in order:
h = f'{int(o,16):05x}'.upper()
if h not in numentries:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'NVRAM entry order "{h}"')
return
new_order.append (h)
subprocess.run (['efibootmgr', '-o', ','.join (new_order)])
#/**
# ogNvramSetTimeout
#@brief Configura el tiempo de espera de la NVRAM
#@param Orden de las entradas separadas por espacios
#@return (nada)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#*/ ##
#ogNvramSetTimeout ('2')
def ogNvramSetTimeout (t):
if not InventoryLib.ogIsEfiActive():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTUEFI, '')
return
try:
num = int (t) ## raises ValueError if t doesn't look like a number
except ValueError:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, 'ogNvramSetTimeout (timeout)')
return
subprocess.run (['efibootmgr', '-t', t])
#/**
# ogUuidChange int_ndisk str_repo
#@brief Reemplaza el UUID de un sistema de ficheros.
#@param int_ndisk nº de orden del disco
#@param int_part nº de partición
#@return (nada, por determinar)
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado.
#*/ ##

View File

@ -0,0 +1,400 @@
#!/usr/bin/python3
# Fichero de idioma: catalá.
#@version 1.1.1
#@author
# Mensajes de error.
MSG_ERR_GENERIC="Error imprevisto no definido"
MSG_ERR_FORMAT="Formato de ejecución incorrecto"
MSG_ERR_OUTOFLIMIT="Valor fuera de rango o no válido"
MSG_ERR_NOTFOUND="Fichero o dispositivo no encontrado"
MSG_ERR_PARTITION="Partición errónea o desconocida"
MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo"
MSG_ERR_CACHE="Error en partición de caché local"
MSG_ERR_NOGPT="El disco indicado no contiene una particion GPT"
MSG_ERR_REPO="Error al montar el repositorio de imágenes"
MSG_ERR_NOMSDOS="El disco indicado no contiene una partición MSDOS"
MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar"
MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar"
MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema"
MSG_ERR_IMAGEFILE="Archivo de imagen corrupto o de otra versión de partclone"
MSG_ERR_NOTEXEC="Programa o función no ejecutable"
MSG_ERR_NOTWRITE="No hay acceso de escritura"
MSG_ERR_NOTCACHE="No existe particion Cache en el cliente"
MSG_ERR_NOTUEFI="La interfaz UEFI no está activa"
MSG_ERR_NOTBIOS="La interfaz BIOS Legacy no está activa"
MSG_ERR_CACHESIZE="El espacio de la cache local o remota no es suficiente"
MSG_ERR_REDUCEFS="Error al reducir el sistema de archivos"
MSG_ERR_EXTENDFS="Error al expandir el sistema de archivos"
MSG_ERR_IMGSIZEPARTITION="Error al restaurar: Particion mas pequeña que la imagen"
MSG_ERR_UPDATECACHE="Error al realizar el comando updateCache"
MSG_ERR_UCASTSYNTAXT="Error en la generación de sintaxis de transferenica unicast"
MSG_ERR_UCASTSENDPARTITION="Error en envio UNICAST de una particion"
MSG_ERR_UCASTSENDFILE="Error en envio UNICAST de un fichero"
MSG_ERR_UCASTRECEIVERPARTITION="Error en la recepcion UNICAST de una particion"
MSG_ERR_UCASTRECEIVERFILE="Error en la recepcion UNICAST de un fichero"
MSG_ERR_MCASTSYNTAXT="Error en la generación de sintaxis de transferenica multicast"
MSG_ERR_MCASTSENDFILE="Error en envio MULTICAST de un fichero"
MSG_ERR_MCASTRECEIVERFILE="Error en la recepcion MULTICAST de un fichero"
MSG_ERR_MCASTSENDPARTITION="Error en envio MULTICAST de una particion"
MSG_ERR_MCASTRECEIVERPARTITION="Error en la recepcion MULTICAST de un fichero"
MSG_ERR_PROTOCOLJOINMASTER="Error en la conexion de una sesion UNICAST|MULTICAST con el MASTER"
MSG_ERR_DONTFORMAT="Error al formatear"
MSG_ERR_DONTMOUNT_IMAGE="Error al montar/reducir la imagen"
MSG_ERR_DONTUNMOUNT_IMAGE="Error al desmontar la imagen"
MSG_ERR_DONTSYNC_IMAGE="Imagen no sincronizable"
MSG_ERR_NOTDIFFERENT="No se detectan diferencias entre la imagen basica y la particion."
MSG_ERR_SYNCHRONIZING="Error al sincronizar, puede afectar la creacion|restauracion de la imagen"
# Mensajes de avisos.
MSG_DONTUSE="NO USAR"
MSG_DONTMOUNT="Sistema de archivos no montado"
MSG_DONTUNMOUNT="El sistema de archivos no se puede desmontar o no está montado"
MSG_MOUNT="Sistema de archivos montado"
MSG_MOUNTREADONLY="Sistema de archivos montado solo de lectura"
MSG_OBSOLETE="EN DESUSO"
# Mensajes complementarios para las ayudas.
MSG_64BIT="64 bits"
MSG_DISK="disc"
MSG_ERROR="Error"
MSG_EXAMPLE="Exemple"
MSG_FORMAT="Format"
MSG_FUNCTION="Funció"
MSG_HARDWAREINVENTORY="Inventario de maquinari de la màquina"
MSG_IMAGE="imatge"
MSG_INSTALLED="instal-lat"
MSG_NOCACHE="sense caché local"
MSG_NOEXTENDED="sense partició estensa"
MSG_PARTITION="partició"
MSG_PROTOCOL="protocol"
MSG_RESERVEDVALUE="Valor reservat"
MSG_SEE="Veure"
MSG_UNKNOWN="Desconegut"
MSG_WARNING="Avís"
# Mensajes del proceso de arranque.
MSG_DETECTLVMRAID="Detectar metadispositivos LVM y RAID."
MSG_ERRBOOTMODE=f"{MSG_ERROR}: Modo de arranque desconocido."
MSG_LAUNCHCLIENT="Ejecutar cliente."
MSG_LOADAPI="Cargar funciones del motor de clonación."
MSG_LOADMODULES="Cargar módulos del kernel."
MSG_MAKELINKS="Crear enlaces simbólicos."
MSG_MOUNTREPO="Montar repositorio por %s en modo %s."
MSG_OFFLINEMODE="Modo de arranque sin conexión."
MSG_OTHERSERVICES="Iniciar servicios complementarios del cliente."
MSG_POWEROFFCONF="Definir parámetros de ahorro de energía."
# Mensajes del menú por defecto.
MSG_BOOT="Iniciar"
MSG_DUPLEX="D&uacute;plex"
MSG_HOSTNAME="Equipo"
MSG_IPADDR="Direcci&oacute;n IP"
MSG_MACADDR="Direcci&oacute;n MAC"
MSG_MENUTITLE="Men&uacute; de opciones"
MSG_POWEROFF="Apagar el equipo"
MSG_SPEED="Velocidad"
# Mensajes de descripción breve de las funciones de la API.
MSG_HELP_ogAclFilter="Extrae las acl de los ficheros de la diferencial"
MSG_HELP_ogAddCmd="Añade comandos al fichero creado por la función ogInstalMiniSetup."
MSG_HELP_ogAddRegistryKey="Añade una nueva clave al registro de Windows."
MSG_HELP_ogAddRegistryValue="Añade un nuevo valor al registro de Windows."
MSG_HELP_ogAddToLaunchDaemon=""
MSG_HELP_ogBoot="Arranca un sistema operativo instalado."
MSG_HELP_ogBootLoaderDeleteEntry=MSG_DONTUSE
MSG_HELP_ogBootLoaderHidePartitions=MSG_DONTUSE
MSG_HELP_ogBootMbrGeneric=""
MSG_HELP_ogBootMbrXP=""
MSG_HELP_ogBurgDefaultEntry="Configura la entrada por defecto de Burg."
MSG_HELP_ogBurgDeleteEntry="Borra en el Burg del MBR las entradas para el inicio en una particion."
MSG_HELP_ogBurgHidePartitions="Configura el Burg del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)."
MSG_HELP_ogBurgInstallMbr="Instal·la el carregador d'arrencada BURG al MBR del primer disc dur"
MSG_HELP_ogBurgOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de Burg."
MSG_HELP_ogCalculateChecksum="Calcula la suma de comprobación (checksum) de un fichero."
MSG_HELP_ogCalculateFullChecksum=""
MSG_HELP_ogChangeRepo="Cambia el repositorio para el recurso remoto images."
MSG_HELP_ogCheckFs="Comprueba la consistencia de un sistema de archivos."
MSG_HELP_ogCheckIpAddress=""
MSG_HELP_ogCheckProgram=""
MSG_HELP_ogCheckStringInGroup=""
MSG_HELP_ogCheckStringInReg=""
MSG_HELP_ogCheckSyncImage="Muestra el contenido de la imagen para comprobarla."
MSG_HELP_ogCleanLinuxDevices=""
MSG_HELP_ogCleanOs="Elimina los archivos que no son necesarios en el sistema operativo."
MSG_HELP_ogCompareChecksumFiles="Compara si coinciden las sumas de comprobación almacenadas de 2 ficheros."
MSG_HELP_ogConfigureFstab=""
MSG_HELP_ogConfigureOgagent="Configura el nuevo agente OGAgent para sistemas ooperativos."
MSG_HELP_ogCopyFile="Copia un fichero a otro almacenamiento."
MSG_HELP_ogCreateBootLoaderImage=""
MSG_HELP_ogCreateCache="Reserva espacio para la partición de caché al final del disco."
MSG_HELP_ogCreateDiskImage="Genera una imagen exacta de un disco completo."
MSG_HELP_ogCreateFileImage="Crea/Redimensiona el archivo de la imagen sincronizada"
MSG_HELP_ogCreateGptPartitions=""
MSG_HELP_ogCreateImage="Genera una imagen exacta de un sistema operativo instalado localmente."
MSG_HELP_ogCreateImageSyntax=""
MSG_HELP_ogCreateInfoImage="Crea informacion del contenido de la imagen"
MSG_HELP_ogCreateMbrImage="Genera una imagen del sector de arranque (MBR)."
MSG_HELP_ogCreatePartitions="Define la estructura de particiones de un disco."
MSG_HELP_ogCreatePartitionTable="Genera una tabla de particiones en caso de que no sea valida."
MSG_HELP_ogCreateTorrent=""
MSG_HELP_ogCopyEfiBootLoader="Copia el cargador de arranque desde la partición EFI a la de sistema."
MSG_HELP_ogDeleteCache="Elimina la partición de caché local."
MSG_HELP_ogDeleteFile="Borra un fichero de un espacio de almacenamiento."
MSG_HELP_ogDeletePartitionTable="Elimina la tabla de particiones del disco"
MSG_HELP_ogDeleteRegistryKey="Borra una clave vacía del registro de Windows."
MSG_HELP_ogDeleteRegistryValue="Borra un valor del registro de Windows."
MSG_HELP_ogDeleteTree="Borra un árbol de directorios de un espacio de almacenamiento."
MSG_HELP_ogDevToDisk="Devuelve el nº de orden de disco o de partición correspondiente al camino del fichero de dispositivo."
MSG_HELP_ogDiskToDev="Devuelve el camino del fichero de dispositivo correspondiente al nº de orden de disco o de partición."
MSG_HELP_ogDomainScript=""
MSG_HELP_ogEcho=""
MSG_HELP_ogExecAndLog=""
MSG_HELP_ogExtendFs="Extiende el tamaño de un sistema de archivo al máximo de su partición."
MSG_HELP_ogFindCache="Indica la partición reservada para caché local."
MSG_HELP_ogFixBootSector=""
MSG_HELP_ogFormatCache="Formatea (inicia) el sistema de caché local."
MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos."
MSG_HELP_ogFormatFs=MSG_HELP_ogFormat
MSG_HELP_ogGetArch="Devuelve el tipo de arquitectura del cliente."
MSG_HELP_ogGetCacheSize="Devuelve el tamaño de la partición de caché local."
MSG_HELP_ogGetCacheSpace="Devuelve el espacio máximo disponible que puede ser reservado para la partición de caché local."
MSG_HELP_ogGetCaller=""
MSG_HELP_ogGetDiskSize="Devuelve el tamaño del disco."
MSG_HELP_ogGetDiskType="Devuelve el mnemónico de tipo de disco."
MSG_HELP_ogGetFreeSize=""
MSG_HELP_ogGetFsSize="Devuelve el tamaño de un sistema de archivos."
MSG_HELP_ogGetFsType="Devuelve el mnemónico de tipo de sistema de archivos."
MSG_HELP_ogGetGroupDir="Devuelve el camino del directorio por defecto para el grupo del cliente."
MSG_HELP_ogGetGroupName="Devuelve el nombre del grupo al que pertenece el cliente."
MSG_HELP_ogGetHivePath="Devuelve el camino completo del fichero de una sección del registro de Windows."
MSG_HELP_ogGetHostname="Devuelve el nombre de la máquina local."
MSG_HELP_ogGetImageCompressor="Devuelve la herramienta de compresión de la imagen."
MSG_HELP_ogGetImageInfo="Muestra información sobre la imagen monolitica: clonacion:compresor:sistemaarchivos:tamañoKB."
MSG_HELP_ogGetImageProgram="Devuelve el programa usado para crear la imagen."
MSG_HELP_ogGetImageSize="Devuelve el tamaño de una imagen de sistema."
MSG_HELP_ogGetImageType="Devuelve el sistema de ficheros de la imagen."
MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente."
MSG_HELP_ogGetLastSector="Devuelve el último sector usable del disco o de una partición."
MSG_HELP_ogGetMacAddress="Devuelve la dirección Ethernet del cliente."
MSG_HELP_ogGetMountImageDir="Devuelve el directorio de montaje de una imagen."
MSG_HELP_ogGetMountPoint="Devuelve el directorio donde está montado un sistema de archivos local."
MSG_HELP_ogGetNetInterface=""
MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado."
MSG_HELP_ogGetOsUuid=""
MSG_HELP_ogGetOsVersion="Devuelve el tipo y la versión de un sistema operativo instalado."
MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnsys."
MSG_HELP_ogGetPartitionActive="Indica cual es la partición marcada como activa en un disco."
MSG_HELP_ogGetPartitionId="Devuelve el identificador de tipo de una partición."
MSG_HELP_ogGetPartitionSize="Devuelve el tamaño de una partición."
MSG_HELP_ogGetPartitionsNumber=""
MSG_HELP_ogGetPartitionTableType="Devuelve el tipo de tabla de particiones del disco"
MSG_HELP_ogGetPartitionType="Devuelve el mnemónico de tipo de una partición."
MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnsys."
MSG_HELP_ogGetRegistryValue="Devuelve el dato de un valor del registro de Windows."
MSG_HELP_ogGetRepoIp="Devuelve la dirección IP del repositorio de datos."
MSG_HELP_ogGetSerialNumber="Devuelve el número de serie del cliente."
MSG_HELP_ogGetServerIp="Devuelve la dirección IP del servidor principal."
MSG_HELP_ogGetSizeParameters="Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido."
MSG_HELP_ogGetWindowsName="Devuelve el nombre del cliente guardado en el registro de Windows."
MSG_HELP_ogGrubAddOgLive="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys."
MSG_HELP_ogGrubDefaultEntry="Configura la entrada por defecto de GRUB."
MSG_HELP_ogGrubDeleteEntry="Borra en el grub del MBR las entradas para el inicio en una particion."
MSG_HELP_ogGrubHidePartitions="Configura el grub del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)."
MSG_HELP_ogGrubInstallMbr="Instal·la el carregador d'arrencada GRUB al MBR del primer disc dur"
MSG_HELP_ogGrubInstallPartition="Instal·la el carregador d'arrencada BURG al BootSector"
MSG_HELP_ogGrubOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de GRUB."
MSG_HELP_ogGrubSecurity="Configura usuario y clave para modificar las entradas del menu del Grub."
MSG_HELP_ogGrubUefiConf="Genera el fichero grub.cfg de la partición EFI."
MSG_HELP_ogHelp="Muestra mensajes de ayudas para las funciones."
MSG_HELP_ogHidePartition="Oculta una partición de Windows."
MSG_HELP_ogIdToType="Devuelve el mnemónico asociado al identificador de tipo de partición."
MSG_HELP_ogNvramActiveEntry="Configura a activa entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramAddEntry="Crea nueva entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramDeleteEntry="Borra entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramGetCurrent="Muestra la entrada del gestor de arranque (NVRAM) que ha iniciado el equipo."
MSG_HELP_ogNvramGetNext="Muestra la entrada del gestor de arranque (NVRAM) que se utilizará en el próximo arranque."
MSG_HELP_ogNvramGetOrder="Muestra el orden de las entradas del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramGetTimeout="Muestra el tiempo de espera del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramInactiveEntry="Configura a inactiva entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramList="Lista las entradas del gestor de arranque (NVRAN) marcando con un asterisco las activas"
MSG_HELP_ogNvramSetNext="Configura el próximo arranque con la entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramSetOrder="Configura el orden de las entradas del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramSetTimeout="Configura el tiempo de espera del gestor de arranque (NVRAM)."
MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado."
MSG_HELP_ogInstallFirstBoot="Crea un archivo que se ejecutará en el primer arranque de Windows."
MSG_HELP_ogInstallLaunchDaemon="Instala un archivo que se ejecutará en el arranque de macOS."
MSG_HELP_ogInstallLinuxClient=MSG_OBSOLETE
MSG_HELP_ogInstallMiniSetup="Instala un archivo que se ejecutará en el arranque de Windows."
MSG_HELP_ogInstallRunonce="Crea un archivo que se ejecutará en el inicio de un usuario administrador de Windows."
MSG_HELP_ogInstallWindowsClient=MSG_OBSOLETE
MSG_HELP_ogIsFormated="Comprueba si un sistema de archivos está formateado."
MSG_HELP_ogIsImageLocked="Comprueba si una imagen está bloqueada por una operación de uso exclusivo."
MSG_HELP_ogIsLocked="Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo."
MSG_HELP_ogIsDiskLocked="Comprueba si un disco está bloqueado por una operación de uso exclusivo."
MSG_HELP_ogIsMounted="Comprueba si un sistema de archivos está montado."
MSG_HELP_ogIsNewerFile="Comprueba si un fichero es más nuevo (se ha modificado después) que otro."
MSG_HELP_ogIsPartitionLocked=MSG_HELP_ogIsLocked
MSG_HELP_ogIsRepoLocked=""
MSG_HELP_ogIsSyncImage="Comprueba si la imagen es sincronizable."
MSG_HELP_ogIsVirtualMachine=""
MSG_HELP_ogIsWritable="Comprueba si un sistema de archivos está montado con permiso de escritura."
MSG_HELP_ogLinuxBootParameters="Devuelve los parámetros de arranque de un sistema operativo Linux instalado."
MSG_HELP_ogListHardwareInfo="Lista el inventario de dispositivos del cliente."
MSG_HELP_ogListLogicalPartitions=""
MSG_HELP_ogListPartitions="Lista la estructura de particiones de un disco."
MSG_HELP_ogListPrimaryPartitions=""
MSG_HELP_ogListRegistryKeys="Lista los nombres de las subclaves incluidas en una clave del registro de Windows."
MSG_HELP_ogListRegistryValues="Lista los nombres de los valores incluidos en una clave del registro de Windows."
MSG_HELP_ogListSoftware="Lista el inventario de programas instalados en un sistema operativo."
MSG_HELP_ogLock="Bloquea una partición para operación de uso exclusivo."
MSG_HELP_ogLockDisk="Bloquea un disco para operación de uso exclusivo."
MSG_HELP_ogLockImage="Bloquea una imagen para operación de uso exclusivo."
MSG_HELP_ogLockPartition=MSG_HELP_ogLock
MSG_HELP_ogMakeChecksumFile="Almacena la suma de comprobación de un fichero."
MSG_HELP_ogMakeDir="Crea un directorio para OpenGnsys."
MSG_HELP_ogMakeGroupDir="Crea el directorio de grupo (aula) en un repositorio."
MSG_HELP_ogMcastReceiverFile=""
MSG_HELP_ogMcastReceiverPartition=""
MSG_HELP_ogMcastRequest=""
MSG_HELP_ogMcastSendFile=""
MSG_HELP_ogMcastSendPartition=""
MSG_HELP_ogMcastSyntax=""
MSG_HELP_ogMountCache="Monta el sistema de archivos dedicado a caché local."
MSG_HELP_ogMountCdrom="Monta dispositivo óptico por defecto."
MSG_HELP_ogMountImage="Monta una imagen sincronizable"
MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje."
MSG_HELP_ogMountFs=MSG_HELP_ogMount
MSG_HELP_ogNvramActiveEntry="Configura a activa entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramAddEntry="Crea nueva entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramDeleteEntry="Borra entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramGetCurrent="Muestra la entrada del gestor de arranque (NVRAM) que ha iniciado el equipo."
MSG_HELP_ogNvramGetNext="Muestra la entrada del gestor de arranque (NVRAM) que se utilizará en el próximo arranque."
MSG_HELP_ogNvramGetOrder="Muestra el orden de las entradas del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramGetTimeout="Muestra el tiempo de espera del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramInactiveEntry="Configura a inactiva entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramList="Lista las entradas del gestor de arranque (NVRAN) marcando con un asterisco las activas"
MSG_HELP_ogNvramPxeFirstEntry="Configura la tarjeta de red como primer arranque en la NVRAM."
MSG_HELP_ogNvramSetNext="Configura el próximo arranque con la entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramSetOrder="Configura el orden de las entradas del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramSetTimeout="Configura el tiempo de espera del gestor de arranque (NVRAM)."
MSG_HELP_ogRaiseError="Muestra y registra mensajes de error y devuelve el código correspondiente."
MSG_HELP_ogReduceFs="Reduce el tamaño del sistema de archivos al mínimo ocupado por sus datos."
MSG_HELP_ogReduceImage="Reduce el tamaño de la imagen"
MSG_HELP_ogRefindDeleteEntry="Borra en rEFInd las entradas para el inicio en una particion."
MSG_HELP_ogRefindDefaultEntry="Configura la entrada por defecto de rEFInd."
MSG_HELP_ogRefindOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de rEFInd."
MSG_HELP_ogRefindSetTheme="Asigna un tema al rEFInd."
MSG_HELP_ogRefindSetTimeOut="Define el tiempo (segundos) que se muestran las opciones de inicio de rEFInd."
MSG_HELP_ogRefindSetResolution="Define la resolución que usuará el thema del gestor de arranque rEFInd."
MSG_HELP_ogRefindInstall="Instala y configura el gestor rEFInd en la particion EFI"
MSG_HELP_ogRestoreAclImage=""
MSG_HELP_ogRestoreBootLoaderImage=""
MSG_HELP_ogRestoreDiskImage="Restaura una imagen de un disco completo."
MSG_HELP_ogRestoreEfiBootLoader="Copia el cargador de arranque de la partición de sistema a la partición EFI."
MSG_HELP_ogRestoreImage="Restaura una imagen de sistema operativo."
MSG_HELP_ogRestoreInfoImage="Restablece informacion del sistema: acl y enlaces simbolicos"
MSG_HELP_ogRestoreMbrImage="Restaura una imagen del sector de arranque (MBR)."
MSG_HELP_ogRestoreUuidPartitions="Restaura los uuid de las particiones y la tabla de particiones."
MSG_HELP_ogSaveImageInfo="Crea un fichero con la información de la imagen."
MSG_HELP_ogSetLinuxName=""
MSG_HELP_ogSetPartitionActive="Establece el número de partición activa de un disco."
MSG_HELP_ogSetPartitionId="Modifica el tipo de una partición física usando el mnemónico del tipo."
MSG_HELP_ogSetPartitionSize="Establece el tamaño de una partición."
MSG_HELP_ogSetPartitionType="Modifica el identificador de tipo de una partición física."
MSG_HELP_ogSetRegistryValue="Asigna un dato a un valor del registro de Windows."
MSG_HELP_ogSetWindowsName="Asigna el nombre del cliente en el registro de Windows."
MSG_HELP_ogSetWinlogonUser="Asigna el nombre de usuario por defecto para el gestor de entrada de Windows."
MSG_HELP_ogSyncCreate="Sincroniza los datos de la particion a la imagen"
MSG_HELP_ogSyncRestore="Sincroniza los datos de la imagen a la particion"
MSG_HELP_ogTorrentStart=""
MSG_HELP_ogTypeToId="Devuelve el identificador asociado al mnemónico de tipo de partición."
MSG_HELP_ogUcastReceiverPartition=""
MSG_HELP_ogUcastSendFile=""
MSG_HELP_ogUcastSendPartition=""
MSG_HELP_ogUcastSyntax=""
MSG_HELP_ogUnhidePartition="Hace visible una partición de Windows."
MSG_HELP_ogUninstallLinuxClient="Desinstala el cliente OpenGnSys en un sistema operativo Linux."
MSG_HELP_ogUninstallWindowsClient="Desinstala el cliente OpenGnSys en un sistema operativo Windows."
MSG_HELP_ogUnlock="Desbloquea una partición tras finalizar una operación de uso exclusivo."
MSG_HELP_ogUnlockDisk="Desbloquea un disco tras finalizar una operación de uso exclusivo."
MSG_HELP_ogUnlockImage="Desbloquea una imagen tras finalizar una operación de uso exclusivo."
MSG_HELP_ogUnlockPartition=MSG_HELP_ogUnlock
MSG_HELP_ogUnmountAll="Desmonta todos los sistemas de archivos."
MSG_HELP_ogUnmountCache="Desmonta el sistema de archivos de caché local."
MSG_HELP_ogUnmount="Desmonta un sistema de archivos."
MSG_HELP_ogUnmountImage="Desmonta la imagen"
MSG_HELP_ogUnmountFs=MSG_HELP_ogUnmount
MSG_HELP_ogUnsetDirtyBit=""
MSG_HELP_ogUpdateCacheIsNecesary="Comprueba si es necesario actualizar una archivo en la cache local."
MSG_HELP_ogUpdatePartitionTable="Actualiza informacion tabla particiones del disco"
MSG_HELP_ogUuidChange="Reemplaza el UUID de un sistema de ficheros."
MSG_HELP_ogWaitSyncImage=""
MSG_HELP_ogWindowsBootParameters=""
MSG_HELP_ogWindowsRegisterPartition=""
# Scripts
MSG_HELP_configureOs="Post-configura de arranque del sistema"
MSG_HELP_createBaseImage="Genera imagen basica de la particion"
MSG_HELP_createDiffImage="Genera imagen diferencial de la particion respecto a la imagen basica"
MSG_HELP_installOfflineMode="Prepara el equipo cliente para el modo offline."
MSG_HELP_partclone2sync="Convierte imagen de partclone en imagen sincronizable."
MSG_HELP_restoreBaseImage="Restaura una imagen basica en una particion"
MSG_HELP_restoreDiffImage="Restaura una imagen diferencial en una particion"
MSG_HELP_updateCache="Realiza la actualizacion de la cache"
# Mensajes de descripción breve de la interfaz.
MSG_INTERFACE_START="[START Interface] Ejecutar comando: "
MSG_INTERFACE_END="[END Interface] Comando terminado con este código: "
# Mensajes de scripts.
MSG_SCRIPTS_START=" INICIO scripts : "
MSG_SCRIPTS_END=" FIN scripts: "
MSG_SCRIPTS_TASK_END="Fin de la tarea"
MSG_SCRIPTS_TASK_SLEEP="Esperando para iniciar"
MSG_SCRIPTS_TASK_START="Iniciando"
MSG_SCRIPTS_TASK_ERR="Error"
# Script createImage.
MSG_SCRIPTS_FILE_RENAME=" Renombrar fichero-imagen previo: "
MSG_SCRIPTS_CREATE_SIZE=" Calcular espacio (KB) requerido para almacenarlo y el disponible: "
# Script updateCache.
MSG_SCRIPTS_UPDATECACHE_DOUPDATE="comprovar si es necessari actualitzar el fitxer imatge"
MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE="Comprobar que el tamaño de la cache es mayor que el fichero a descargar."
# Script updateCache: para las imágenes sincronizadas tipo dir.
MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calculamos el tamaño de la imagen."
MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Comprobamos si hay que la imagen del repositorio es mayor que la de la cache."
MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Comprobar el espacio libre de la cache y actuar según engine.cfg"
MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesion multicast: ServidorMcast:PuertoDatos"
# interface sustituye temporalmente al scritp restore
MSG_SCRIPTS_CHECK_ENGINE="Analizar proceso a realizar según engine.cfg"
MSG_SCRIPTS_MULTICAST_PRECHECK_PORT="Determinar puerto principal y auxiliar multicast."
MSG_SCRIPTS_MULTICAST_CHECK_PORT="Comprobar puertos de sesion y datos"
MSG_SCRIPTS_MULTICAST_REQUEST_PORT="Solicitar la apertura: "
MSG_SCRIPTS_OS_CONFIGURE="Iniciar la configuracion del sistema restaurado"
# TIME MESSAGES
MSG_SCRIPTS_TIME_TOTAL="tiempo total del proceso"
MSG_SCRIPTS_TIME_PARTIAL="tiempo parcial del subproceso"
# HTTPLOG
MSG_HTTPLOG_NOUSE="No apague este ordenador por favor"
# Mensajes sincronizadas
MSG_SYNC_RESIZE="Redimensiona la imagen al tamaño necesario"
MSG_SYNC_RESTORE="Trae el listado ficheros y baja la imagen"
MSG_SYNC_DELETE="Diferencial: Borra archivos antiguos"
MSG_SYNC_SLEEP="Espera que se monte/reduzca la imagen"
# Mensajes sincronizadas complementarios a errores
MSG_SYNC_DIFFERENTFS="El sistema de ficheros de destino no coincide con el de la imagen"
MSG_SYNC_EXTENSION="Las extensiones de la imagenes deben ser img o diff"
MSG_SYNC_NOCHECK="La imagen esta montada por otro proceso, no podemos comprobarla"
MSG_RESTORE="Restaura la imagen en"

View File

@ -0,0 +1,387 @@
#!/usr/bin/python3
# English language file.
#@version 1.1.0
#@author Jose Miguel Hernandez - Universidad de Salamanca
#@date 2018-03-01
# Error messages.
MSG_ERR_GENERIC="Undefined unknown error"
MSG_ERR_FORMAT="Wrong execution format"
MSG_ERR_OUTOFLIMIT="Out of range or invalid value"
MSG_ERR_NOTFOUND="File or device not found"
MSG_ERR_PARTITION="Unknown or wrong partition"
MSG_ERR_LOCKED="Resource locked by exclusive use operation"
MSG_ERR_CACHE="Local cache error"
MSG_ERR_NOGPT="Current disk does not include GPT partition"
MSG_ERR_REPO="Failed when mounting images repository"
MSG_ERR_NOMSDOS="Current disk does not include MSDOS partition"
MSG_ERR_FILESYS="Unknown or unmountable file system"
MSG_ERR_NOTOS="Cannot detect or boot OS"
MSG_ERR_IMAGE="Cannot create or restore a system image"
MSG_ERR_IMAGEFILE="Image file corrupt or of other partclone version"
MSG_ERR_NOTEXEC="Non executable program or function"
MSG_ERR_NOTWRITE="Write access denied"
MSG_ERR_NOTCACHE="No client cache partition"
MSG_ERR_NOTUEFI="UEFI isn't active"
MSG_ERR_NOTBIOS="BIOS legacy isn't active"
MSG_ERR_CACHESIZE="Not enough space in local or remote cache"
MSG_ERR_REDUCEFS="Error when reducing file system"
MSG_ERR_EXTENDFS="Error when expanding file system"
MSG_ERR_IMGSIZEPARTITION="Backup error: Partition smaller than image"
MSG_ERR_UPDATECACHE="Error when running `updateCache´ command"
MSG_ERR_UCASTSYNTAXT="Error when generating Unicast transfer syntax"
MSG_ERR_UCASTSENDPARTITION="Error when sending a Unicast partition"
MSG_ERR_UCASTSENDFILE="Error when sending a Unicast file"
MSG_ERR_UCASTRECEIVERPARTITION="Error when receiving an Unicast partition"
MSG_ERR_UCASTRECEIVERFILE="Error when receiving an Unicast file"
MSG_ERR_MCASTSYNTAXT="Error when generating Multicast transfer syntax"
MSG_ERR_MCASTSENDFILE="Error when sending Multicast file"
MSG_ERR_MCASTRECEIVERFILE="Error when receiving Multicast file"
MSG_ERR_MCASTSENDPARTITION="Error when sending Multicast partition"
MSG_ERR_MCASTRECEIVERPARTITION="Error when receiving Multicast partition "
MSG_ERR_PROTOCOLJOINMASTER="Error when connecting Unicast/Multicast session to Master"
MSG_ERR_DONTFORMAT="Formatting Error"
MSG_ERR_DONTMOUNT_IMAGE="Error when mounting/reducing image"
MSG_ERR_DONTUNMOUNT_IMAGE="Error when unmounting image"
MSG_ERR_DONTSYNC_IMAGE="Unsynchronizable image"
MSG_ERR_NOTDIFFERENT="Basic image identical to partition"
MSG_ERR_SYNCHRONIZING="Synchronizing error, it may affect image creation/restoration process"
# Warning messages.
MSG_DONTUSE="DO NOT USE"
MSG_DONTMOUNT="Unmounted file system"
MSG_DONTUNMOUNT="Cannot unmount file system or it isn't mounted"
MSG_MOUNT="File system already mounted"
MSG_MOUNTREADONLY="Read-only file system mounted"
MSG_OBSOLETE="OBSOLETE"
# Auxiliary help messages.
MSG_64BIT="64-bit"
MSG_DISK="Disk"
MSG_ERROR="Error"
MSG_EXAMPLE="Example"
MSG_FORMAT="Format"
MSG_FUNCTION="Function"
MSG_HARDWAREINVENTORY="Hardware inventory"
MSG_IMAGE="Image"
MSG_INSTALLED="Installed"
MSG_NOCACHE="No local cache"
MSG_NOEXTENDED="No extended partition"
MSG_PARTITION="Partition"
MSG_PROTOCOL="Protocol"
MSG_RESERVEDVALUE="Reserved value"
MSG_SEE="See"
MSG_UNKNOWN="Unknown"
MSG_WARNING="Warning"
# Boot process messages.
MSG_DETECTLVMRAID="Detecting LVM and RAID meta-devices."
MSG_ERRBOOTMODE=f"{MSG_ERROR}: Unknown boot mode."
MSG_LAUNCHCLIENT="Launching client browser."
MSG_LOADAPI="Loading cloning-engine functions."
MSG_LOADMODULES="Loading kernel modules."
MSG_MAKELINKS="Creating symbolic links."
MSG_MOUNTREPO="Mounting repository using %s by %s mode."
MSG_OFFLINEMODE="Off-line boot mode."
MSG_OTHERSERVICES="Starting client complementary services."
MSG_POWEROFFCONF="Defining power-saving parameters."
# Default menu messages.
MSG_BOOT="Boot"
MSG_DUPLEX="Duplex"
MSG_HOSTNAME="Hostname"
MSG_IPADDR="IP Address"
MSG_MACADDR="MAC Address"
MSG_MENUTITLE="Options menu"
MSG_POWEROFF="Shutdown computer"
MSG_SPEED="Speed"
# API functions messages.
MSG_HELP_ogAclFilter="Draws ACL files from differential image."
MSG_HELP_ogAddCmd="Adds commands to file created by ogInstalMiniSetup."
MSG_HELP_ogAddRegistryKey="Adds new Windows registry key."
MSG_HELP_ogAddRegistryValue="Adds new Windows registry value."
MSG_HELP_ogAddToLaunchDaemon=""
MSG_HELP_ogBoot="Boots installed OS."
MSG_HELP_ogBootLoaderDeleteEntry=MSG_DONTUSE
MSG_HELP_ogBootLoaderHidePartitions=MSG_DONTUSE
MSG_HELP_ogBootMbrGeneric=""
MSG_HELP_ogBootMbrXP=""
MSG_HELP_ogBurgDefaultEntry="Sets default Burg entry."
MSG_HELP_ogBurgDeleteEntry="Deletes partition start-entries from MBR BURG."
MSG_HELP_ogBurgHidePartitions="Sets MBR Burg to hide non starting windows partitions. Allows you to select a partition that will not be hidden (e.g. for data)."
MSG_HELP_ogBurgInstallMbr="Installs BURG boot-loader on 1st HD MBR."
MSG_HELP_ogBurgOgliveDefaultEntry="Sets ogLive input as default Burg input."
MSG_HELP_ogCalculateChecksum="Calculates file checksum."
MSG_HELP_ogCalculateFullChecksum="Calculates file full checksum"
MSG_HELP_ogChangeRepo="Changes repository for remote resource: images."
MSG_HELP_ogCheckFs="Checks file system consistence."
MSG_HELP_ogCheckIpAddress=""
MSG_HELP_ogCheckProgram=""
MSG_HELP_ogCheckStringInGroup=""
MSG_HELP_ogCheckStringInReg=""
MSG_HELP_ogCheckSyncImage="Displays image contents to check it."
MSG_HELP_ogCleanLinuxDevices=""
MSG_HELP_ogCleanOs="Deletes OS unnecessary files."
MSG_HELP_ogCompareChecksumFiles="Compares if the checksums match."
MSG_HELP_ogConfigureFstab=""
MSG_HELP_ogConfigureOgagent="Sets OS new agent: OGAgent."
MSG_HELP_ogCopyFile="Copies file to another storage unit ."
MSG_HELP_ogCreateBootLoaderImage=""
MSG_HELP_ogCreateCache="Saves space for cache partition at the end of disk."
MSG_HELP_ogCreateDiskImage="Creates exact image from local disk."
MSG_HELP_ogCreateFileImage="Creates/Resizes synchronized image file."
MSG_HELP_ogCreateGptPartitions=""
MSG_HELP_ogCreateImage="Creates exact image from local installed OS."
MSG_HELP_ogCreateImageSyntax=""
MSG_HELP_ogCreateInfoImage="Creates image content information."
MSG_HELP_ogCreateMbrImage="Creates MBR image."
MSG_HELP_ogCreatePartitions="Creates disk partition table."
MSG_HELP_ogCreatePartitionTable="Creates partition table, if necessary."
MSG_HELP_ogCreateTorrent=""
MSG_HELP_ogCopyEfiBootLoader="Copy the boot loader from the EFI partition to system partition."
MSG_HELP_ogDeleteCache="Deletes local cache partition."
MSG_HELP_ogDeleteFile="Deletes file from storage."
MSG_HELP_ogDeletePartitionTable="Deletes disk table partition"
MSG_HELP_ogDeleteRegistryKey="Deletes empty Windows registry key."
MSG_HELP_ogDeleteRegistryValue="Deletes Windows registry value."
MSG_HELP_ogDeleteTree="Deletes directory tree."
MSG_HELP_ogDevToDisk="Returns disk or partition ordinal number for device file path."
MSG_HELP_ogDiskToDev="Returns device file path for disk or partition ordinal number."
MSG_HELP_ogDomainScript=""
MSG_HELP_ogEcho="Displays and log messages."
MSG_HELP_ogExecAndLog="Runs and logs command"
MSG_HELP_ogExtendFs="Expands file system size to partition maximum."
MSG_HELP_ogFindCache="Shows local cache reserved partition."
MSG_HELP_ogFixBootSector=""
MSG_HELP_ogFormatCache="Formats (clears) local cache."
MSG_HELP_ogFormat="Formats file system."
MSG_HELP_ogFormatFs=MSG_HELP_ogFormat
MSG_HELP_ogGetArch="Returns client architecture."
MSG_HELP_ogGetCacheSize="Returns local cache partition size."
MSG_HELP_ogGetCacheSpace="Returns maximum available space that can be reserved for local cache partition."
MSG_HELP_ogGetCaller="Returns program or function which is calling to current one"
MSG_HELP_ogGetDiskSize="Returns disk size."
MSG_HELP_ogGetDiskType="Returns disk type."
MSG_HELP_ogGetFreeSize=""
MSG_HELP_ogGetFsSize="Returns file system size."
MSG_HELP_ogGetFsType="Returns file system type."
MSG_HELP_ogGetGroupDir="Returns default directory path for client group."
MSG_HELP_ogGetGroupName="Returns client group name."
MSG_HELP_ogGetHivePath="Returns full path of file from Windows registry section."
MSG_HELP_ogGetHostname="Returns local hostname."
MSG_HELP_ogGetImageCompressor="Returns image compression tool."
MSG_HELP_ogGetImageInfo="Displays monolithic image information: cloning; compressor; file system; size(KB)."
MSG_HELP_ogGetImageProgram="Returns used program to create image."
MSG_HELP_ogGetImageSize="Returns system image size."
MSG_HELP_ogGetImageType="Returns image file system."
MSG_HELP_ogGetIpAddress="Returns client IP."
MSG_HELP_ogGetLastSector="Returns last available sector from disk or partition."
MSG_HELP_ogGetMacAddress="Returns client Ethernet address."
MSG_HELP_ogGetMountImageDir="Returns mounting directory of image."
MSG_HELP_ogGetMountPoint="Returns directory of local file system mount point."
MSG_HELP_ogGetNetInterface=""
MSG_HELP_ogGetOsType="Returns installed OS type."
MSG_HELP_ogGetOsUuid="Returns OS UUID"
MSG_HELP_ogGetOsVersion="Returns OS version."
MSG_HELP_ogGetParentPath="Returns full path of OpenGnsys system file parent directory."
MSG_HELP_ogGetPartitionActive="Returns disk active partition."
MSG_HELP_ogGetPartitionId="Returns partition type ID."
MSG_HELP_ogGetPartitionSize="Returns partition size."
MSG_HELP_ogGetPartitionsNumber="Returns disk partitions number."
MSG_HELP_ogGetPartitionTableType="Returns disk partition table type."
MSG_HELP_ogGetPartitionType="Returns partition type."
MSG_HELP_ogGetPath="Returns full path of OpenGnsys system file."
MSG_HELP_ogGetRegistryValue="Returns data from Windows registry value."
MSG_HELP_ogGetRepoIp="Returns OpenGnsys Repository IP address ."
MSG_HELP_ogGetSerialNumber="Returns host serial number."
MSG_HELP_ogGetServerIp="Returns main OpenGnsys Server IP address."
MSG_HELP_ogGetSizeParameters="Returns file system data size, required space for image and if it fits in the chosen repository."
MSG_HELP_ogGetWindowsName="Returns saved client name on Windows registry."
MSG_HELP_ogGrubAddOgLive="Adds MBR grub an entry calling Opengnsys client."
MSG_HELP_ogGrubDefaultEntry="Sets GRUB default entry."
MSG_HELP_ogGrubDeleteEntry="Deletes partition start entries on MBR grub."
MSG_HELP_ogGrubHidePartitions="Sets MBR grub to hide non starting Windows partitions. Allows you to select a partition that will not be hidden (e.g. for data)."
MSG_HELP_ogGrubInstallMbr="Installs GRUB boot loader on 1st HD MBR"
MSG_HELP_ogGrubInstallPartition="Installs GRUB boot loader on BootSector"
MSG_HELP_ogGrubOgliveDefaultEntry="Sets ogLive entry as default GRUB entry."
MSG_HELP_ogGrubSecurity="Configures user and password for change the menu entries of grub."
MSG_HELP_ogGrubUefiConf="Generates the grub.cfg file of the EFI partition."
MSG_HELP_ogHelp="Shows functions help messages."
MSG_HELP_ogHidePartition="Hides Windows partition."
MSG_HELP_ogIdToType="Returns partition type identifier."
MSG_HELP_ogInstallFirstBoot="Creates file to run on first Windows boot."
MSG_HELP_ogInstallLaunchDaemon="Installs file to run on MACos boot."
MSG_HELP_ogInstallLinuxClient=MSG_OBSOLETE
MSG_HELP_ogInstallMiniSetup="Installs file to run on Windows boot."
MSG_HELP_ogInstallRunonce="Creates file to run on admin-user Windows boot."
MSG_HELP_ogInstallWindowsClient=MSG_OBSOLETE
MSG_HELP_ogIsFormated="Checks file system if formatted."
MSG_HELP_ogIsImageLocked="Checks image if blocked by exclusive use operation."
MSG_HELP_ogIsLocked="Checks partition or disk if blocked by exclusive use operation."
MSG_HELP_ogIsDiskLocked="Checks disk if blocked by exclusive use operation."
MSG_HELP_ogIsMounted="Checks file system if mounted."
MSG_HELP_ogIsNewerFile="Checks if one file is newer (or has been modified later) than another one."
MSG_HELP_ogIsPartitionLocked=MSG_HELP_ogIsLocked
MSG_HELP_ogIsRepoLocked=""
MSG_HELP_ogIsSyncImage="Checks image if synchronizable."
MSG_HELP_ogIsVirtualMachine="Checks if client is a virtual machine"
MSG_HELP_ogIsWritable="Checks if mounted file system has write permissions."
MSG_HELP_ogLinuxBootParameters="Returns installed Linux boot parameters."
MSG_HELP_ogListHardwareInfo="Lists the client hardware inventory."
MSG_HELP_ogListLogicalPartitions="Lists disk logic partitions."
MSG_HELP_ogListPartitions="Lists disk partitions table."
MSG_HELP_ogListPrimaryPartitions="Lists disk primary partitions"
MSG_HELP_ogListRegistryKeys="Lists sub-keys names included on a Windows registry key."
MSG_HELP_ogListRegistryValues="Lists value names included on a Windows registry key."
MSG_HELP_ogListSoftware="Lists OS installed programs inventory."
MSG_HELP_ogLock="Blocks partition for exclusive use operation."
MSG_HELP_ogLockDisk="Blocks disk for exclusive use operation."
MSG_HELP_ogLockImage="Blocks image for exclusive use operation."
MSG_HELP_ogLockPartition=MSG_HELP_ogLock
MSG_HELP_ogMakeChecksumFile="Stores file checksum."
MSG_HELP_ogMakeDir="Makes OpenGnsys directory."
MSG_HELP_ogMakeGroupDir="Makes group (lab) directory on repository."
MSG_HELP_ogMcastReceiverFile=""
MSG_HELP_ogMcastReceiverPartition=""
MSG_HELP_ogMcastRequest=""
MSG_HELP_ogMcastSendFile=""
MSG_HELP_ogMcastSendPartition=""
MSG_HELP_ogMcastSyntax=""
MSG_HELP_ogMountCache="Mounts cache file system."
MSG_HELP_ogMountCdrom="Mounts default optical drive."
MSG_HELP_ogMountImage="Mounts synchronizable image"
MSG_HELP_ogMount="Mounts file system and returns mount point."
MSG_HELP_ogMountFs=MSG_HELP_ogMount
MSG_HELP_ogNvramActiveEntry="Sets active a bootloader (NVRAM) entry."
MSG_HELP_ogNvramAddEntry="Creates new entry in bootloader (NVRAM)."
MSG_HELP_ogNvramDeleteEntry="Deletes a bootloader (NVRAM) entry."
MSG_HELP_ogNvramGetCurrent="Displays the bootloader (NVRAM) entry that was started by the computer."
MSG_HELP_ogNvramGetNext="Displays the bootloader (NVRAM) entry for the boot next."
MSG_HELP_ogNvramGetOrder="Displays the bootloader (NVRAM) entries order."
MSG_HELP_ogNvramGetTimeout="Displays the bootloader (NVRAM) timeout."
MSG_HELP_ogNvramInactiveEntry="Sets inactive bootloader (NVRAM) entry."
MSG_HELP_ogNvramList="Lists bootloader (NVRAM) entries, by staring actives ones."
MSG_HELP_ogNvramPxeFirstEntry="Set the network as the NVRAM first boot."
MSG_HELP_ogNvramSetNext="Set the bootloader (NVRAM) entry for the boot next."
MSG_HELP_ogNvramSetOrder="Sets the bootloader (NVRAM) entries order."
MSG_HELP_ogNvramSetTimeout="Sets the bootloader (NVRAM) timeout."
MSG_HELP_ogRaiseError="Displays and registers error messages and returns code."
MSG_HELP_ogReduceFs="Reduces file system size to minimum."
MSG_HELP_ogReduceImage="Reduces image size."
MSG_HELP_ogRefindDeleteEntry="Deletes the menu entry of a partition in rEFInd."
MSG_HELP_ogRefindDefaultEntry="Configures default menu entry in rEFInd."
MSG_HELP_ogRefindOgliveDefaultEntry="Configures ogLive menu entry as default menu entry in rEFInd."
MSG_HELP_ogRefindSetTheme="Configures rEFInd's theme."
MSG_HELP_ogRefindSetTimeOut="Defines the time that rEFInd shows the menu."
MSG_HELP_ogRefindSetResolution="Defines the resolucion of rEFInd's theme."
MSG_HELP_ogRefindInstall="Installs and configures rEFInd boot loader in ESP."
MSG_HELP_ogRestoreAclImage="Restores Windows ACL (Inf. must be on /tmp)."
MSG_HELP_ogRestoreBootLoaderImage=""
MSG_HELP_ogRestoreDiskImage="Restores disk image."
MSG_HELP_ogRestoreEfiBootLoader="Copy the boot loader from the system partition to the EFI partition."
MSG_HELP_ogRestoreImage="Restore OS image."
MSG_HELP_ogRestoreInfoImage="Restores system information: ACL and symbolic links"
MSG_HELP_ogRestoreMbrImage="Restores boot sector image (MBR)."
MSG_HELP_ogRestoreUuidPartitions="Restores UUID of partitions and partition table."
MSG_HELP_ogSaveImageInfo="Creates the image information file."
MSG_HELP_ogSetLinuxName=""
MSG_HELP_ogSetPartitionActive="Sets active partition number of disk."
MSG_HELP_ogSetPartitionId="Changes partition ID using mnemonic."
MSG_HELP_ogSetPartitionSize="Sets partition size."
MSG_HELP_ogSetPartitionType="Changes partition type ID."
MSG_HELP_ogSetRegistryValue="Assigns data to a Windows registry values."
MSG_HELP_ogSetWindowsName="Assigns client name to Windows registry."
MSG_HELP_ogSetWinlogonUser="Assigns Windows default user name to Windows input manager."
MSG_HELP_ogSyncCreate="Synchronizes partition data to image"
MSG_HELP_ogSyncRestore="Synchronize image data to partition"
MSG_HELP_ogTorrentStart=""
MSG_HELP_ogTypeToId="Returns the ID of partition type mnemonic."
MSG_HELP_ogUcastReceiverPartition=""
MSG_HELP_ogUcastSendFile=""
MSG_HELP_ogUcastSendPartition=""
MSG_HELP_ogUcastSyntax=""
MSG_HELP_ogUnhidePartition="Unhides Windows partition."
MSG_HELP_ogUninstallLinuxClient="Uninstalls old OpenGnSys agent from Linux OS."
MSG_HELP_ogUninstallWindowsClient="Uninstalls oldOpenGnSys agent from Windows OS."
MSG_HELP_ogUnlock="Unlocks partition after exclusive use operation."
MSG_HELP_ogUnlockDisk="Unlocks disk after exclusive use operation."
MSG_HELP_ogUnlockImage="Unlocks image after exclusive use operation."
MSG_HELP_ogUnlockPartition=MSG_HELP_ogUnlock
MSG_HELP_ogUnmountAll="Unmounts all file systems."
MSG_HELP_ogUnmountCache="Unmounts cache file system."
MSG_HELP_ogUnmountImage="Unmounts image"
MSG_HELP_ogUnmount="Unmounts file system."
MSG_HELP_ogUnmountFs=MSG_HELP_ogUnmount
MSG_HELP_ogUnsetDirtyBit=""
MSG_HELP_ogUpdateCacheIsNecesary="Checks if necessary file update in local cache."
MSG_HELP_ogUpdatePartitionTable="Updates disk partition table info "
MSG_HELP_ogUuidChange="Replaces the filesystem UUID"
MSG_HELP_ogWaitSyncImage=""
MSG_HELP_ogWindowsBootParameters=""
MSG_HELP_ogWindowsRegisterPartition=""
# Scripts
MSG_HELP_configureOs="Post-configure system boot"
MSG_HELP_createBaseImage="Create partition basic image"
MSG_HELP_createDiffImage="Create partition differential image from basic image"
MSG_HELP_installOfflineMode="Prepare client for off-line mode."
MSG_HELP_partclone2sync="Turn part-clone image into synchronizable image."
MSG_HELP_restoreBaseImage="Restore basic image into partition"
MSG_HELP_restoreDiffImage="Restore differential image into partition"
MSG_HELP_updateCache="Update cache"
# INTERFACE functions messages.
MSG_INTERFACE_START="[START Interface] Run command: "
MSG_INTERFACE_END="[END Interface] Command finished with this code: "
# SCRIPTS messages.
MSG_SCRIPTS_START=" START scripts: "
MSG_SCRIPTS_END=" END scripts: "
MSG_SCRIPTS_TASK_END="End of task"
MSG_SCRIPTS_TASK_SLEEP="Waiting to start"
MSG_SCRIPTS_TASK_START="Starting"
MSG_SCRIPTS_TASK_ERR="Error"
# createImage script
MSG_SCRIPTS_FILE_RENAME="Rename previous image-file: "
MSG_SCRIPTS_CREATE_SIZE="Check required and available storing space(KB): "
# updateCache script
MSG_SCRIPTS_UPDATECACHE_DOUPDATE="Check if it is necessary to update image file"
MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE="Check if Cache size is bigger than image file size."
# Script updateCache: for dir synchronized images .
MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calculate image size."
MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Check if repository image file size is bigger than Cache size."
MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Check free Cache and apply engine.cfg"
MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Checking Multicast Session McastServer:DataPort"
# interface temporarily replaces restore script
MSG_SCRIPTS_CHECK_ENGINE="Analyze process to carry out according to engine.cfg"
MSG_SCRIPTS_MULTICAST_PRECHECK_PORT="Check main and auxiliary Multicast port."
MSG_SCRIPTS_MULTICAST_CHECK_PORT="Check session and data ports"
MSG_SCRIPTS_MULTICAST_REQUEST_PORT="Request Multicast port opening: "
MSG_SCRIPTS_OS_CONFIGURE="Start restored system setting"
# TIME MESSAGES
MSG_SCRIPTS_TIME_TOTAL="Total process time"
MSG_SCRIPTS_TIME_PARTIAL="Partial sub-process time"
# HTTPLOG
MSG_HTTPLOG_NOUSE="PLEASE DO NOT TURN OFF THIS COMPUTER"
# Messages for synchronized images (complementary to errors)
MSG_SYNC_RESIZE="Resize image to necessary size"
MSG_SYNC_RESTORE="Get files list and download image"
MSG_SYNC_DELETE="Differential: Delete old files"
MSG_SYNC_SLEEP="Wait for mounting/reducing image"
# Messages for synchronized images (complementary to errors)
MSG_SYNC_DIFFERENTFS="Destination file system does not match image"
MSG_SYNC_EXTENSION="Image extension must be img or diff"
MSG_SYNC_NOCHECK="Image mounted by another process. Cannot verify it"
MSG_RESTORE="Restore image on "

View File

@ -0,0 +1,387 @@
#!/usr/bin/python3
# Fichero de idioma: español.
#@version 1.1.1
#@author
# Mensajes de error.
MSG_ERR_GENERIC="Error imprevisto no definido"
MSG_ERR_FORMAT="Formato de ejecución incorrecto"
MSG_ERR_OUTOFLIMIT="Valor fuera de rango o no válido"
MSG_ERR_NOTFOUND="Fichero o dispositivo no encontrado"
MSG_ERR_PARTITION="Partición errónea o desconocida"
MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo"
MSG_ERR_CACHE="Error en partición de caché local"
MSG_ERR_NOGPT="El disco indicado no contiene una partición GPT"
MSG_ERR_REPO="Error al montar el repositorio de imágenes"
MSG_ERR_NOMSDOS="El disco indicado no contiene una partición MSDOS"
MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar"
MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar"
MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema"
MSG_ERR_IMAGEFILE="Archivo de imagen corrupto o de otra versión de partclone"
MSG_ERR_NOTEXEC="Programa o función no ejecutable"
MSG_ERR_NOTWRITE="No hay acceso de escritura"
MSG_ERR_NOTCACHE="No existe partición caché en el cliente"
MSG_ERR_NOTUEFI="La interfaz UEFI no está activa"
MSG_ERR_NOTBIOS="La interfaz BIOS Legacy no está activa"
MSG_ERR_CACHESIZE="El espacio de la caché local o remota no es suficiente"
MSG_ERR_REDUCEFS="Error al reducir el sistema de archivos"
MSG_ERR_EXTENDFS="Error al expandir el sistema de archivos"
MSG_ERR_IMGSIZEPARTITION="Error al restaurar: Partición mas pequeña que la imagen"
MSG_ERR_UPDATECACHE="Error al realizar el comando updateCache"
MSG_ERR_UCASTSYNTAXT="Error en la generación de sintaxis de transferenica Unicast"
MSG_ERR_UCASTSENDPARTITION="Error en envío Unicast de una partición"
MSG_ERR_UCASTSENDFILE="Error en envío Unicast de un fichero"
MSG_ERR_UCASTRECEIVERPARTITION="Error en la recepción Unicast de una partición"
MSG_ERR_UCASTRECEIVERFILE="Error en la recepción Unicast de un fichero"
MSG_ERR_MCASTSYNTAXT="Error en la generación de sintaxis de transferenica Multicast"
MSG_ERR_MCASTSENDFILE="Error en envío Multicast de un fichero"
MSG_ERR_MCASTRECEIVERFILE="Error en la recepción Multicast de un fichero"
MSG_ERR_MCASTSENDPARTITION="Error en envío Multicast de una partición"
MSG_ERR_MCASTRECEIVERPARTITION="Error en la recepción Multicast de un fichero"
MSG_ERR_PROTOCOLJOINMASTER="Error en la conexión de una sesión Unicast|Multicast con el Master"
MSG_ERR_DONTFORMAT="Error al formatear"
MSG_ERR_DONTMOUNT_IMAGE="Error al montar/reducir la imagen"
MSG_ERR_DONTUNMOUNT_IMAGE="Error al desmontar la imagen"
MSG_ERR_DONTSYNC_IMAGE="Imagen no sincronizable"
MSG_ERR_NOTDIFFERENT="No se detectan diferencias entre la imagen básica y la partición"
MSG_ERR_SYNCHRONIZING="Error al sincronizar, puede afectar la creacion|restauracion de la imagen"
# Mensajes de avisos.
MSG_DONTMOUNT="Sistema de archivos no montado"
MSG_DONTUSE="NO USAR"
MSG_DONTUNMOUNT="El sistema de archivos no se puede desmontar o no está montado"
MSG_MOUNT="Sistema de archivos montado"
MSG_MOUNTREADONLY="Sistema de archivos montado solo de lectura"
MSG_OBSOLETE="EN DESUSO"
# Mensajes complementarios para las ayudas.
MSG_64BIT="64 bits"
MSG_DISK="disco"
MSG_ERROR="Error"
MSG_EXAMPLE="Ejemplo"
MSG_FORMAT="Formato"
MSG_FUNCTION="Función"
MSG_HARDWAREINVENTORY="Inventario de hardware de la máquina"
MSG_IMAGE="imagen"
MSG_INSTALLED="instalado"
MSG_NOCACHE="sin caché local"
MSG_NOEXTENDED="sin partición extendida"
MSG_PARTITION="partición"
MSG_PROTOCOL="protocolo"
MSG_RESERVEDVALUE="Valor reservado"
MSG_SEE="Ver"
MSG_UNKNOWN="Desconocido"
MSG_WARNING="Aviso"
# Mensajes del proceso de arranque.
MSG_DETECTLVMRAID="Detectar metadispositivos LVM y RAID."
MSG_ERRBOOTMODE=f"{MSG_ERROR}: Modo de arranque desconocido."
MSG_LAUNCHCLIENT="Ejecutar cliente."
MSG_LOADAPI="Cargar funciones del motor de clonación."
MSG_LOADMODULES="Cargar módulos del kernel."
MSG_MAKELINKS="Crear enlaces simbólicos."
MSG_MOUNTREPO="Montar repositorio por %s en modo %s."
MSG_OFFLINEMODE="Modo de arranque sin conexión."
MSG_OTHERSERVICES="Iniciar servicios complementarios del cliente."
MSG_POWEROFFCONF="Definir parámetros de ahorro de energía."
# Mensajes del menú por defecto.
MSG_BOOT="Iniciar"
MSG_DUPLEX="D&uacute;plex"
MSG_HOSTNAME="Equipo"
MSG_IPADDR="Direcci&oacute;n IP"
MSG_MACADDR="Direcci&oacute;n MAC"
MSG_MENUTITLE="Men&uacute; de opciones"
MSG_POWEROFF="Apagar el equipo"
MSG_SPEED="Velocidad"
# Mensajes de descripción breve de las funciones de la API.
MSG_HELP_ogAclFilter="Extrae las acl de los ficheros de la diferencial"
MSG_HELP_ogAddCmd="Añade comandos al fichero creado por la función ogInstalMiniSetup."
MSG_HELP_ogAddRegistryKey="Añade una nueva clave al registro de Windows."
MSG_HELP_ogAddRegistryValue="Añade un nuevo valor al registro de Windows."
MSG_HELP_ogAddToLaunchDaemon=""
MSG_HELP_ogBoot="Arranca un sistema operativo instalado."
MSG_HELP_ogBootLoaderDeleteEntry=MSG_DONTUSE
MSG_HELP_ogBootLoaderHidePartitions=MSG_DONTUSE
MSG_HELP_ogBootMbrGeneric=""
MSG_HELP_ogBootMbrXP=""
MSG_HELP_ogBurgDefaultEntry="Configura la entrada por defecto de Burg."
MSG_HELP_ogBurgDeleteEntry="Borra en el Burg del MBR las entradas para el inicio en una particion."
MSG_HELP_ogBurgHidePartitions="Configura el Burg del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)."
MSG_HELP_ogBurgInstallMbr="Instala el gestor de arranque BURG en el MBR del primer disco duro"
MSG_HELP_ogBurgOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de Burg."
MSG_HELP_ogCalculateChecksum="Calcula la suma de comprobación (checksum) de un fichero."
MSG_HELP_ogCalculateFullChecksum="Calcula la suma de comprobación completa de un fichero."
MSG_HELP_ogChangeRepo="Cambia el repositorio para el recurso remoto images."
MSG_HELP_ogCheckFs="Comprueba la consistencia de un sistema de archivos."
MSG_HELP_ogCheckIpAddress=""
MSG_HELP_ogCheckProgram=""
MSG_HELP_ogCheckStringInGroup=""
MSG_HELP_ogCheckStringInReg=""
MSG_HELP_ogCheckSyncImage="Muestra el contenido de la imagen para comprobarla."
MSG_HELP_ogCleanLinuxDevices=""
MSG_HELP_ogCleanOs="Elimina los archivos que no son necesarios en el sistema operativo."
MSG_HELP_ogCompareChecksumFiles="Compara si coinciden las sumas de comprobación almacenadas de 2 ficheros."
MSG_HELP_ogConfigureFstab=""
MSG_HELP_ogConfigureOgagent="Configura el nuevo agente OGAgent para sistemas operativos."
MSG_HELP_ogCopyFile="Copia un fichero a otro almacenamiento."
MSG_HELP_ogCreateBootLoaderImage=""
MSG_HELP_ogCreateCache="Reserva espacio para la partición de caché al final del disco."
MSG_HELP_ogCreateDiskImage="Genera una imagen exacta de un disco completo."
MSG_HELP_ogCreateFileImage="Crea/redimensiona el archivo de la imagen sincronizada"
MSG_HELP_ogCreateGptPartitions=""
MSG_HELP_ogCreateImage="Genera una imagen exacta de un sistema operativo instalado localmente."
MSG_HELP_ogCreateImageSyntax=""
MSG_HELP_ogCreateInfoImage="Crea información del contenido de la imagen"
MSG_HELP_ogCreateMbrImage="Genera una imagen del sector de arranque (MBR)."
MSG_HELP_ogCreatePartitions="Define la estructura de particiones de un disco."
MSG_HELP_ogCreatePartitionTable="Genera una tabla de particiones en caso de que no sea valida."
MSG_HELP_ogCreateTorrent=""
MSG_HELP_ogCopyEfiBootLoader="Copia el cargador de arranque desde la partición EFI a la de sistema."
MSG_HELP_ogDeleteCache="Elimina la partición de caché local."
MSG_HELP_ogDeleteFile="Borra un fichero de un espacio de almacenamiento."
MSG_HELP_ogDeletePartitionTable="Elimina la tabla de particiones del disco"
MSG_HELP_ogDeleteRegistryKey="Borra una clave vacía del registro de Windows."
MSG_HELP_ogDeleteRegistryValue="Borra un valor del registro de Windows."
MSG_HELP_ogDeleteTree="Borra un árbol de directorios de un espacio de almacenamiento."
MSG_HELP_ogDevToDisk="Devuelve el nº de orden de disco o de partición correspondiente al camino del fichero de dispositivo."
MSG_HELP_ogDiskToDev="Devuelve el camino del fichero de dispositivo correspondiente al nº de orden de disco o de partición."
MSG_HELP_ogDomainScript=""
MSG_HELP_ogEcho="Muestra un mensaje en pantalla y permite registrarlo en fichero de log"
MSG_HELP_ogExecAndLog="Ejecuta un comando y registra su salida en fichero de log"
MSG_HELP_ogExtendFs="Extiende el tamaño de un sistema de archivo al máximo de su partición."
MSG_HELP_ogFindCache="Indica la partición reservada para caché local."
MSG_HELP_ogFixBootSector=""
MSG_HELP_ogFormatCache="Formatea (inicia) el sistema de caché local."
MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos."
MSG_HELP_ogFormatFs=MSG_HELP_ogFormat
MSG_HELP_ogGetArch="Devuelve el tipo de arquitectura del cliente."
MSG_HELP_ogGetCacheSize="Devuelve el tamaño de la partición de caché local."
MSG_HELP_ogGetCacheSpace="Devuelve el espacio máximo disponible que puede ser reservado para la partición de caché local."
MSG_HELP_ogGetCaller="Devuelve el programa o función que llama al actual"
MSG_HELP_ogGetDiskSize="Devuelve el tamaño del disco."
MSG_HELP_ogGetDiskType="Devuelve el mnemónico de tipo de disco."
MSG_HELP_ogGetFreeSize=""
MSG_HELP_ogGetFsSize="Devuelve el tamaño de un sistema de archivos."
MSG_HELP_ogGetFsType="Devuelve el mnemónico de tipo de sistema de archivos."
MSG_HELP_ogGetGroupDir="Devuelve el camino del directorio por defecto para el grupo del cliente."
MSG_HELP_ogGetGroupName="Devuelve el nombre del grupo al que pertenece el cliente."
MSG_HELP_ogGetHivePath="Devuelve el camino completo del fichero de una sección del registro de Windows."
MSG_HELP_ogGetHostname="Devuelve el nombre de la máquina local."
MSG_HELP_ogGetImageCompressor="Devuelve la herramienta de compresión de la imagen."
MSG_HELP_ogGetImageInfo="Muestra información sobre la imagen monolitica: clonacion:compresor:sistemaarchivos:tamañoKB."
MSG_HELP_ogGetImageProgram="Devuelve el programa usado para crear la imagen."
MSG_HELP_ogGetImageSize="Devuelve el tamaño de una imagen de sistema."
MSG_HELP_ogGetImageType="Devuelve el sistema de ficheros de la imagen."
MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente."
MSG_HELP_ogGetLastSector="Devuelve el último sector usable del disco o de una partición."
MSG_HELP_ogGetMacAddress="Devuelve la dirección Ethernet del cliente."
MSG_HELP_ogGetMountImageDir="Devuelve el directorio de montaje de una imagen."
MSG_HELP_ogGetMountPoint="Devuelve el directorio donde está montado un sistema de archivos local."
MSG_HELP_ogGetNetInterface=""
MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado."
MSG_HELP_ogGetOsUuid="Devuelve el UUID de un sistema operativo"
MSG_HELP_ogGetOsVersion="Devuelve el tipo y la versión de un sistema operativo instalado."
MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnsys."
MSG_HELP_ogGetPartitionActive="Indica cual es la partición marcada como activa en un disco."
MSG_HELP_ogGetPartitionId="Devuelve el identificador de tipo de una partición."
MSG_HELP_ogGetPartitionSize="Devuelve el tamaño de una partición."
MSG_HELP_ogGetPartitionsNumber="Devuelve el número de particiones de un disco"
MSG_HELP_ogGetPartitionTableType="Devuelve el tipo de tabla de particiones del disco"
MSG_HELP_ogGetPartitionType="Devuelve el mnemónico de tipo de una partición."
MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnsys."
MSG_HELP_ogGetRegistryValue="Devuelve el dato de un valor del registro de Windows."
MSG_HELP_ogGetRepoIp="Devuelve la dirección IP del repositorio de datos."
MSG_HELP_ogGetSerialNumber="Devuelve el número de serie del equipo"
MSG_HELP_ogGetServerIp="Devuelve la dirección IP del servidor principal."
MSG_HELP_ogGetSizeParameters="Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido."
MSG_HELP_ogGetWindowsName="Devuelve el nombre del cliente guardado en el registro de Windows."
MSG_HELP_ogGrubAddOgLive="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys."
MSG_HELP_ogGrubDefaultEntry="Configura la entrada por defecto de GRUB."
MSG_HELP_ogGrubDeleteEntry="Borra en el grub del MBR las entradas para el inicio en una particion."
MSG_HELP_ogGrubHidePartitions="Configura el grub del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)."
MSG_HELP_ogGrubInstallMbr="Instala el gestor de arranque GRUB en el MBR del primer disco duro"
MSG_HELP_ogGrubInstallPartition="Instala el gestor de arranque GRUB en el BootSector"
MSG_HELP_ogGrubOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de GRUB."
MSG_HELP_ogGrubSecurity="Configura usuario y clave para modificar las entradas del menu del Grub."
MSG_HELP_ogGrubUefiConf="Genera el fichero grub.cfg de la partición EFI."
MSG_HELP_ogHelp="Muestra mensajes de ayudas para las funciones."
MSG_HELP_ogHidePartition="Oculta una partición de Windows."
MSG_HELP_ogIdToType="Devuelve el mnemónico asociado al identificador de tipo de partición."
MSG_HELP_ogInstallFirstBoot="Crea un archivo que se ejecutará en el primer arranque de Windows."
MSG_HELP_ogInstallLaunchDaemon="Instala un archivo que se ejecutará en el arranque de macOS."
MSG_HELP_ogInstallLinuxClient=MSG_OBSOLETE
MSG_HELP_ogInstallMiniSetup="Instala un archivo que se ejecutará en el arranque de Windows."
MSG_HELP_ogInstallRunonce="Crea archivo que se ejecutará en el inicio de un usuario administrador de Windows."
MSG_HELP_ogInstallWindowsClient=MSG_OBSOLETE
MSG_HELP_ogIsFormated="Comprueba si un sistema de archivos está formateado."
MSG_HELP_ogIsImageLocked="Comprueba si una imagen está bloqueada por una operación de uso exclusivo."
MSG_HELP_ogIsLocked="Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo."
MSG_HELP_ogIsDiskLocked="Comprueba si un disco está bloqueado por una operación de uso exclusivo."
MSG_HELP_ogIsMounted="Comprueba si un sistema de archivos está montado."
MSG_HELP_ogIsNewerFile="Comprueba si un fichero es más nuevo (se ha modificado después) que otro."
MSG_HELP_ogIsPartitionLocked=MSG_HELP_ogIsLocked
MSG_HELP_ogIsRepoLocked=""
MSG_HELP_ogIsSyncImage="Comprueba si la imagen es sincronizable."
MSG_HELP_ogIsVirtualMachine="Comprueba si el cliente es una máquina virtual"
MSG_HELP_ogIsWritable="Comprueba si un sistema de archivos está montado con permiso de escritura."
MSG_HELP_ogLinuxBootParameters="Devuelve los parámetros de arranque de un sistema operativo Linux instalado."
MSG_HELP_ogListHardwareInfo="Lista el inventario de dispositivos del cliente."
MSG_HELP_ogListLogicalPartitions="Lista las particiones lógicas de un disco"
MSG_HELP_ogListPartitions="Lista la estructura de particiones de un disco."
MSG_HELP_ogListPrimaryPartitions="Lista las particiones primarias de un disco"
MSG_HELP_ogListRegistryKeys="Lista los nombres de las subclaves incluidas en una clave del registro de Windows."
MSG_HELP_ogListRegistryValues="Lista los nombres de los valores incluidos en una clave del registro de Windows."
MSG_HELP_ogListSoftware="Lista el inventario de programas instalados en un sistema operativo."
MSG_HELP_ogLock="Bloquea una partición para operación de uso exclusivo."
MSG_HELP_ogLockDisk="Bloquea un disco para operación de uso exclusivo."
MSG_HELP_ogLockImage="Bloquea una imagen para operación de uso exclusivo."
MSG_HELP_ogLockPartition=MSG_HELP_ogLock
MSG_HELP_ogMakeChecksumFile="Almacena la suma de comprobación de un fichero."
MSG_HELP_ogMakeDir="Crea un directorio para OpenGnsys."
MSG_HELP_ogMakeGroupDir="Crea el directorio de grupo (aula) en un repositorio."
MSG_HELP_ogMcastReceiverFile=""
MSG_HELP_ogMcastReceiverPartition=""
MSG_HELP_ogMcastRequest=""
MSG_HELP_ogMcastSendFile=""
MSG_HELP_ogMcastSendPartition=""
MSG_HELP_ogMcastSyntax=""
MSG_HELP_ogMountCache="Monta el sistema de archivos dedicado a caché local."
MSG_HELP_ogMountCdrom="Monta dispositivo óptico por defecto."
MSG_HELP_ogMountImage="Monta una imagen sincronizable"
MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje."
MSG_HELP_ogMountFs=MSG_HELP_ogMount
MSG_HELP_ogNvramActiveEntry="Configura a activa entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramAddEntry="Crea nueva entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramDeleteEntry="Borra entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramGetCurrent="Muestra la entrada del gestor de arranque (NVRAM) que ha iniciado el equipo."
MSG_HELP_ogNvramGetNext="Muestra la entrada del gestor de arranque (NVRAM) que se utilizará en el próximo arranque."
MSG_HELP_ogNvramGetOrder="Muestra el orden de las entradas del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramGetTimeout="Muestra el tiempo de espera del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramInactiveEntry="Configura a inactiva entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramList="Lista las entradas del gestor de arranque (NVRAN) marcando con un asterisco las activas"
MSG_HELP_ogNvramPxeFirstEntry="Configura la tarjeta de red como primer arranque en la NVRAM."
MSG_HELP_ogNvramSetNext="Configura el próximo arranque con la entrada del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramSetOrder="Configura el orden de las entradas del gestor de arranque (NVRAM)."
MSG_HELP_ogNvramSetTimeout="Configura el tiempo de espera del gestor de arranque (NVRAM)."
MSG_HELP_ogRaiseError="Muestra y registra mensajes de error y devuelve el código correspondiente."
MSG_HELP_ogReduceFs="Reduce el tamaño del sistema de archivos al mínimo ocupado por sus datos."
MSG_HELP_ogReduceImage="Reduce el tamaño de la imagen"
MSG_HELP_ogRefindDeleteEntry="Borra en rEFInd las entradas para el inicio en una particion."
MSG_HELP_ogRefindDefaultEntry="Configura la entrada por defecto de rEFInd."
MSG_HELP_ogRefindOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de rEFInd."
MSG_HELP_ogRefindSetTheme="Asigna un tema al rEFInd."
MSG_HELP_ogRefindSetTimeOut="Define el tiempo (segundos) que se muestran las opciones de inicio de rEFInd."
MSG_HELP_ogRefindSetResolution="Define la resolución que usuará el thema del gestor de arranque rEFInd."
MSG_HELP_ogRefindInstall="Instala y configura el gestor rEFInd en la particion EFI"
MSG_HELP_ogRestoreAclImage="Restaura las ACL de Windows (La informacion debe estar copiada en /tmp)."
MSG_HELP_ogRestoreBootLoaderImage=""
MSG_HELP_ogRestoreDiskImage="Restaura una imagen de un disco completo."
MSG_HELP_ogRestoreEfiBootLoader="Copia el cargador de arranque de la partición de sistema a la partición EFI."
MSG_HELP_ogRestoreImage="Restaura una imagen de sistema operativo."
MSG_HELP_ogRestoreInfoImage="Restablece información del sistema: ACL y enlaces simbolicos"
MSG_HELP_ogRestoreMbrImage="Restaura una imagen del sector de arranque (MBR)."
MSG_HELP_ogRestoreUuidPartitions="Restaura los uuid de las particiones y la tabla de particiones."
MSG_HELP_ogSaveImageInfo="Crea un fichero con la información de la imagen."
MSG_HELP_ogSetLinuxName=""
MSG_HELP_ogSetPartitionActive="Establece el número de partición activa de un disco."
MSG_HELP_ogSetPartitionId="Modifica el tipo de una partición física usando el mnemónico del tipo."
MSG_HELP_ogSetPartitionSize="Establece el tamaño de una partición."
MSG_HELP_ogSetPartitionType="Modifica el identificador de tipo de una partición física."
MSG_HELP_ogSetRegistryValue="Asigna un dato a un valor del registro de Windows."
MSG_HELP_ogSetWindowsName="Asigna el nombre del cliente en el registro de Windows."
MSG_HELP_ogSetWinlogonUser="Asigna el nombre de usuario por defecto para el gestor de entrada de Windows."
MSG_HELP_ogSyncCreate="Sincroniza los datos de la partición a la imagen"
MSG_HELP_ogSyncRestore="Sincroniza los datos de la imagen a la partición"
MSG_HELP_ogTorrentStart=""
MSG_HELP_ogTypeToId="Devuelve el identificador asociado al mnemónico de tipo de partición."
MSG_HELP_ogUcastReceiverPartition=""
MSG_HELP_ogUcastSendFile=""
MSG_HELP_ogUcastSendPartition=""
MSG_HELP_ogUcastSyntax=""
MSG_HELP_ogUnhidePartition="Hace visible una partición de Windows."
MSG_HELP_ogUninstallLinuxClient="Desinstala el antiguo cliente OpenGnSys en un sistema operativo Linux."
MSG_HELP_ogUninstallWindowsClient="Desinstala el antiguo cliente OpenGnSys en un sistema operativo Windows."
MSG_HELP_ogUnlock="Desbloquea una partición tras finalizar una operación de uso exclusivo."
MSG_HELP_ogUnlockDisk="Desbloquea un disco tras finalizar una operación de uso exclusivo."
MSG_HELP_ogUnlockImage="Desbloquea una imagen tras finalizar una operación de uso exclusivo."
MSG_HELP_ogUnlockPartition=MSG_HELP_ogUnlock
MSG_HELP_ogUnmountAll="Desmonta todos los sistemas de archivos."
MSG_HELP_ogUnmountCache="Desmonta el sistema de archivos de caché local."
MSG_HELP_ogUnmount="Desmonta un sistema de archivos."
MSG_HELP_ogUnmountImage="Desmonta la imagen."
MSG_HELP_ogUnmountFs=MSG_HELP_ogUnmount
MSG_HELP_ogUnsetDirtyBit=""
MSG_HELP_ogUpdateCacheIsNecesary="Comprueba si es necesario actualizar una archivo en la cache local."
MSG_HELP_ogUpdatePartitionTable="Actualiza información de la tabla de particiones del disco."
MSG_HELP_ogUuidChange="Reemplaza el UUID de un sistema de ficheros."
MSG_HELP_ogWaitSyncImage=""
MSG_HELP_ogWindowsBootParameters=""
MSG_HELP_ogWindowsRegisterPartition=""
# Scripts
MSG_HELP_configureOs="Post-configura de arranque del sistema"
MSG_HELP_createBaseImage="Genera imagen básica de la partición"
MSG_HELP_createDiffImage="Genera imagen diferencial de la partición respecto a la imagen básica"
MSG_HELP_installOfflineMode="Prepara el equipo cliente para el modo offline."
MSG_HELP_partclone2sync="Convierte imagen de partclone en imagen sincronizable."
MSG_HELP_restoreBaseImage="Restaura una imagen básica en una partición"
MSG_HELP_restoreDiffImage="Restaura una imagen diferencial en una partición"
MSG_HELP_updateCache="Realiza la actualización de la caché"
# Mensajes de descripción breve de la interfaz.
MSG_INTERFACE_START="[START Interface] Ejecutar comando: "
MSG_INTERFACE_END="[END Interface] Comando terminado con este código: "
# Mensajes de scripts.
MSG_SCRIPTS_START=" INICIO scripts: "
MSG_SCRIPTS_END=" FIN scripts: "
MSG_SCRIPTS_TASK_END="Fin de la tarea"
MSG_SCRIPTS_TASK_SLEEP="Esperando para iniciar"
MSG_SCRIPTS_TASK_START="Iniciando"
MSG_SCRIPTS_TASK_ERR="Error"
# Script createImage.
MSG_SCRIPTS_FILE_RENAME=" Renombrar fichero-imagen previo: "
MSG_SCRIPTS_CREATE_SIZE=" Calcular espacio (KB) requerido para almacenarlo y el disponible: "
# Script updateCache.
MSG_SCRIPTS_UPDATECACHE_DOUPDATE="Comprobar si es necesario actualizar el fichero imagen "
MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE="Comprobar que el tamaño de la caché es mayor que el fichero a descargar."
# Script updateCache: para las imágenes sincronizadas tipo dir.
MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calcular el tamaño de la imagen."
MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Comprobar si la imagen del repositorio es mayor que la de la caché."
MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Comprobar el espacio libre de la caché y actuar según engine.cfg"
MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesión Multicast: ServidorMcast:PuertoDatos"
# interface sustituye temporalmente al scritp restore
MSG_SCRIPTS_CHECK_ENGINE="Analizar proceso a realizar según engine.cfg"
MSG_SCRIPTS_MULTICAST_PRECHECK_PORT="Determinar puerto principal y auxiliar Multicast."
MSG_SCRIPTS_MULTICAST_CHECK_PORT="Comprobar puertos de sesión y datos"
MSG_SCRIPTS_MULTICAST_REQUEST_PORT="Solicitar la apertura: "
MSG_SCRIPTS_OS_CONFIGURE="Iniciar la configuración del sistema restaurado"
# TIME MESSAGES
MSG_SCRIPTS_TIME_TOTAL="tiempo total del proceso"
MSG_SCRIPTS_TIME_PARTIAL="tiempo parcial del subproceso"
# HTTPLOG
MSG_HTTPLOG_NOUSE="No apague este ordenador por favor"
# Mensajes sincronizadas
MSG_SYNC_RESIZE="Redimensiona la imagen al tamaño necesario"
MSG_SYNC_RESTORE="Trae el listado ficheros y baja la imagen"
MSG_SYNC_DELETE="Diferencial: Borra archivos antiguos"
MSG_SYNC_SLEEP="Espera que se monte/reduzca la imagen"
# Mensajes sincronizadas complementarios a errores
MSG_SYNC_DIFFERENTFS="El sistema de ficheros de destino no coincide con el de la imagen"
MSG_SYNC_EXTENSION="Las extensiones de la imagenes deben ser img o diff"
MSG_SYNC_NOCHECK="La imagen esta montada por otro proceso, no podemos comprobarla"
MSG_RESTORE="Restaura la imagen en"

View File

@ -0,0 +1,159 @@
#!/usr/bin/python3
#/**
# configureOs
#@brief Script para realizar la configuracion del sistema operativo restaurado.
#@param 1 disco
#@param 2 particion
#@return
#@TODO comprobar que el tipo de particion corresponde con el sistema de archivos.
#@exception OG_ERR_FORMAT # 1 formato incorrecto.
#*/ ##
import sys
import os
import os.path
import subprocess
import ogGlobals
import SystemLib
import DiskLib
import FileSystemLib
import NetLib
import InventoryLib
import BootLib
import UEFILib
import PostConfLib
import FileLib
## el código bash original hace:
## [ -f $DEVICECFG ] && source $DEVICECFG
## pero luego no utiliza ninguna de las variables definidas en el archivo...
disk = sys.argv[1]
par = sys.argv[2]
# Si el sistema de archivos no esta extendido, ampliarlo al tamaño de su partición.
partsize = DiskLib.ogGetPartitionSize (disk, par)
if not partsize: sys.exit (1)
fssize = FileSystemLib.ogGetFsSize (disk, par)
if fssize < partsize:
print ('Extender sistema de archivos.')
FileSystemLib.ogExtendFs (disk, par)
# Si no existe partición activa, activar este sistema.
flagactive = DiskLib.ogGetPartitionActive (disk)
if not flagactive: DiskLib.ogSetPartitionActive (disk, par)
# Si el sistema de archivos es de solo lectura, no hacer la post-configuración.
mntdir = FileSystemLib.ogMount (disk, par)
if not FileSystemLib.ogIsWritable (disk, par):
print ('AVISO: sistema de archivos de solo lectura, no se ejecuta postconfiguración.')
sys.exit (0)
# Nombre del cliente.
host = NetLib.ogGetHostname()
# Post-configuración personalizada para cada tipo de sistema operativo.
ostype = InventoryLib.ogGetOsType (disk, par)
if 'Windows' == ostype:
if not host: host = 'pc'
BootLib.ogSetWindowsName (disk, par, host) # Cambiar nombre en sistemas Windows.
if InventoryLib.ogIsEfiActive(): # Si es UEFI copio el cargador de arranque a la partición EFI e instalo Grub.
UEFILib.ogRestoreEfiBootLoader (disk, par)
esp = DiskLib.ogGetEsp()
if not esp:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'ESP')
sys.exit (1)
efidisk, efipart = esp.split()
BootLib.ogGrubInstallMbr (efidisk, efipart, 'TRUE')
else:
BootLib.ogFixBootSector (disk, par) # Configurar el boot sector de la partición Windows.
BootLib.ogWindowsBootParameters (disk, par) # Configurar el gestor de arranque de Windows XP/Vista/7.
BootLib.ogWindowsRegisterPartition (disk, par, 'C', disk, par) # Registrar en Windows que la partición indicada es su nueva unidad C:\
PostConfLib.ogConfigureOgagent (disk, par) # Configurar nuevo agente OGAgent.
path1 = FileLib.ogGetPath (file=f'{mntdir}/windows/ogAdmWinClient.exe')
path2 = FileLib.ogGetPath (file=f'{mntdir}/winnt/ogAdmWinClient.exe')
if path1 or path2: # Eliminar el antiguo cliente de Windows.
PostConfLib.ogInstallMiniSetup (disk, par, 'postconf.cmd')
PostConfLib.ogUninstallWindowsClient (disk, par, 'postconf.cmd')
elif 'Linux' == ostype:
BootLib.ogConfigureFstab (disk, par) # Configuro fstab: particion de Swap y si es UEFI además la partición EFI.
if InventoryLib.ogIsEfiActive(): # Si es UEFI instalo Grub en la partición EFI
esp = DiskLib.ogGetEsp()
efidisk, efipart = esp.split()
BootLib.ogGrubInstallMbr (efidisk, efipart, 'TRUE')
BootLib.ogGrubInstallPartition (disk, par) ## Instala (no configura) el codigo de arranque del Grub en la partición (no lo configura, se mantiene el original de la imagen)
find_out = subprocess.run (['find', f'{mntdir}/usr/sbin', f'{mntdir}/sbin', f'{mntdir}/usr/local/sbin', '-name', 'ogAdmLnxClient', '-print'], capture_output=True, text=True).stdout
if find_out:
PostConfLib.ogUninstallLinuxClient (disk, par) # Eliminar el antiguo cliente de Linux.
PostConfLib.ogConfigureOgagent (disk, par) # Configurar nuevo agente OGAgent.
## Modificar el nombre del equipo
print (f'Asignar nombre Linux "{host}".')
etc = FileLib.ogGetPath (src=f'{disk} {par}', file='/etc')
if os.path.isdir (etc):
with open (f'{etc}/hostname', 'w') as fd:
fd.write (f'{host}\n')
elif 'MacOS' == ostype:
open (f'{mntdir}/osxpostconf', 'a').close() ## touch, Fichero indicador de activación de postconfiguración.
# Crear fichero de configuración del servicio de arranque.
with open (f'{mntdir}/Library/LaunchDaemons/es.opengnsys.postconfd.plist', 'w') as fd:
fd.write ('<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n')
fd.write ('<plist version="1.0">\n')
fd.write ('\t<dict>\n')
fd.write ('\t\t<key>Label</key>\n')
fd.write ('\t\t<string>es.opengnsys.postconfd.sh</string>\n')
fd.write ('\t\t<key>ProgramArguments</key>\n')
fd.write ('\t\t<array>\n')
fd.write ('\t\t\t<string>/var/root/postconfd.sh</string>\n')
fd.write ('\t\t</array>\n')
fd.write ('\t\t<key>RunAtLoad</key>\n')
fd.write ('\t\t<true/>\n')
fd.write ('\t\t<key>StandardOutPath</key>\n')
fd.write ('\t\t<string>/var/log/postconfd.log</string>\n')
fd.write ('\t\t<key>StandardErrorPath</key>\n')
fd.write ('\t\t<string>/var/log/postconfd.err</string>\n')
fd.write ('\t\t<key>Debug</key>\n')
fd.write ('\t\t<true/>\n')
fd.write ('\t</dict>\n')
fd.write ('</plist>\n')
# Programa de inicio que será ejecutado en el arranque de Mac OS X.
with open (f'{mntdir}/var/root/postconfd.sh', 'w') as fd:
fd.write ('#!/bin/bash\n')
fd.write ('# postconfd - ejecución de scripts de inicio.\n')
fd.write ('\n')
fd.write ('# Ejecutar postconfiguración si existe el fichero indicador.\n')
fd.write ('if [ -e /osxpostconf ]; then\n')
fd.write ('\t# Tomar nombre del equipo.\n')
fd.write (f'\tHOST="{host}"\n')
fd.write ('\tif [ -z "$HOST" ]; then\n')
fd.write ('\t\t# Si no hay nombre asociado, activar la red para obtener datos del DHCP.\n')
fd.write ('\t\tsource /etc/rc.common\n')
fd.write ('\t\tCheckForNetwork\n')
fd.write ('\t\twhile [ "$NETWORKUP" != "-YES-" ]; do\n')
fd.write ('\t\t\tsleep 5\n')
fd.write ('\t\t\tNETWORKUP=\n')
fd.write ('\t\t\tCheckForNetwork\n')
fd.write ('\t\tdone\n')
fd.write ('\t\t# Componer nombre del equipo a partir de datos del DHCP.\n')
fd.write ('\t\tIP=$(ifconfig en0 inet | awk \'{if ($1=="inet") print $2}\')\n')
fd.write ('\t\tHOST="mac-$(echo ${IP//./-} | cut -f3-4 -d-)"\n')
fd.write ('\tfi\n')
fd.write ('\t# Asignar nombre del equipo.\n')
fd.write ('\tscutil --set ComputerName "$HOST"\n')
fd.write ('\tscutil --set LocalHostName "$HOST"\n')
fd.write ('\tscutil --set HostName "$HOST"\n')
fd.write ('\thostname "$HOST"\n')
fd.write ('\t# Descromprimir ficheros de versión para obtener inventario de aplicaciones.\n')
fd.write ('\tfind /Applications -type d -name "*.app" -prune -exec \\n')
fd.write ('\t ditto --nopreserveHFSCompression "{}/Contents/version.plist" "{}/Contents/version.plist.uncompress"\n')
fd.write ('\trm -f /osxpostconf # Borrar fichero indicador de psotconfiguración\n')
fd.write ('fi\n')
os.chmod (f'{mntdir}/var/root/postconfd.sh', 0o700) # Dar permiso de ejecución.
PostConfLib.ogConfigureOgagent (disk, par) # Configurar nuevo agente OGAgent de sistema operativo.
sys.exit (0)

View File

@ -0,0 +1,182 @@
#!/usr/bin/python3
import os
import sys
import time
import subprocess
import shutil
import ogGlobals
import SystemLib
import FileSystemLib
import DiskLib
import NetLib
import StringLib
import FileLib
import ImageLib
#Descripcion:
# Si Repositorio es el global (REPO) realiza un deploy.
# Si Repositorio es local (CACHE) realiza un restoreImage CACHE
# El deploy, si detecta que el cliente no tiene una CACHE o no tiene espacio suficiente consulta el engine.cfg RESTOREPROTOCOLNOCACHE
prog = os.path.basename (sys.argv[0])
def main (repo, imgname, disk, par, proto='UNICAST', protoopt=''):
if repo: repo = repo.upper()
else: repo = 'REPO'
proto = proto.upper()
protoopt = protoopt.upper()
time1 = time.time()
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
with open (ogGlobals.OGLOGCOMMAND, 'w') as fd:
fd.write (' ')
if 'EjecutarScript' != SystemLib.ogGetCaller():
with open (ogGlobals.OGLOGSESSION, 'w') as fd:
fd.write ('')
# Registro de inicio de ejecución
SystemLib.ogEcho (['log', 'session'], None, f'[1] {ogGlobals.lang.MSG_SCRIPTS_START} {prog} {" ".join(sys.argv)}')
# Si el origen(pariticion) esta bloqueada salir.
if FileSystemLib.ogIsLocked (disk, par):
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_LOCKED, f'{ogGlobals.lang.MSG_PARTITION}, {disk} {par}')
sys.exit (1)
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_HELP_ogUnmount} {disk} {par}')
FileSystemLib.ogUnmount (disk, par)
# Valor por defecto para el repositorio.
mode = None
if NetLib.ogGetIpAddress() == repo or 'CACHE' == repo:
mode = 'CACHE'
else:
if StringLib.ogCheckIpAddress (repo) or 'REPO' == repo:
if not NetLib.ogChangeRepo (repo):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repo)
sys.exit (1)
mode = 'REPO'
#Informacioin previa de la imagen
if mode:
imgpath = FileLib.ogGetPath (src=mode, file=f'{imgname}.img')
else:
imgpath = FileLib.ogGetPath (file=f'{imgname}.img')
imgos = ImageLib.ogGetImageInfo (imgpath)
#if imgos == 1: sys.exit(SystemLib.ogRaiseError("session", OG_ERR_NOTFOUND, f"{repo} {imgname}"))
#elif imgos == 5: sys.exit(SystemLib.ogRaiseError("session", OG_ERR_IMAGEFILE, f"{repo} {imgname}"))
#elif imgos != 0: sys.exit(SystemLib.ogRaiseError("session", OG_ERR_GENERIC))
if not imgos:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_GENERIC, '')
sys.exit (1)
imgsize = os.path.getsize (imgpath) // 1024
SystemLib.ogEcho (['log', 'session'], None, f'[1] REPO={repo} IMG-FILE={imgname}.img SIZE={imgsize} (KB) METADATA={imgos}')
# Procesar repositorio.
if 'CACHE' == mode:
nextoperation = 'CACHE'
elif 'REPO' == mode:
if 'MULTICAST-DIRECT' == proto:
nextoperation = 'MULTICAST'
elif 'UNICAST-DIRECT' == proto:
nextoperation = 'UNICAST'
# Si protocolo es torrent|torrent-cache o multicast|multicast-cache
elif proto in ['TORRENT', 'TORRENT-CACHE', 'MULTICAST', 'MULTICAST-CACHE', 'UNICAST', 'UNICAST-CACHE']:
# Eliminamos CACHE o DIRECT
proto = proto.split ('-')[0]
SystemLib.ogEcho (['log', 'session'], None, f'[2] updateCache {repo} "/{imgname}.img" {proto} {protoopt}')
time2 = time.time()
retval = subprocess.run (['updateCache.py', repo, f'/{imgname}.img', proto, protoopt]).returncode
time2 = time.time() - time2
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TIME_PARTIAL} updateCache {int (time2/60)}m {int (time2%60)}s')
if 0 == retval:
SystemLib.ogEcho (['log', 'session'], None, '[50] updateCache (OK)')
nextoperation = 'CACHE'
elif retval in [15, 16]:
# no se permite usar la cache (no existe(15) o no espacio sufiente (16). Se consulta engine.cfg para RESTOREPROTOCOLNOCACHE [ multicast unicast none ]
SystemLib.ogEcho (['log', 'session'], None, f'[50] {ogGlobals.lang.MSG_ERR_NOTCACHE} ; {ogGlobals.lang.MSG_ERR_CACHESIZE}')
SystemLib.ogEcho (['log', 'session'], None, f'[50] {ogGlobals.lang.MSG_SCRIPTS_CHECK_ENGINE}: RESTOREPROTOCOLNOTCACHE={ogGlobals.RESTOREPROTOCOLNOTCACHE}')
if 'MULTICAST' == RESTOREPROTOCOLNOTCACHE:
if 'MULTICAST' == proto: nextoperation = 'MULTICAST'
elif 'TORRENT' == proto: nextoperation = 'UNICAST'
elif 'UNICAST' == proto: nextoperation = 'UNICAST'
elif 'UNICAST' == RESTOREPROTOCOLNOTCACHE:
nextoperation = 'UNICAST'
elif RESTOREPROTOCOLNOTCACHE is None:
if 15 == retval:
SystemLib.ogEcho (['log', 'session'], None, f'[100] {ogGlobals.lang.MSG_ERR_NOTCACHE}')
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_NOTCACHE, 'NOT CACHE')
sys.exit (1)
elif 16 == retval:
SystemLib.ogEcho (['log', 'session'], None, f'[100] {ogGlobals.lang.MSG_ERR_CACHESIZE}')
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_CACHESIZE, 'CACHE FULL')
sys.exit (1)
elif retval in [57, 60]:
# Time-out en la transferencia multicast (El mensaje de error está enviado)
sys.exit (retval)
else:
# Error desconocido
sys.exit (retval)
else:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_ERR_FORMAT}, {proto}')
sys.exit (1)
else:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_ERR_FORMAT}, {repo}')
sys.exit (1)
time3 = time.time()
# Obtener parámetros de restauración.
if 'CACHE' == nextoperation:
params = ['CACHE', imgname, disk, par]
elif 'UNICAST' == nextoperation:
params = [repo, imgname, disk, par]
elif 'MULTICAST' == nextoperation:
params = [repo, imgname, disk, par, proto, protoopt]
# Si existe, ejecuta script personalizado "restoreImageCustom"; si no, llama al genérico "restoreImage".
if shutil.which ('restoreImageCustom'):
SystemLib.ogEcho (['log', 'session'], None, f'[55] {ogGlobals.lang.MSG_HELP_ogRestoreImage}: restoreImageCustom {params}')
retval = subprocess.run (['restoreImageCustom'] + params).returncode
else:
SystemLib.ogEcho (['log', 'session'], None, f'[55] {ogGlobals.lang.MSG_HELP_ogRestoreImage}: restoreImage {params}')
retval = subprocess.run (['restoreImage.py'] + params).returncode
# Mostrar resultados.
resumerestoreimage = subprocess.run (['grep', '--max-count', '1', 'Total Time:', ogGlobals.OGLOGCOMMAND], capture_output=True, text=True).stdout
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {resumerestoreimage} ')
# Si la transferencia ha dado error me salgo.
if retval:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_IMAGE, f'{repo} {imgname}')
if SystemLib.ogGetCaller() != 'EjecutarScript':
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {ogGlobals.OG_ERR_IMAGE}')
sys.exit (ogGlobals.OG_ERR_IMAGE)
time3 = time.time() - time3
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TIME_PARTIAL} : {int (time3/60)}m {int (time3%60)}s')
# Si existe, ejecuta script personalizado de postconfiguración "configureOsCustom"; si no, llama al genérico "configureOs".
if shutil.which ('configureOsCustom'):
SystemLib.ogEcho (['log', 'session'], None, '[90] configureOsCustom')
subprocess.run (['configureOsCustom', disk, par, repo, imgname])
else:
SystemLib.ogEcho (['log', 'session'], None, f'[90] {ogGlobals.lang.MSG_SCRIPTS_OS_CONFIGURE}')
subprocess.run (['configureOs.py', disk, par])
time_total = time.time() - time1
SystemLib.ogEcho (['log', 'session'], None, f'[100] {ogGlobals.lang.MSG_SCRIPTS_TIME_TOTAL} {int (time_total/60)}m {int (time_total%60)}s')
# Registro de fin de ejecución
# Si se ha llamado desde ejecutar script no lo muestro para no repetir.
if SystemLib.ogGetCaller() != 'EjecutarScript':
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}')
sys.exit (retval)
if __name__ == '__main__':
if len (sys.argv) < 6:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_FORMAT}: {prog} REPO imagen ndisco nparticion [ UNICAST-DIRECT|UNICAST|UNICAST-CACHE|MULTICAST-DIRECT|MULTICAST|MULTICAST-CACHE|TORRENT [opciones protocolo] ]')
sys.exit (1)
main (*sys.argv[1:])

View File

@ -0,0 +1,128 @@
#!/usr/bin/python3
# Scirpt de iniciación de la caché local de disco.
# Nota: se usa como base para el programa de configuración de equipos de OpenGnsys Admin).
# Formato: initCache [int_ndisk [int_npart]] {-1 | 0 | int_size} [NOMOUNT]
import sys
import time
import subprocess
import ogGlobals
import SystemLib
import FileSystemLib
import CacheLib
import DiskLib
def main (NDISK, NPART, SIZE, MOUNT):
TIME1 = time.time()
# Si tamaño=0, no hacer nada.
if 0 == SIZE:
print("No modificar la caché local.")
return True
# Si tamaño=-1, borrar caché.
if -1 == SIZE:
print("[10] Trabajar sin caché local.")
CacheLib.ogUnmountCache()
CacheLib.ogDeleteCache()
else:
# Si la caché actual está definida en otro disco y partición, se elimina.
current_cache = CacheLib.ogFindCache()
if current_cache and f"{NDISK} {NPART}" != current_cache:
print("[10] Detectada otra caché, eliminarla")
CacheLib.ogUnmountCache()
CacheLib.ogDeleteCache()
# Tomamos el tamaño actual. Si no existe cache será 0.
CACHESIZE = CacheLib.ogGetCacheSize()
if not CACHESIZE: CACHESIZE = 0 ## may be None
# Error si tamaño definido no es >0.
if SIZE <= 0:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f"!({SIZE}>0)")
return False
# Si no existe caché o si cambia su tamaño, crearla.
if SIZE != CACHESIZE:
print("[10] Crear partición de caché local.")
CacheLib.ogUnmountCache()
print (f'nati: calling ogCreateCache ({NDISK}, {NPART}, {SIZE})')
CacheLib.ogCreateCache (NDISK, NPART, SIZE)
DiskLib.ogUpdatePartitionTable()
# Si caché no montada y no formateada o cambia el tamaño: formatear.
cache = CacheLib.ogFindCache()
if not cache:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTCACHE, '')
return False
cache = cache.split()
if not FileSystemLib.ogIsFormated (cache[0], cache[1]) or SIZE != CACHESIZE:
print("[50] Formatear caché local.")
CacheLib.ogFormatCache()
print("[70] Comprobar montaje de caché local.")
# Si error al montar, chequear sistema de archivos y volver a montar.
if not CacheLib.ogMountCache():
print("[80] Comprobar consistencia y volver a montar caché local.")
FileSystem.ogCheckFs (cache[0], cache[1])
if not CacheLib.ogMountCache():
return False
# Dejar desmontada la caché si se ha solicitado.
if not MOUNT:
print("[90] Dejar desmontada la caché local.")
CacheLib.ogUnmountCache()
# Duración del proceso.
TIME = time.time() - TIME1
print (f"[100] Duración de la operación {int(TIME // 60)}m {int(TIME % 60)}s")
return True
if __name__ == "__main__":
PROG = sys.argv[0]
EXECFORMAT = f"{PROG} [int_ndisk [int_npart]] {{-1 | 0 | int_size}} [NOMOUNT]"
args = sys.argv[1:]
if args and 'NOMOUNT' == args[-1].upper():
MOUNT = False
args = args[:-1]
else:
MOUNT = True
PARAMS = len (args)
try:
if 1 == PARAMS:
NDISK = 1
NPART = 4
SIZE = int (args[0])
elif 2 == PARAMS:
NDISK = int (args[0])
NPART = 4
SIZE = int (args[1])
elif 3 == PARAMS:
NDISK = int (args[0])
NPART = int (args[1])
SIZE = int (args[2])
else:
print (f'nati: params no es ni 1 ni 2 ni 3 sino ({PARAMS})')
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT)
sys.exit (1)
except ValueError:
print (f'nati: ValueError')
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT)
sys.exit (1)
# Si disco o partición no son mayores o iguales que 1, error.
if NDISK < 1 or NPART < 1:
print (f'nati: ndisk<1 or npart<1, ({NDISK}) ({NPART})')
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT)
sys.exit (1)
# Si tamaño no es numérico o tamaño<-1, error.
if SIZE < -1:
print (f'nati: SIZE<-1 ({SIZE})')
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT)
sys.exit (1)
rc = main (NDISK, NPART, SIZE, MOUNT)
sys.exit (not rc)

View File

@ -0,0 +1,39 @@
#!/usr/bin/python3
# Scirpt de ejemplo para almacenear en fichero temporal el listado de software.
# Nota: se usa como base para el programa de recogida de listado de software de OpenGnsys Admin.
# Formato: listSoftwareInfo [-r] ndisk npart
# -r listado reducido (sin parches de Windows)
import os
import sys
import re
import argparse
import ogGlobals
import SystemLib
import InventoryLib
import NetLib
prog = os.path.basename (sys.argv[0])
def main (disk, par, reduced):
ip = NetLib.ogGetIpAddress()
softfile = f'{ogGlobals.OGLOG}/soft-{ip}-{disk}-{par}'
software_list = InventoryLib.ogListSoftware (disk, par)
if reduced:
software_list = [line for line in software_list if not re.search (r'(KB[0-9]{6})', line)]
with open (softfile, 'w') as f:
for line in software_list:
f.write (f'{line}\n')
print (softfile)
if __name__ == '__main__':
parser = argparse.ArgumentParser (add_help=False)
parser.add_argument ('-r', '--reduced', action='store_true', default=False)
parser.add_argument ('disk')
parser.add_argument ('par')
args = parser.parse_args()
main (args.disk, args.par, args.reduced)

View File

@ -0,0 +1,118 @@
#!/usr/bin/python3
#/**
#@file restoreImage.py
#@brief Script de ejemplo para restaurar una imagen.
#@param $1 Repositorio (CACHE, REPO o dirección IP)
#@param $2 Nombre canónico de la imagen (sin extensión)
#@param $3 Número de disco
#@param $4 Número de particion
#@param $5 Protocolo (UNICAST, UNICAST-DIRECT, MULTICAST o MULTICAST-DIRECT)
#@param $6 Opciones del protocolo
#@ejemplo restoreImage.py REPO imgname 2 2 unicast
#@exception OG_ERR_FORMAT 1 formato incorrecto.
#@exception OG_ERR_NOTFOUND 2 cambio de repositorio: repositorio no encontrado
#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados.
#@exception $OG_ERR_MCASTRECEIVERFILE 57 Error en la recepción Multicast de un fichero
#@exception $OG_ERR_PROTOCOLJOINMASTER 60 Error en la conexión de una sesión Unicast|Multicast con el Master
#**/
import os
import os.path
import sys
import re
import time
import ogGlobals
import SystemLib
import NetLib
import StringLib
import FileLib
import ImageLib
import ProtocolLib
t0 = time.time()
prog = os.path.basename (sys.argv[0])
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
# Valores por defecto: #IMGPROG="partclone" ; #IMGCOMP="lzop" ; #IMGEXT="img" #IMGREDUCE="TRUE"
## (ogGlobals se encarga)
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
open (ogGlobals.OGLOGCOMMAND, 'w').close()
if SystemLib.ogGetCaller() not in ['deployImage', 'restoreImageCustom']:
open (ogGlobals.OGLOGSESSION, 'w').close()
SystemLib.ogEcho (['log', 'session'], None, f'[1] {ogGlobals.lang.MSG_SCRIPTS_START} {prog} ({sys.argv})')
# Procesar parámetros de entrada
print (f'argv ({sys.argv}) len ({len (sys.argv)})')
if len (sys.argv) < 5:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_FORMAT}: {prog} REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones protocolo]')
sys.exit (1)
_, repo, imgname, disk, par, *other = sys.argv
proto = other[0].upper() if len (other) > 0 else 'UNICAST'
protoopt = other[1] if len (other) > 1 else ''
repo = repo.upper()
# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento
MCASTWAIT = ogGlobals.MCASTWAIT
if ':' in protoopt:
port, wait = protoopt.split (':')
else:
port, wait = ('', '')
if proto.startswith ('MULTICAST') and re.match (r'^-?\d+$', wait):
if int (MCASTWAIT or 0) < int (wait):
MCASTWAIT = int (wait) + 5
imgtype = 'img'
print (f'repo ({repo}) imgname ({imgname}) disk ({disk}) par ({par}) proto ({proto}) protoopt ({protoopt}) MCASTWAIT ({MCASTWAIT})')
# Si es una ip y es igual a la del equipo restaura desde cache
if repo == NetLib.ogGetIpAddress(): repo = 'CACHE'
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
if StringLib.ogCheckIpAddress (repo) or 'REPO' == repo:
# Si falla el cambio -> salimos con error repositorio no valido
if not NetLib.ogChangeRepo (repo):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repo)
sys.exit (1)
REPO = 'REPO'
# Comprobar que existe la imagen del origen.
imgfile = FileLib.ogGetPath (repo, f'{imgname}.{imgtype}')
imgdir = FileLib.ogGetParentPath (repo, imgname)
print (f'imgfile ({imgfile}) imgdir ({imgdir})')
if not imgfile or not imgdir:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_NOTFOUND, f'{repo}, {imgname}')
sys.exit (1)
# Procesar protocolos de transferencia.
retval = 0
if proto in ['UNICAST', 'UNICAST-DIRECT']:
SystemLib.ogEcho (['log', 'session'], None, f'[40] ogRestoreImage {repo} {imgname} {disk} {par} UNICAST')
retval = SystemLib.ogExecAndLog ('command', ImageLib.ogRestoreImage, repo, imgname, disk, par)
elif proto in ['MULTICAST', 'MULTICAST-DIRECT']:
tool = ImageLib.ogGetImageProgram ('REPO', imgname)
if not tool:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_IMAGE, f'could not get tool used for image {imgname}')
sys.exit (1)
compress = ImageLib.ogGetImageCompressor ('REPO', imgname)
if not compress:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_IMAGE, f'could not get compressor used for image {imgname}')
sys.exit (1)
SystemLib.ogEcho (['log', 'session'], None, f'[40] ogMcastReceiverPartition {disk} {par} {port} {tool} {compress}')
if not ProtocolLib.ogMcastRequest (f'{imgname}.img', protoopt):
sys.exit (1)
retval = SystemLib.ogExecAndLog ('command', ProtocolLib.ogMcastReceiverPartition, disk, par, port, tool, compress)
else:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_FORMAT}: {prog} REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones protocolo]')
sys.exit (1)
t = time.time() - t0
SystemLib.ogEcho (['log', 'session'], None, f'[100] Duracion de la operacion {int (t/60)}m {int (t%60)}s')
# Código de salida del comando prinicpal de restauración.
sys.exit (retval)

View File

@ -0,0 +1,62 @@
#!/usr/bin/python3
import os
import shutil
import ogGlobals
import SystemLib
import CacheLib
#/**
# updateBootCache
#@brief acelerador arranque pxe. incorpora a la cache el initrd y el kernel.
#@param 1
#@param ejemplo:
#@return
#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15
#@exception OG_ERR_NOTFOUND=2 # Fichero o dispositivo no encontrado.
#@note
#@todo:
#*/ ##
oglivedir = os.environ.get ('oglivedir', 'ogLive')
ogbtftp = f'/opt/oglive/tftpboot/{oglivedir}'
ogbcache = f'{ogGlobals.OGCAC}/boot/{oglivedir}'
#control de errores
if not os.path.isdir (ogbtftp):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, ogbtftp)
os.exit (1)
if not CacheLib.ogMountCache():
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTCACHE, 'CACHE')
os.exit (1)
os.makedirs (ogbcache, exist_ok=True)
# comparamos los del server
with open (f'{ogbtftp}/ogvmlinuz.sum', 'rb') as fd: servervmlinuz = fd.read()
with open (f'{ogbtftp}/oginitrd.img.sum', 'rb') as fd: serverinitrd = fd.read()
#comparamos los de la cache
with open (f'{ogbcache}/ogvmlinuz.sum', 'rb') as fd: cachevmlinuz = fd.read()
with open (f'{ogbcache}/oginitrd.img.sum', 'rb') as fd: cacheinitrd = fd.read()
print (f'MD5 on SERVER: {servervmlinuz} {serverinitrd}')
print (f'MD5 on CACHE: {cachevmlinuz} {cacheinitrd}')
do_reboot = '0'
if cachevmlinuz != servervmlinuz:
print ('ogvmlinuz updating')
shutil.copy2 (f'{ogbtftp}/ogvmlinuz', f'{ogbcache}/ogvmlinuz')
shutil.copy2 (f'{ogbtftp}/ogvmlinuz.sum', f'{ogbcache}/ogvmlinuz.sum')
do_reboot = '1'
if cacheinitrd != serverinitrd:
print ('oginitrd updating')
shutil.copy2 (f'{ogbtftp}/oginitrd.img', f'{ogbcache}/oginitrd.img')
shutil.copy2 (f'{ogbtftp}/oginitrd.img.sum', f'{ogbcache}/oginitrd.img.sum')
do_reboot = '1'
print (do_reboot)
os.exit (0)

View File

@ -0,0 +1,219 @@
#!/usr/bin/python3
#/**
# updateCache
#@brief Actualiza la cache del cliente con imagen o fichero iso.
#@param 1 REPO Origen del fichero. -accesible por nfs-samba-
#@param 2 str_fichero nombre del fichero a actualizar.
#@param 3 str_protoco. TORRENT | MULTICAST | UNICAST.
#@param 4 str_opcionesprotocolo
#@param 4 str_opcionesupdatecache
#@ejemplo: updateCache.py REPO imgname.img UNICAST 8042:42
#@return
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTCACHE No existe cache -15-
#@exception $OG_ERR_CACHESIZE Tamaño de la paticion menor al archivo a descargar -16-
#@exception $OG_ERR_MCASTRECEIVERFILE Error en la recepción Multicast de un fichero -57-
#@exception $OG_ERR_PROTOCOLJOINMASTER Error en la conexión de una sesión Unicast|Multicast con el Master -60-
#@note
#@todo:
#*/ ##
import os.path
import sys
import re
import time
import subprocess
import shutil
import glob
import random
import ogGlobals
import SystemLib
import StringLib
import NetLib
import CacheLib
import FileLib
import ProtocolLib
import FileSystemLib
prog = os.path.basename (sys.argv[0])
print (f'argv ({sys.argv}) len ({len (sys.argv)})')
if len (sys.argv) < 3:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_FORMAT}: {prog} str_REPO _str_Relative_Path_OGIMG_with_/ PROTOCOLO OPCIONES_PROTOCOLO OPCIONES_UPDATECACHE')
sys.exit (1)
_, repositorio, path, protocolo, *other = sys.argv
optprotocolo = other[0] if len (other) > 0 else ''
cacheopts = other[1] if len (other) > 1 else ''
if 'RSYNC' == protocolo:
raise Exception ('synchronised images are no longer supported')
#Carga del configurador del engine
## (ogGlobals se encarga)
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
open (ogGlobals.OGLOGCOMMAND, 'w').close()
if SystemLib.ogGetCaller() not in ['deployImage', 'restoreBaseImage', 'restoreDiffImage']:
open (ogGlobals.OGLOGSESSION, 'w').close()
SystemLib.ogEcho (['log', 'session'], None, f'[1] {ogGlobals.lang.MSG_SCRIPTS_START} {prog} {sys.argv}')
# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento
MCASTWAIT = ogGlobals.MCASTWAIT
if ':' in optprotocolo:
port, wait, *other = optprotocolo.split (':')
else:
port, wait = ('', '')
if protocolo.startswith ('MULTICAST') and re.match (r'^-?\d+$', wait):
if int (MCASTWAIT or 0) < int (wait):
MCASTWAIT = int (wait) + 5
# Unidad organizativa.
## (no longer supported)
#print (f'repositorio ({repositorio}) path ({path}) protocolo ({protocolo}) optprotocolo ({optprotocolo}) cacheopts ({cacheopts}) MCASTWAIT ({MCASTWAIT})')
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
if StringLib.ogCheckIpAddress (repositorio) or 'REPO' == repositorio:
if not NetLib.ogChangeRepo (repositorio):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repositorio)
sys.exit (1)
repositorio = 'REPO'
repoip = NetLib.ogGetRepoIp()
SystemLib.ogEcho (['log', 'session'], None, f'{repositorio} {repoip} {protocolo} {optprotocolo}')
# Si el repositorio local CACHE no existe error 15.
if not CacheLib.ogFindCache():
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_NOTCACHE, 'CACHE')
sys.exit (1)
# comprobar si la imagen existe (.img, .img.diff o directorio)
repofile = FileLib.ogGetPath ('REPO', f'/{path}')
if not os.path.exists (repofile):
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_NOTFOUND, f'REPO /{path}')
sys.exit (1)
SystemLib.ogEcho (['log', 'session'], None, ogGlobals.lang.MSG_SCRIPTS_UPDATECACHE_DOUPDATE)
# Distingo si es monolitica o sincronizable
f = subprocess.run (['file', repofile], capture_output=True, text=True).stdout.lower()
if ' btrfs filesystem ' in f or ' ext4 filesystem ' in f or ' directory' in f:
raise Exception ('synchronised images are no longer supported')
rc = ProtocolLib.ogUpdateCacheIsNecesary (repositorio, path, protocolo)
# si rc=True: actualizamos; si rc=False: no actualizamos (exit 0); si rc=None: exit error
if rc == True: pass ## es necesario actualizar
elif rc == False: sys.exit (0) ## no es necesario actualizar
elif rc == None: sys.exit (ogGlobals.OG_ERR_UPDATECACHE) ## hubo errores
SystemLib.ogEcho (['log', 'session'], None, ogGlobals.lang.MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE)
cachesize = CacheLib.ogGetCacheSize()
cache_disk, cache_par = CacheLib.ogFindCache().split()
cachesizefree = FileSystemLib.ogGetFreeSize (cache_disk, cache_par)
path_repo = FileLib.ogGetPath ('REPO', path)
filesize = int (subprocess.run (['ls', '-sk', path_repo], capture_output=True, text=True).stdout.split()[0])
realfilesize = subprocess.run (['stat', '--format', '%s', repofile], capture_output=True, text=True).stdout
realfilesize = int (int (realfilesize) / 1024)
# La sincronizada, si existe la imagen en cache el espacio necesario
# es la nueva menos lo que ocupa la que ya hay.
sizerequired = filesize
#ERROR CACHESIZE 16 (tamanyo de la CACHE insuficiente)
if sizerequired >= cachesize:
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_WARNING}: {ogGlobals.lang.MSG_ERR_CACHESIZE}: {path} = {sizerequired} > CACHE = {cachesize}')
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_CACHESIZE, 'CACHE')
sys.exit (1)
#ERROR CACHESIZE 16 (Espacio libre en CACHE insuficiente)
if sizerequired >= cachesizefree:
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO}: ACTIONCACHEFULL={ogGlobals.ACTIONCACHEFULL}')
if 'NONE' == ogGlobals.ACTIONCACHEFULL:
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_WARNING}: {ogGlobals.lang.MSG_ERR_CACHESIZE}: {path} = {sizerequired} > FREE SPACE CACHE = {cachesizefree}')
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_CACHESIZE, 'CACHE FULL, NO SPACE FREE')
sys.exit (1)
elif 'FORMAT' == ogGlobals.ACTIONCACHEFULL:
SystemLib.ogEcho (['log', 'session'], None, f'[51] {ogGlobals.lang.MSG_HELP_ogFormatCache}')
CacheLib.ogUnmountCache()
CacheLib.ogFormatCache()
CacheLib.ogMountCache()
elif 'DELETE' == ogGlobals.ACTIONCACHEFULL:
SystemLib.ogEcho (['log', 'session'], None, f'[51] {ogGlobals.lang.MSG_HELP_ogDeleteTree} {ogGlobals.OGCAC}{ogGlobals.OGIMG}/*')
for d in glob.glob (f'{ogGlobals.OGCAC}{ogGlobals.OGIMG}/*'):
shutil.rmtree (d)
else:
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_WARNING}: {ogGlobals.lang.MSG_ERR_CACHESIZE}: {path} = {filesize} > CACHE = {cachesizefree}')
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_CACHESIZE, 'CACHE')
sys.exit (1)
# Comprobamos que imagen cache igual a la del repo. Si sincronizada no podemos comprobar.
## nati: esto ya lo hicimos mas arriba...
rc = ProtocolLib.ogUpdateCacheIsNecesary (repositorio, path, protocolo)
# si rc=True: actualizamos; si rc=False: no actualizamos (exit 0); si rc=None: exit error
if rc == True: pass ## es necesario actualizar
elif rc == False: sys.exit (0) ## no es necesario actualizar
elif rc == None: sys.exit (ogGlobals.OG_ERR_UPDATECACHE) ## hubo errores
CacheLib.ogMountCache()
## Si no existe, crear subdirectorio para el fichero en la cache.
imgdir = FileLib.ogGetParentPath ('CACHE', f'/{path}')
if not imgdir:
SystemLib.ogEcho (['log', 'session'], None, f'[5] {ogGlobals.lang.MSG_HELP_ogMakeDir} "{path} {os.path.dirname (path)}".')
FileLib.ogMakeDir ('CACHE', os.path.dirname (f'/{path}'))
imgdir = ogGetParentPath ('CACHE', f'/{path}')
if not imgdir:
sys.exit (1)
t0 = time.time()
if 'TORRENT' == protocolo:
SystemLib.ogEcho (['log', 'session'], None, f'ogCopyFile {repositorio} {path}.torrent absolute {ogGlobals.OGCAC}/{ogGlobals.OGIMG}')
mac_digits = NetLib.ogGetMacAddress().split (':')
timewait = int ('0x' + mac_digits[4] + mac_digits[5], 16) * 120 / 65535
if not SystemLib.ogExecAndLog ('command', FileLib.ogCopyFile, {'container':repositorio, 'file':f'{path}.torrent'}, {'file':imgdir}):
sys.exit (1)
p2pwait = random.randint (1, 121)
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TASK_SLEEP} : {p2pwait} seconds')
time.sleep (p2pwait)
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TASK_START}: ogTorrentStart CACHE {path}.torrent {optprotocolo}')
SystemLib.ogExecAndLog ('command', ProtocolLib.ogTorrentStart, 'CACHE', f'{path}.torrent', optprotocolo)
resumeupdatecache = subprocess.run (['grep', '--max-count', '1', '--before-context', '1', 'Download', ogGlobals.OGLOGCOMMAND], capture_output=True, text=True).stdout
resumeupdatecachebf = subprocess.run (['grep', '--max-count', '1', 'Download', ogGlobals.OGLOGCOMMAND], capture_output=True, text=True).stdout
if 'Download complete.' == resumeupdatecachebf:
os.unlink (imgdir + path + '.torrent.bf')
elif 'MULTICAST' == protocolo:
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION}: {repoip}:{port}')
time.sleep (random.randint (1, 31))
SystemLib.ogEcho (['log', 'session'], None, f'ogMcastRequest {path} {optprotocolo}')
if not SystemLib.ogExecAndLog ('command', ProtocolLib.ogMcastRequest, path, optprotocolo):
sys.exit (1)
SystemLib.ogEcho (['log', 'session'], None, f'ogMcastReceiverFile {port} CACHE {path}')
if not SystemLib.ogExecAndLog ('command', ProtocolLib.ogMcastReceiverFile, sess=port, container='CACHE', file=path):
sys.exit (1)
resumeupdatecache = subprocess.run (['grep', '--max-count', '1', '--before-context', '1', 'Transfer complete', f'{ogGlobals.OGLOGCOMMAND}.tmp'], capture_output=True, text=True).stdout
elif 'UNICAST' == protocolo:
print (f'ogExecAndLog ("command", FileLib.ogCopyFile, {{"container":{repositorio}, "file":{path}}}, {{"file":{imgdir}}})')
SystemLib.ogExecAndLog ('command', FileLib.ogCopyFile, {'container':repositorio, 'file':path}, {'file':imgdir})
time.sleep (5)
resumeupdatecache = subprocess.run (['grep', '--max-count', '1', '100%', f'{ogGlobals.OGLOGCOMMAND}.tmp'], capture_output=True, text=True).stdout
elif 'RSYNC' == protocolo:
raise Exception ('synchronised images are no longer supported')
t = time.time() - t0
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {resumeupdatecache} ')
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TIME_PARTIAL} updateCache {int (t/60)}m {int (t%60)}s')
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TASK_START} {ogGlobals.lang.MSG_HELP_ogCalculateChecksum} ')
t0 = time.time()
# Si es imagen sincronizada siempre da distinto md5. No podemos comprobar
rc = ProtocolLib.ogUpdateCacheIsNecesary (repositorio, path, protocolo)
if 'deployImage' != SystemLib.ogGetCaller():
t = time.time() - t0
SystemLib.ogEcho (['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TIME_PARTIAL} {ogGlobals.lang.MSG_HELP_ogCalculateChecksum} {int (t/60)}m {int (t%60)}s')
# si rc todavia es True: exit error; si rc=False: todo bien (exit 0); si rc=None: exit error
if rc == True: sys.exit (ogGlobals.OG_ERR_UPDATECACHE)
elif rc == False: sys.exit (0)
elif rc == None: sys.exit (ogGlobals.OG_ERR_UPDATECACHE)