refs #1114 scripts function call updates

pull/1/head
Antonio Guerrero 2024-11-07 06:10:58 +00:00
parent 150685fe75
commit e73700a57d
24 changed files with 211 additions and 174 deletions

0
client/shared/scripts/__init__.py 100644 → 100755
View File

34
client/shared/scripts/bootOS.py 100644 → 100755
View File

@ -1,6 +1,10 @@
import sys
import os
import subprocess
import SystemLib
import FileSystemLib
import DiskLib
import Boot
#!/usr/bin/env python3
# Script de ejemplo para arrancar un sistema operativo instalado.
@ -9,18 +13,18 @@ import subprocess
def main():
prog = os.path.basename(__file__)
if len(sys.argv) < 3 or len(sys.argv) > 6:
og_raise_error(1, f"Formato: {prog} ndisco nfilesys [str_kernel str_initrd str_kernelparams]")
SystemLib.ogRaiseError(1, f"Formato: {prog} ndisco nfilesys [str_kernel str_initrd str_kernelparams]")
disk = sys.argv[1]
filesystem = sys.argv[2]
try:
part = og_disk_to_dev(disk, filesystem)
part = DiskLib.ogDiskToDev(disk, filesystem)
except Exception as e:
sys.exit(1)
try:
mntdir = og_mount(disk, filesystem)
mntdir = FileSystemLib.ogMount(disk, filesystem)
except Exception as e:
sys.exit(1)
@ -28,17 +32,17 @@ def main():
mount_output = subprocess.getoutput(f"mount | grep -q '{mntdir}.*(rw'")
if mount_output:
og_echo("log", "session", "MSG_WARNING: MSG_MOUNTREADONLY")
og_unmount(disk, filesystem)
og_check_fs(disk, filesystem)
SystemLib.ogEcho("log", "session", "MSG_WARNING: MSG_MOUNTREADONLY")
FileSystemLib.ogUnmount(disk, filesystem)
FileSystemLib.ogCheckFs(disk, filesystem)
part = og_disk_to_dev(disk, filesystem)
part = DiskLib.ogDiskToDev(disk, filesystem)
os.makedirs(mntdir, exist_ok=True)
subprocess.run(["ntfs-3g", "-o", "remove_hiberfile", part, mntdir])
og_echo("log", "session", "Particion desbloqueada")
SystemLib.ogEcho("log", "session", "Particion desbloqueada")
og_unmount(disk, filesystem)
og_mount(disk, filesystem)
FileSystemLib.ogUnmount(disk, filesystem)
FileSystemLib.ogMount(disk, filesystem)
if subprocess.call("which bootOsCustom", shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
print("[10] Configuración personalizada del inicio.")
@ -46,13 +50,13 @@ def main():
print("[70] Desmontar todos los sistemas de archivos.")
subprocess.run(["sync"])
for i in range(1, len(og_disk_to_dev(disk, filesystem).split())):
og_unmount_all(i)
for i in range(1, len(DiskLib.ogDiskToDev(disk, filesystem).split())):
FileSystemLib.ogUnmountAll(i)
print("[80] Desmontar cache local.")
og_unmount_cache()
FileSystemLib.ogUnmount_cache()
print("[90] Arrancar sistema operativo.")
og_boot(sys.argv[1:])
BootLib.ogBoot(sys.argv[1:])
if __name__ == "__main__":
main()
main()

View File

@ -1,5 +1,10 @@
import sys
import os
import SystemLib
import DiskLib
import FileSystemLib
import NetLib
import FileLib
#!/usr/bin/env python3
"""
@ -12,7 +17,6 @@ bootOsCustom
@version 1.1.1 Soporta varios discos
"""
# CONFIGURAR: Partición de datos de Windows que no queremos ocultar (valor por defecto '0' no oculta nada)
DISKDATA = 0
PARTDATA = 0
@ -21,7 +25,7 @@ PROG = os.path.basename(__file__)
# Control de errores
if len(sys.argv) < 3:
ogRaiseError(OG_ERR_FORMAT, f"Formato: {PROG} ndisco nparticion")
SystemLib.ogRaiseError(OG_ERR_FORMAT, f"Formato: {PROG} ndisco nparticion")
sys.exit(1)
# Parámetros obligatorios.
@ -29,61 +33,61 @@ DISK = sys.argv[1] # Nº de disco.
PART = sys.argv[2] # Nº de partición.
# Paso 0: Añadir código para realizar control de errores de los parámetros de entrada (recomendado).
DEVICE = ogDiskToDev(DISK, PART)
DEVICE = DiskLib.ogDiskToDev(DISK, PART)
if not DEVICE:
sys.exit(1)
# Paso 1: Adaptar el código de ejemplo para arranque personalizado.
# Nota: el script "bootOs" llama al script "bootOsCustom" después de realizar la operaciones de inicio estándar y antes de desmontar las particiones e iniciar el sistema operativo.
MNTDIR = ogMount(DISK, PART)
MNTDIR = FileSystemLib.ogMount(DISK, PART)
if not MNTDIR:
sys.exit(1)
NAME = ogGetHostname()
NAME = NetLib.ogGetHostname()
NAME = NAME if NAME else "pc"
OSTYPE = ogGetOsType(DISK, PART)
OSTYPE = Inventory.ogGetOsType(DISK, PART)
if OSTYPE == "Windows":
# Mostrar las particiones NTFS de sistema (dos opciones)
# Opción 1: SIN ocultar las demás.
# ogEcho log session "[40] Mostrar y activar particion de Windows {PART}."
# if ogGetPartitionType(DISK, PART) in ["HNTFS", "WIN-RESERV"]:
# ogUnhidePartition(DISK, PART)
# SystemLib.ogEcho log session "[40] Mostrar y activar particion de Windows {PART}."
# if DiskLib.ogGetPartitionType(DISK, PART) in ["HNTFS", "WIN-RESERV"]:
# DiskLib.ogUnhidePartition(DISK, PART)
# Recorremos los distintos discos
# for DEVICE in ogDiskToDev():
# d = ogDevToDisk(DEVICE)
# for DEVICE in DiskLib.ogDiskToDev():
# d = DiskLib.ogDevToDisk(DEVICE)
# # Mostrar las particiones NTFS de sistema (dos opciones)
# # Opción 2: Ocultamos las demás.
# ogEcho log session "[40] Activar particion de Windows {PART} y ocultar las demás."
# for i in range(1, ogGetPartitionsNumber(d) + 1):
# SystemLib.ogEcho log session "[40] Activar particion de Windows {PART} y ocultar las demás."
# for i in range(1, DiskLib.ogGetPartitionsNumber(d) + 1):
# if (d == DISK and i == PART) or (d == DISKDATA and i == PARTDATA):
# if ogGetPartitionType(d, i) in ["HNTFS", "WIN-RESERV"]:
# ogUnhidePartition(d, i)
# if DiskLib.ogGetPartitionType(d, i) in ["HNTFS", "WIN-RESERV"]:
# DiskLib.ogUnhidePartition(d, i)
# else:
# if ogGetPartitionType(d, i) in ["NTFS", "WINDOWS"]:
# ogHidePartition(d, i)
# if DiskLib.ogGetPartitionType(d, i) in ["NTFS", "WINDOWS"]:
# DiskLib.ogHidePartition(d, i)
# # Borrar marcas de arrranque de todos los Windows instalados en el disco.
# ogEcho log session "[30] Borrar marcas de arrranque de todos los Windows instalados en el disco."
# for i in range(1, ogGetPartitionsNumber(d) + 1):
# if ogGetOsType(d, i) == "Windows":
# ogMount(d, i)
# SystemLib.ogEcho log session "[30] Borrar marcas de arrranque de todos los Windows instalados en el disco."
# for i in range(1, DiskLib.ogGetPartitionsNumber(d) + 1):
# if Inventory.ogGetOsType(d, i) == "Windows":
# FileSystemLib.ogMount(d, i)
# os.system("rm -f /mnt/*/ogboot.*")
elif OSTYPE == "Linux":
# Modificar el nombre del equipo
# ogEcho log session "[30] Asignar nombre Linux \"{NAME}\"."
# ETC = ogGetPath(DISK, PART, "/etc")
# SystemLib.ogEcho log session "[30] Asignar nombre Linux \"{NAME}\"."
# ETC = FileLib.ogGetPath(DISK, PART, "/etc")
# if os.path.isdir(ETC):
# with open(os.path.join(ETC, "hostname"), "w") as f:
# f.write(NAME)
# Sustituir UUID o LABEL por su dispositivo en definición de sistema de archivo raíz.
# if os.path.isfile(os.path.join(ETC, "fstab")):
# ogEcho log session "[40] Actualizar fstab con particion raíz \"{PART}\"."
# SystemLib.ogEcho log session "[40] Actualizar fstab con particion raíz \"{PART}\"."
# with open(os.path.join(ETC, "fstab"), "r") as f:
# lines = f.readlines()
# with open("/tmp/fstab", "w") as f:
@ -97,5 +101,5 @@ elif OSTYPE == "Linux":
# En el servidor el nuevo fichero debe situarse en el directorio del grupo:
# /opt/opengnsys/images/groups/nombre_aula
# if os.path.isfile(os.path.join(ogGetGroupDir(), "passwd")):
# ogEcho log session "[65] Cambiar claves de usuarios."
# os.system(f"cp {os.path.join(ogGetGroupDir(), 'passwd')} {os.path.join(MNTDIR, 'etc')}")
# SystemLib.ogEcho log session "[65] Cambiar claves de usuarios."
# os.system(f"cp {os.path.join(ogGetGroupDir(), 'passwd')} {os.path.join(MNTDIR, 'etc')}")

View File

View File

View File

@ -1,5 +1,6 @@
import sys
import DiskLib
if __name__ == "__main__":
result = og_create_partitions(sys.argv[1:])
sys.exit(result.returncode)
result = DiskLib.ogCreatePartitions(sys.argv[1:])
sys.exit(result.returncode)

View File

@ -1,13 +1,17 @@
import os
import sys
import time
import SystemLib
import DiskLib
import NetLib
import ImageLib
#!/usr/bin/env python3
def main():
PROG = os.path.basename(__file__)
if len(sys.argv) < 5:
ogRaiseError("session", OG_ERR_FORMAT, f"{MSG_FORMAT}: {PROG} REPO imagen ndisco nparticion [ UNICAST-DIRECT|UNICAST|UNICAST-CACHE|MULTICAST-DIRECT|MULTICAST|MULTICAST-CACHE|TORRENT [opciones protocolo] ]")
SystemLib.ogRaiseError("session", OG_ERR_FORMAT, f"{MSG_FORMAT}: {PROG} REPO imagen ndisco nparticion [ UNICAST-DIRECT|UNICAST|UNICAST-CACHE|MULTICAST-DIRECT|MULTICAST|MULTICAST-CACHE|TORRENT [opciones protocolo] ]")
sys.exit(1)
TIME1 = time.time()
@ -24,36 +28,36 @@ def main():
with open(OGLOGCOMMAND, 'w') as f:
f.write(" ")
if ogGetCaller() != "EjecutarScript":
if SystemLib.ogGetCaller() != "EjecutarScript":
with open(OGLOGSESSION, 'w') as f:
f.write("")
ogEcho("log", "session", f"[1] {MSG_SCRIPTS_START} {PROG} {' '.join(sys.argv)}")
SystemLib.ogEcho("log", "session", f"[1] {MSG_SCRIPTS_START} {PROG} {' '.join(sys.argv)}")
if ogIsLocked(DISK, PART):
sys.exit(ogRaiseError("session", OG_ERR_LOCKED, f"{MSG_PARTITION}, {DISK} {PART}"))
if FileSystemLib.ogIsLocked(DISK, PART):
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_LOCKED, f"{MSG_PARTITION}, {DISK} {PART}"))
ogEcho("log", "session", f"{MSG_HELP_ogUnmount} {DISK} {PART}")
ogUnmount(DISK, PART)
SystemLib.ogEcho("log", "session", f"{MSG_HELP_FileSystemLib.ogUnmount} {DISK} {PART}")
FileSystemLib.ogUnmount(DISK, PART)
if REPO == ogGetIpAddress() or REPO == "CACHE":
if REPO == NetLib.ogGetIpAddress() or REPO == "CACHE":
MODE = "CACHE"
else:
if ogCheckIpAddress(REPO) == 0 or REPO == "REPO":
if not ogChangeRepo(REPO, OGUNIT):
sys.exit(ogRaiseError(OG_ERR_NOTFOUND, f"{REPO} {OGUNIT}"))
if DiskLib.ogCheckIpAddress(REPO) == 0 or REPO == "REPO":
if not NetLib.ogChangeRepo(REPO, OGUNIT):
sys.exit(SystemLib.ogRaiseError(OG_ERR_NOTFOUND, f"{REPO} {OGUNIT}"))
MODE = "REPO"
IMGOS = ogGetImageInfo(ogGetPath(MODE, f"{IMGNAME}.img"))
IMGOS = ImageLib.ogGetImageInfo(ogGetPath(MODE, f"{IMGNAME}.img"))
if IMGOS == 1:
sys.exit(ogRaiseError("session", OG_ERR_NOTFOUND, f"{REPO} {IMGNAME}"))
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_NOTFOUND, f"{REPO} {IMGNAME}"))
elif IMGOS == 5:
sys.exit(ogRaiseError("session", OG_ERR_IMAGEFILE, f"{REPO} {IMGNAME}"))
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_IMAGEFILE, f"{REPO} {IMGNAME}"))
elif IMGOS != 0:
sys.exit(ogRaiseError("session", OG_ERR_GENERIC))
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_GENERIC))
IMGSIZE = os.path.getsize(ogGetPath(MODE, f"{IMGNAME}.img")) // 1024
ogEcho("log", "session", f"[1] REPO={REPO} IMG-FILE={IMGNAME}.img SIZE={IMGSIZE} (KB) METADATA={IMGOS}")
SystemLib.ogEcho("log", "session", f"[1] REPO={REPO} IMG-FILE={IMGNAME}.img SIZE={IMGSIZE} (KB) METADATA={IMGOS}")
if MODE == "CACHE":
NEXTOPERATION = "CACHE"
@ -62,36 +66,36 @@ def main():
NEXTOPERATION = PROTO.split('-')[0]
elif PROTO in ["TORRENT", "TORRENT-CACHE", "MULTICAST", "MULTICAST-CACHE", "UNICAST", "UNICAST-CACHE"]:
PROTO = PROTO.split('-')[0]
ogEcho("log", "session", f"[2] updateCache {REPO} /{IMGNAME}.img {PROTO} {PROTOOPT}")
SystemLib.ogEcho("log", "session", f"[2] updateCache {REPO} /{IMGNAME}.img {PROTO} {PROTOOPT}")
TIME2 = time.time()
RETVAL = updateCache(REPO, f"/{IMGNAME}.img", PROTO, PROTOOPT)
TIME2 = time.time() - TIME2
ogEcho("log", "session", f" [ ] {MSG_SCRIPTS_TIME_PARTIAL} updateCache {TIME2 // 60}m {TIME2 % 60}s")
SystemLib.ogEcho("log", "session", f" [ ] {MSG_SCRIPTS_TIME_PARTIAL} updateCache {TIME2 // 60}m {TIME2 % 60}s")
if RETVAL == 0:
ogEcho("log", "session", "[50] updateCache (OK)")
SystemLib.ogEcho("log", "session", "[50] updateCache (OK)")
NEXTOPERATION = "CACHE"
elif RETVAL in [15, 16]:
ogEcho("log", "session", f"[50] {MSG_ERR_NOTCACHE} ; {MSG_ERR_CACHESIZE}")
ogEcho("log", "session", f"[50] {MSG_SCRIPTS_CHECK_ENGINE}: RESTOREPROTOCOLNOTCACHE={RESTOREPROTOCOLNOTCACHE}")
SystemLib.ogEcho("log", "session", f"[50] {MSG_ERR_NOTCACHE} ; {MSG_ERR_CACHESIZE}")
SystemLib.ogEcho("log", "session", f"[50] {MSG_SCRIPTS_CHECK_ENGINE}: RESTOREPROTOCOLNOTCACHE={RESTOREPROTOCOLNOTCACHE}")
if RESTOREPROTOCOLNOTCACHE == "MULTICAST":
NEXTOPERATION = "MULTICAST" if PROTO == "MULTICAST" else "UNICAST"
elif RESTOREPROTOCOLNOTCACHE == "UNICAST":
NEXTOPERATION = "UNICAST"
elif RESTOREPROTOCOLNOTCACHE == "NONE":
if RETVAL == 15:
ogEcho("log", "session", f"[100] {MSG_ERR_NOTCACHE}")
sys.exit(ogRaiseError("session", OG_ERR_NOTCACHE, "NOT CACHE"))
SystemLib.ogEcho("log", "session", f"[100] {MSG_ERR_NOTCACHE}")
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_NOTCACHE, "NOT CACHE"))
elif RETVAL == 16:
ogEcho("log", "session", f"[100] {MSG_ERR_CACHESIZE}")
sys.exit(ogRaiseError("session", OG_ERR_CACHESIZE, "CACHE FULL"))
SystemLib.ogEcho("log", "session", f"[100] {MSG_ERR_CACHESIZE}")
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_CACHESIZE, "CACHE FULL"))
elif RETVAL in [57, 60]:
sys.exit(RETVAL)
else:
sys.exit(RETVAL)
else:
sys.exit(ogRaiseError("session", OG_ERR_FORMAT, f"{MSG_ERR_FORMAT}, {PROTO}"))
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_FORMAT, f"{MSG_ERR_FORMAT}, {PROTO}"))
else:
sys.exit(ogRaiseError("session", OG_ERR_FORMAT, f"{MSG_ERR_FORMAT}, {REPO}"))
sys.exit(SystemLib.ogRaiseError("session", OG_ERR_FORMAT, f"{MSG_ERR_FORMAT}, {REPO}"))
TIME3 = time.time()
@ -103,37 +107,37 @@ def main():
PARAMS = f"{REPO} {IMGNAME} {DISK} {PART} {PROTO} {PROTOOPT}"
if os.system("which restoreImageCustom") == 0:
ogEcho("log", "session", f"[55] {MSG_HELP_ogRestoreImage}: restoreImageCustom {PARAMS}")
SystemLib.ogEcho("log", "session", f"[55] {MSG_HELP_ogRestoreImage}: restoreImageCustom {PARAMS}")
os.system(f"restoreImageCustom {PARAMS}")
else:
ogEcho("log", "session", f"[55] {MSG_HELP_ogRestoreImage}: restoreImage {PARAMS}")
SystemLib.ogEcho("log", "session", f"[55] {MSG_HELP_ogRestoreImage}: restoreImage {PARAMS}")
os.system(f"restoreImage {PARAMS}")
RETVAL = os.system(f"restoreImage {PARAMS}")
RESUMERESTOREIMAGE = os.popen(f"grep -m 1 'Total Time:' {OGLOGCOMMAND}").read()
ogEcho("log", "session", f" [ ] {RESUMERESTOREIMAGE}")
SystemLib.ogEcho("log", "session", f" [ ] {RESUMERESTOREIMAGE}")
if RETVAL != 0:
ogRaiseError("session", OG_ERR_IMAGE, f"{REPO} {IMGNAME}")
if ogGetCaller() != "EjecutarScript":
ogEcho("log", "session", f"{MSG_INTERFACE_END} {OG_ERR_IMAGE}")
SystemLib.ogRaiseError("session", OG_ERR_IMAGE, f"{REPO} {IMGNAME}")
if SystemLib.ogGetCaller() != "EjecutarScript":
SystemLib.ogEcho("log", "session", f"{MSG_INTERFACE_END} {OG_ERR_IMAGE}")
sys.exit(OG_ERR_IMAGE)
TIME3 = time.time() - TIME3
ogEcho("log", "session", f" [ ] {MSG_SCRIPTS_TIME_PARTIAL} : {TIME3 // 60}m {TIME3 % 60}s")
SystemLib.ogEcho("log", "session", f" [ ] {MSG_SCRIPTS_TIME_PARTIAL} : {TIME3 // 60}m {TIME3 % 60}s")
if os.system("which configureOsCustom") == 0:
ogEcho("log", "session", "[90] configureOsCustom")
SystemLib.ogEcho("log", "session", "[90] configureOsCustom")
os.system(f"configureOsCustom {DISK} {PART} {REPO} {IMGNAME}")
else:
ogEcho("log", "session", f"[90] {MSG_SCRIPTS_OS_CONFIGURE}")
SystemLib.ogEcho("log", "session", f"[90] {MSG_SCRIPTS_OS_CONFIGURE}")
os.system(f"configureOs {DISK} {PART}")
TIME = time.time() - TIME1
ogEcho("log", "session", f"[100] {MSG_SCRIPTS_TIME_TOTAL} {TIME // 60}m {TIME % 60}s")
SystemLib.ogEcho("log", "session", f"[100] {MSG_SCRIPTS_TIME_TOTAL} {TIME // 60}m {TIME % 60}s")
if ogGetCaller() != "EjecutarScript":
ogEcho("log", "session", f"{MSG_INTERFACE_END} {RETVAL}")
if SystemLib.ogGetCaller() != "EjecutarScript":
SystemLib.ogEcho("log", "session", f"{MSG_INTERFACE_END} {RETVAL}")
sys.exit(RETVAL)
if __name__ == "__main__":
main()
main()

10
client/shared/scripts/formatFs.py 100644 → 100755
View File

@ -1,6 +1,8 @@
import sys
import time
import subprocess
import SystemLib
import FileSystemLib
#!/usr/bin/env python3
# Script de ejemplo para formatear un sistema de archivos.
@ -11,20 +13,20 @@ def main():
prog = sys.argv[0]
if len(sys.argv) != 3:
ogRaiseError(1, f"{prog} ndisco nparticion")
SystemLib.ogRaiseError(1, f"{prog} ndisco nparticion")
disk = sys.argv[1]
partition = sys.argv[2]
# Desmontar y formatear el sistema de archivos.
print("[5] Desmontando sistema de archivos")
ogUnmountFs(disk, partition)
FileSystemLib.ogUnmountFs(disk, partition)
print("[20] Formateando sistema de archivos")
ogFormatFs(disk, partition)
FileSystemLib.ogFormatFs(disk, partition)
elapsed_time = time.time() - start_time
minutes, seconds = divmod(int(elapsed_time), 60)
print(f"[100] Duración de la operación {minutes}m {seconds}s")
if __name__ == "__main__":
main()
main()

View File

@ -1,7 +1,8 @@
#!/usr/bin/env python3
import os
import subprocess
#!/usr/bin/env python3
# generateMenuDefault - Crea fichero con la página web de inicio del cliente
# con información de red y de los sistemas operativos instalados,
# crea fichero con información del contenido de la caché local.
@ -89,4 +90,4 @@ with open(FILEINFOHTML, 'a') as f:
# Crear contenido de la caché.
with open(FILEINFOCACHE, 'a') as f:
f.write(subprocess.getoutput(CACHECONTENIDO))
f.write(subprocess.getoutput(CACHECONTENIDO))

View File

@ -1,5 +1,6 @@
import sys
import FileSystemLib
if __name__ == "__main__":
output = ogGetFsType(sys.argv[1:])
print(output)
output = FileSystemLib.ogGetFsType(sys.argv[1:])
print(output)

View File

@ -1,17 +1,16 @@
#!/usr/bin/env python3
import subprocess
import sys
from NetLib import ogGetIpAddress
import NetLib
def get_ip_address(*args):
try:
# Ejecuta ogGetIpAddress como un comando en el sistema
result = subprocess.run(["/opt/opengnsys/client/lib/engine/bin/ogGetIpAddress"] + list(args),
capture_output=True, text=True, check=True)
print(result.stdout.strip())
except subprocess.CalledProcessError as e:
# Llama a ogGetIpAddress desde NetLib y captura el resultado
result = NetLib.ogGetIpAddress(*args)
print(result.strip())
except Exception as e:
print(f"Error ejecutando ogGetIpAddress: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
get_ip_address(*sys.argv[1:])

View File

@ -1,12 +1,14 @@
import subprocess
import sys
import InventoryLib
def main():
try:
subprocess.run(["ogGetOsVersion"] + sys.argv[1:], check=True)
except subprocess.CalledProcessError as e:
result = InventoryLib.ogGetOsVersion(*sys.argv[1:])
print(result.strip())
except Exception as e:
print(f"An error occurred: {e}", file=sys.stderr)
sys.exit(e.returncode)
sys.exit(1)
if __name__ == "__main__":
main()
main()

View File

@ -1,6 +1,7 @@
import os
import subprocess
import sys
import DiskLib
#!/usr/bin/env python3
@ -41,8 +42,8 @@ def prepare_grub_to_access_device(device):
print(f"insmod {module}")
if "nvme" in device:
d, p = ogDevToDisk(device)
if ogGetPartitionTableType(d) == "GPT":
d, p = DiskLib.ogDevToDisk(device)
if DiskLib.ogGetPartitionTableType(d) == "GPT":
nvme_device = f"hd{d-1},gpt{p}"
else:
nvme_device = f"hd{d-1},{p-1}"
@ -85,7 +86,7 @@ def main():
f.write("DISTRIB_DESCRIPTION=OpenGnsys Live\n")
if disk:
os_search = ogDiskToDev(disk, part)
os_search = DiskLib.ogDiskToDev(disk, part)
os_probed = run_command(f"os-prober | grep {os_search} | tr ' ' '^' | paste -s -d ' '")
else:
os_probed = run_command("os-prober | tr ' ' '^' | paste -s -d ' '")
@ -193,4 +194,4 @@ def main():
os.remove("/opt/opengnsys/cache/etc/lsb-release")
if __name__ == "__main__":
main()
main()

44
client/shared/scripts/initCache.py 100644 → 100755
View File

@ -1,6 +1,10 @@
import sys
import time
import subprocess
import SystemLib
import FileSystemLib
import CacheLib
import DiskLib
#!/usr/bin/env python3
@ -30,13 +34,13 @@ def main():
NPART = int(args[1])
SIZE = int(args[2])
else:
ogRaiseError("OG_ERR_FORMAT", f"{EXECFORMAT}")
SystemLib.ogRaiseError("OG_ERR_FORMAT", f"{EXECFORMAT}")
if NDISK < 1 or NPART < 1:
ogRaiseError("OG_ERR_FORMAT", f"{EXECFORMAT}")
SystemLib.ogRaiseError("OG_ERR_FORMAT", f"{EXECFORMAT}")
if SIZE < -1:
ogRaiseError("OG_ERR_FORMAT", f"{EXECFORMAT}")
SystemLib.ogRaiseError("OG_ERR_FORMAT", f"{EXECFORMAT}")
if SIZE == 0:
print("No modificar la caché local.")
@ -44,44 +48,44 @@ def main():
if SIZE == -1:
print("[10] Trabajar sin caché local.")
ogUnmountCache()
ogDeleteCache()
CacheLib.ogUnmountCache()
CacheLib.ogDeleteCache()
else:
current_cache = ogFindCache()
current_cache = CacheLib.ogFindCache()
if current_cache and f"{NDISK} {NPART}" != current_cache:
print("[10] Detectada otra caché, eliminarla")
ogUnmountCache()
ogDeleteCache()
CacheLib.ogUnmountCache()
CacheLib.ogDeleteCache()
try:
OLDSIZE = ogGetCacheSize()
OLDSIZE = CacheLib.ogGetCacheSize()
except ValueError:
OLDSIZE = 0
if SIZE <= 0:
ogRaiseError("OG_ERR_FORMAT", f"!({SIZE}>0)")
SystemLib.ogRaiseError("OG_ERR_FORMAT", f"!({SIZE}>0)")
if SIZE != OLDSIZE:
print("[10] Crear partición de caché local.")
ogUnmountCache()
ogCreateCache(NDISK, NPART, SIZE)
ogUpdatePartitionTable(NDISK)
CacheLib.ogUnmountCache()
CacheLib.ogCreateCache(NDISK, NPART, SIZE)
DiskLib.ogUpdatePartitionTable(NDISK)
cache = ogFindCache()
if not ogIsFormated(cache) or SIZE != OLDSIZE:
cache = CacheLib.ogFindCache()
if not FileSystemLib.ogIsFormated(cache) or SIZE != OLDSIZE:
print("[50] Formatear caché local.")
ogFormatCache()
CacheLib.ogFormatCache()
print("[70] Comprobar montaje de caché local.")
if ogMountCache() != 0:
if CacheLib.ogMountCache() != 0:
print("[80] Comprobar consistencia y volver a montar caché local.")
ogCheckFs(cache)
if ogMountCache() != 0:
FileSystem.ogCheckFs(cache)
if CacheLib.ogMountCache() != 0:
sys.exit(1)
if MOUNT == 0:
print("[90] Dejar desmontada la caché local.")
ogUnmountCache()
CacheLib.ogUnmountCache()
TIME = time.time() - TIME1
print(f"[100] Duración de la operación {int(TIME // 60)}m {int(TIME % 60)}s")

View File

@ -1,6 +1,8 @@
import os
import subprocess
import sys
import SystemLib
import NetLib
#!/usr/bin/env python3
@ -18,9 +20,9 @@ Prepara el equipo cliente para el modo offline.
PROG = os.path.basename(__file__)
if len(sys.argv) > 1 and sys.argv[1] == "help":
og_help()
SystemLib.ogHelp()
og_echo("log", "session $MSG_HELP_installOfflineMode")
SystemLib.ogEcho("log", "session $MSG_HELP_installOfflineMode")
# Cargamos las variables de entorno.
OGENGINECONFIGURATE = os.getenv('OGENGINECONFIGURATE')
@ -31,26 +33,26 @@ DIRTFTP = "/opt/oglive/tftpboot"
DIROGCLIENT = os.path.join(DIRTFTP, "ogclient")
# Comprobamos que el DIROGCLIENT esta montado desde repo
repo_ip = og_get_repo_ip()
repo_ip = NetLib.ogGetRepoIp()
result = subprocess.run(['df'], capture_output=True, text=True)
if f"{repo_ip} {DIRTFTP}" not in result.stdout:
og_raise_error("OG_ERR_NOTFOUND", "REPO OGclient")
SystemLib.ogRaiseError("OG_ERR_NOTFOUND", "REPO OGclient")
# Copiamos el kernel y el initrd.
og_echo("log", "session [10] updateBootCache")
SystemLib.ogEcho("log", "session [10] updateBootCache")
if not update_boot_cache():
og_raise_error("OG_ERR_NOTCACHE", "")
SystemLib.ogRaiseError("OG_ERR_NOTCACHE", "")
# Creamos los dir necesarios.
OGCAC = "/path/to/ogcac" # Placeholder for OGCAC path
og_echo("log", f"session [40] mkdir -p {OGCAC}/{{ogclient, menus, log}}.")
SystemLib.ogEcho("log", f"session [40] mkdir -p {OGCAC}/{{ogclient, menus, log}}.")
os.makedirs(os.path.join(OGCAC, "menus/images/iconos"), exist_ok=True)
os.makedirs(os.path.join(OGCAC, "ogclient"), exist_ok=True)
os.makedirs(os.path.join(OGCAC, "log"), exist_ok=True)
os.makedirs(os.path.join(OGCAC, "opt/opengnsys/images"), exist_ok=True)
# Comparamos el cliente en el server y en cache
og_echo("log", f"session [60] cp {DIROGCLIENT}/ogclient.sqfs {OGCAC}/ogclient/")
SystemLib.ogEcho("log", f"session [60] cp {DIROGCLIENT}/ogclient.sqfs {OGCAC}/ogclient/")
try:
with open(os.path.join(DIROGCLIENT, "ogclient.sqfs.sum"), 'r') as f:
SERVEROGCLIENT = f.read().strip()
@ -68,13 +70,13 @@ if CACHEOGCLIENT != SERVEROGCLIENT:
subprocess.run(['cp', os.path.join(DIROGCLIENT, "ogclient.sqfs.sum"), os.path.join(OGCAC, "ogclient/")])
# Si se ha generado el menu de inicio lo copiamos a cache.
IPCLIENT = og_get_ip_address()
IPCLIENT = NetLib.ogGetIpAddress()
MENU = os.path.join("/path/to/oglog", f"{IPCLIENT}.info.html") # Placeholder for OGLOG path
ICONO = "images/iconos/logoopengnsys.png"
if not os.path.isfile(MENU):
generate_menu_default()
og_echo("log", f"session [90] cp {MENU} {OGCAC}/menus/{IPCLIENT}.html")
SystemLib.ogEcho("log", f"session [90] cp {MENU} {OGCAC}/menus/{IPCLIENT}.html")
subprocess.run(['cp', MENU, os.path.join(OGCAC, f"menus/{IPCLIENT}.html")])
subprocess.run(['sed', '-i', 's/"../images"/"images"/g', os.path.join(OGCAC, f"menus/{IPCLIENT}.html")])
subprocess.run(['wget', '--no-check-certificate', f"https://{og_get_repo_ip()}/opengnsys/{ICONO}", '-O', os.path.join(OGCAC, f"menus/{ICONO}")])
subprocess.run(['wget', '--no-check-certificate', f"https://{NetLib.ogGetRepoIp()}/opengnsys/{ICONO}", '-O', os.path.join(OGCAC, f"menus/{ICONO}")])

View File

@ -2,6 +2,10 @@ import os
import sys
import subprocess
import json
import FileLib
import FileSystemLib
import InventoryLib
import SystemLib
#!/usr/bin/env python3
@ -21,15 +25,15 @@ def main():
show_help(prog)
if not callable(globals().get('ogRaiseError')):
raise_error(f"{prog}: it can only be executed by an ogLive client.")
SystemLib.ogRaiseError(f"{prog}: it can only be executed by an ogLive client.")
if len(sys.argv) not in [3, 4]:
raise_error(f"{prog} ndisk npart [adminuser]")
SystemLib.ogRaiseError(f"{prog} ndisk npart [adminuser]")
ndisk, npart = sys.argv[1], sys.argv[2]
windowsadmin = sys.argv[3] if len(sys.argv) == 4 else None
mntdir = ogMount(ndisk, npart)
mntdir = FileSystemLib.ogMount(ndisk, npart)
if not mntdir:
sys.exit(1)
@ -41,17 +45,17 @@ def main():
pass
if not ogversion:
raise_error(f"GET /rest/info")
SystemLib.ogRaiseError(f"GET /rest/info")
os_type = ogGetOsType(ndisk, npart)
os_type = Inventory.ogGetOsType(ndisk, npart)
if os_type == "Windows":
hive = ogGetHivePath(mntdir, windowsadmin)
hive = FileSystemLib.ogGetHivePath(mntdir, windowsadmin)
if not hive:
raise_error(f"{ndisk} {npart} {windowsadmin}/NTUSER.DAT")
SystemLib.ogRaiseError(f"{ndisk} {npart} {windowsadmin}/NTUSER.DAT")
ogagentfile = f"OGAgentSetup-{ogversion.replace('pre', '')}.exe"
tmpdir = ogGetPath(f"{mntdir}/Windows/Temp")
if "opengnsys agent" in ogListSoftware(ndisk, npart).lower():
tmpdir = FileLib.ogGetPath(f"{mntdir}/Windows/Temp")
if "opengnsys agent" in InventoryLib.ogListSoftware(ndisk, npart).lower():
print("OGAgent for Windows is already installed, you need to uninstall it before re-install.")
else:
if download_file(f"https://{ogGetServerIp()}/opengnsys/descargas/{ogagentfile}", f"{tmpdir}/{ogagentfile}"):
@ -69,17 +73,17 @@ exit
print(f'Scheduled OGAgent installation after "{windowsadmin}" logon')
print(" (for connection problems, check configuration file).")
except subprocess.CalledProcessError:
raise_error(f"{ndisk} {npart} .../{windowsadmin}/NTUSER.DAT")
SystemLib.ogRaiseError(f"{ndisk} {npart} .../{windowsadmin}/NTUSER.DAT")
else:
raise_error(f"{ndisk} {npart} /Windows/Temp/{ogagentfile}")
SystemLib.ogRaiseError(f"{ndisk} {npart} /Windows/Temp/{ogagentfile}")
elif os_type == "Linux":
if "ogagent" in ogListSoftware(ndisk, npart).lower():
if "ogagent" in InventoryLib.ogListSoftware(ndisk, npart).lower():
print("OGAgent for Linux is already installed, you need to uninstall it before re-install.")
else:
systemddir = f"{mntdir}/lib/systemd"
if not (os.path.isdir(systemddir) and os.path.isdir(systemddir.replace('/lib', '/etc'))):
raise_error(f"{ndisk} {npart} systemd")
SystemLib.ogRaiseError(f"{ndisk} {npart} systemd")
ogagentfile = None
code = None
@ -91,7 +95,7 @@ exit
code = f"if ! rpm -q ogagent &>/dev/null && [ -f /var/tmp/{ogagentfile} ]; then yum install -y /var/tmp/{ogagentfile}; fi"
if not ogagentfile:
raise_error(f"{ndisk} {npart} ogagent")
SystemLib.ogRaiseError(f"{ndisk} {npart} ogagent")
tmpdir = f"{mntdir}/var/tmp"
if download_file(f"https://{ogGetServerIp()}/opengnsys/descargas/{ogagentfile}", f"{tmpdir}/{ogagentfile}"):
@ -136,12 +140,12 @@ WantedBy=multi-user.target
print("Scheduled OGAgent installation at next boot")
print(" (process will be executed in the background, do not shutdown until finish).")
else:
raise_error(f"{ndisk} {npart} /var/tmp/{ogagentfile}")
SystemLib.ogRaiseError(f"{ndisk} {npart} /var/tmp/{ogagentfile}")
elif os_type == "MacOS":
print("OGAgent installer for macOS is not implemented yet.")
else:
raise_error(f"{ndisk} {npart}")
SystemLib.ogRaiseError(f"{ndisk} {npart}")
if __name__ == "__main__":
main()
main()

View File

@ -1,11 +1,16 @@
import subprocess
import sys
import DiskLib
import SystemLib
def list_partitions(*args):
result = subprocess.run(['ogListPartitions'] + list(args), capture_output=True, text=True)
output = result.stdout
cleaned_output = output.rstrip('EMPTY:0 ')
print(cleaned_output)
try:
result = DiskLib.ogListPartitions(*args)
cleaned_output = result.rstrip('EMPTY:0 ').strip()
print(cleaned_output)
except Exception as e:
SystemLib.ogRaiseError(f"Error al ejecutar ogListPartitions: {e}")
if __name__ == "__main__":
list_partitions(*sys.argv[1:])
list_partitions(*sys.argv[1:])

View File

@ -1,13 +1,14 @@
import sys
import subprocess
import DiskLib
import SystemLib
def og_list_primary_partitions(args):
try:
result = subprocess.run(['ogListPrimaryPartitions'] + args, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout.decode())
except subprocess.CalledProcessError as e:
print(f"Error: {e.stderr.decode()}", file=sys.stderr)
sys.exit(e.returncode)
result = DiskLib.ogListPrimaryPartitions(*args)
print(result)
except Exception as e:
SystemLib.ogRaiseError(f"Error al ejecutar ogListPrimaryPartitions: {e}")
if __name__ == "__main__":
og_list_primary_partitions(sys.argv[1:])
og_list_primary_partitions(sys.argv[1:])

View File

@ -1,16 +1,17 @@
import sys
import os
import subprocess
import SystemLib
#!/usr/bin/env python3
def main():
PROG = os.path.basename(__file__)
if len(sys.argv) != 2:
og_raise_error(os.getenv('OG_ERR_FORMAT', 1), f"{os.getenv('MSG_FORMAT', 'Usage')}: {PROG} urlmenu")
SystemLib.ogRaiseError(os.getenv('OG_ERR_FORMAT', 1), f"{os.getenv('MSG_FORMAT', 'Usage')}: {PROG} urlmenu")
url = sys.argv[1]
subprocess.run(['browser', '-qws', url])
if __name__ == "__main__":
main()
main()

View File

@ -1,5 +1,6 @@
import sys
import os
import SystemLib
#!/usr/bin/env python3
"""
@ -14,7 +15,7 @@ restoreImageCustom
# Control de parámetros.
if not (4 <= len(sys.argv) <= 6):
ogRaiseError(os.getenv('OG_ERR_FORMAT'), "restoreImageCustom str_repo str_imagen int_ndisco int_npart [ str_proto [\"str_opciones\"] ]")
SystemLib.ogRaiseError(os.getenv('OG_ERR_FORMAT'), "restoreImageCustom str_repo str_imagen int_ndisco int_npart [ str_proto [\"str_opciones\"] ]")
# Toma de parámetros.
REPO = sys.argv[1].upper() # Repositorio (en mayúsculas).
@ -31,4 +32,4 @@ PROTOOPT = sys.argv[6] if len(sys.argv) > 6 else "" # Opciones del protocolo se
# Paso 2: Sustituir, si se desea, la llamada al proceso estándar de restauración de imagen por código personalizado.
restoreImage(*sys.argv[1:])
# Aviso: editar la plantilla "configureOsCustom" para añadir el código personalizado para el proceso de postconfiguración de los clientes (no incluir aquí dicho código).
# Aviso: editar la plantilla "configureOsCustom" para añadir el código personalizado para el proceso de postconfiguración de los clientes (no incluir aquí dicho código).

View File

@ -15,4 +15,4 @@ def start_roxterm():
if __name__ == "__main__":
start_xvesa()
start_roxterm()
start_roxterm()

View File

@ -35,4 +35,4 @@ def main():
f.write("WAITING\n")
if __name__ == "__main__":
main()
main()