refs #2422 rename scripts

rename-sh-py
Natalia Serrano 2025-07-18 12:13:25 +02:00
parent 5606085fbd
commit 9da7d374f1
56 changed files with 56 additions and 703 deletions

View File

@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.0] - 2025-07-18
### Changed
- Renamed scripts so they don't have .py extension
## [0.30.1] - 2025-07-17
### Changed

View File

@ -226,10 +226,10 @@ if recreate_partition_table:
# Inicia la cache.
if is_there_cache:
SystemLib.ogEcho (['session', 'log'], None, f'[30] {ogGlobals.lang.MSG_HELP_ogCreateCache}')
SystemLib.ogEcho (['session', 'log'], None, f' initCache.py {dis} {tch}')
rc = SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGSCRIPTS}/initCache.py', str (dis), str (tch)])
SystemLib.ogEcho (['session', 'log'], None, f' initCache {dis} {tch}')
rc = SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGSCRIPTS}/initCache', str (dis), str (tch)])
if not rc:
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_CACHE, f'initCache.py failed')
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_CACHE, f'initCache failed')
sys.exit (1)
# Definir particionado.

View File

@ -20,7 +20,7 @@ def main(script_path, output_path):
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python ConsolaRemota.py <script_path> <output_path>")
print("Usage: python ConsolaRemota <script_path> <output_path>")
sys.exit(1)
script_path = sys.argv[1]

View File

@ -74,16 +74,16 @@ if 'REPO' == repo or ogCheckIpAddress (repo):
# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura,
if 'REPO' == repo and 'admin' != env_boot:
retval = subprocess.run ([f'{dirname}/CambiarAcceso.py', 'admin']).returncode
retval = subprocess.run ([f'{dirname}/CambiarAcceso', 'admin']).returncode
if retval:
sys.exit (retval)
ogEcho ([], None, f'createImage "{disk}" "{par}" "{arg_repo}" /"{imgname}"')
# Si existe, ejecuta script personalizado "createImageCustom"; si no, llama al genérico "createImage".
if os.path.exists ('{ogGlobals.OGSCRIPTS}/createImageCustom.py'):
script = f'{ogGlobals.OGSCRIPTS}/createImageCustom.py'
if os.path.exists ('{ogGlobals.OGSCRIPTS}/createImageCustom'):
script = f'{ogGlobals.OGSCRIPTS}/createImageCustom'
else:
script = f'{ogGlobals.OGSCRIPTS}/createImage.py'
script = f'{ogGlobals.OGSCRIPTS}/createImage'
with open (ogGlobals.OGLOGCOMMAND, 'a') as fd:
p = subprocess.Popen ([script, disk, par, arg_repo, f'/{imgname}'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
@ -100,7 +100,7 @@ retval = p.returncode
# Cambiar acceso a modo usuario, si es necesario.
if 'REPO' == repo and 'admin' != env_boot:
subprocess.run ([f'{dirname}/CambiarAcceso.py', 'user'])
subprocess.run ([f'{dirname}/CambiarAcceso', 'user'])
# Registro de fin de ejecución
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}')

View File

@ -64,7 +64,7 @@ def main():
if len(sys.argv) != 6:
sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, "Incorrect number of arguments. Usage: CrearImagenGit.py disk_num partition_num image_name repo tag"))
sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, "Incorrect number of arguments. Usage: CrearImagenGit disk_num partition_num image_name repo tag"))
# repo - repositorio, ip address. Opcional porque oglive lo recibe como parametro de kernel
# tag - tag a crear automaticamente. Opcional, no necesitamos crear un tag siempre.

View File

@ -20,4 +20,4 @@ else:
disk = args[0]
part = args[1]
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/bootOs.py', disk, part])
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/bootOs', disk, part])

View File

@ -13,11 +13,11 @@ if len (sys.argv) != 2:
sys.exit (1)
output_file = sys.argv[1]
listhi_out = subprocess.run ( [f'{ogGlobals.OGSCRIPTS}/listHardwareInfo.py'], capture_output=True, text=True).stdout
listhi_out = subprocess.run ( [f'{ogGlobals.OGSCRIPTS}/listHardwareInfo'], capture_output=True, text=True).stdout
if listhi_out:
inventory_path = listhi_out.splitlines()[0]
else:
ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'listHardwareInfo.py failed')
ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'listHardwareInfo failed')
sys.exit (1)
with open (inventory_path, 'r') as fdin, open (output_file, 'w') as fdout:

View File

@ -27,11 +27,11 @@ if __name__ == "__main__":
# Registro de inicio de ejecución
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {prog} {disk} {par} {dest_file}')
listsi_out = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/listSoftwareInfo.py', disk, par], capture_output=True, text=True).stdout
listsi_out = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/listSoftwareInfo', disk, par], capture_output=True, text=True).stdout
if listsi_out:
file = listsi_out.splitlines()[0]
else:
ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'listSoftwareInfo.py failed')
ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'listSoftwareInfo failed')
sys.exit (1)
shutil.copy (file, dest_file)

View File

@ -83,7 +83,7 @@ def main():
if len(sys.argv) != 5:
import json
args = json.dumps(sys.argv)
sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, f"Incorrect number of arguments. Usage: ModificarImagenGit.py disk_num partition_num image_name repo msg. Received args: {args}"))
sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, f"Incorrect number of arguments. Usage: ModificarImagenGit disk_num partition_num image_name repo msg. Received args: {args}"))
# repo - repositorio, ip address. Opcional porque oglive lo recibe como parametro de kernel
# tag - tag a crear automaticamente. Opcional, no necesitamos crear un tag siempre.

View File

@ -25,5 +25,5 @@ if __name__ == '__main__':
disk, par, imgname, repo, proto, *extra = sys.argv[1:]
rc = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/deployImage.py', repo, imgname, disk, par, proto] + extra).returncode
rc = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/deployImage', repo, imgname, disk, par, proto] + extra).returncode
sys.exit (rc)

View File

@ -43,7 +43,7 @@ if __name__ == "__main__":
if len(sys.argv) < 6:
print("Usage: python RestaurarImagenGit.py <disk> <partition> <repo> <ip> <ref> <protocol>")
print("Usage: python RestaurarImagenGit <disk> <partition> <repo> <ip> <ref> <protocol>")
sys.exit(1)
disk = sys.argv[1]

View File

@ -3,7 +3,7 @@ import sys
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python procesaCache.py <arg>")
print("Usage: python procesaCache <arg>")
sys.exit(1)
init_cache(sys.argv[1])

View File

@ -707,7 +707,7 @@ def ogGrubInstallMbr (disk, par, checkos='FALSE', kernelparam=''):
prefixsecondstage = '' # Reactivamos el grub con el grub.cfg original.
else: # SI Reconfigurar segunda etapa (grub.cfg) == TRUE
#llamada a updateBootCache para que aloje la primera fase del ogLive
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/updateBootCache.py'])
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/updateBootCache'])
if InventoryLib.ogIsEfiActive():
# UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup.

View File

@ -236,7 +236,7 @@ def ogFormatCache():
os.makedirs (j, exist_ok=True)
# Incluir kernel e Initrd del ogLive
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/updateBootCache.py'])
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/updateBootCache'])
#/**
@ -360,7 +360,7 @@ def ogUnmountCache():
#@return lo mismo que devuelve initCache
#*/ ##
def initCache (*args):
p = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/initCache.py'] + list(args))
p = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/initCache'] + list(args))
return not p.returncode ## negate shell return code

View File

@ -127,7 +127,6 @@ def ogCreatePartitions (disk, parts):
NVME_PREFIX = 'p' if 'nvme' in DISK else ''
EXTSTART = EXTSIZE = 0
for p in parts:
# Leer formato de cada parámetro - Tipo:Tamaño
TYPE, SIZE = p.split (':')
if TYPE is None or 'None' == TYPE: TYPE='EMPTY'

View File

@ -44,8 +44,8 @@ def ogEcho (logtypes, loglevel, msg):
if loglevel is None or 'help' == loglevel:
if ogGlobals.DEBUG.lower() != "no":
logfiles.append (ogGlobals.OGLOGFILE)
logfiles.append (ogGlobals.OGJSONLOGFILE)
logfiles.append (_logtype2logfile ('log'))
logfiles.append (_logtype2logfile ('jsonlog'))
for f in logfiles:
with open (f, 'a') as fd:
if ogGlobals.OGJSONLOGFILE == f:

View File

@ -6,7 +6,7 @@ Este directorio contiene algunos scripts de ejemplo que se utilizan
por el cliente de la consola web de administración, para realizar
las operaciones más comunes de gestión de clientes.
Dichos scripts están desarrollados en BASH y utilizan las funciones
Dichos scripts están desarrollados en PYTHON y utilizan las funciones
básicas del motor de clonación.
OpenGnsys Client Cloning Engine incluye un completo conjunto de
@ -17,9 +17,7 @@ operativos y pueden ser utilizados directamente.
Scripts distribuidos:
- bootLinux arranca un sistema Linux con partición de inicio.
- bootOs arranca un sistema operativo instalado.
- bootWindows arranca un sistema Windows con partición de inicio.
- configureOs ejecuta tereas de postconfiguración de un sistema operativo.
- createImage genera una imagen de un sistema operativo.
- createLogicalPartitions define las particiones primarias del disco.
@ -27,7 +25,6 @@ Scripts distribuidos:
- deployImage restaura una imagen y postconfigura su sistema operativo.
- formatFs formatea un sistema de archivos.
- getFsType muestra el tipo (mnemónico) de una partición.
- getIpAddress muestra la IP local del cliente.
- getOsVersion muestra la versión de sistema operativo instalado.
- initCache inicia o define la caché local.
- listHardwareInfo lista los dispoisitivos del cliente.
@ -37,6 +34,8 @@ Scripts distribuidos:
- poweroff desmonta los sistemas de archivos y apaga el equipo.
- reboot desmonta los sistemas de archivos y reinicia el equipo.
- restoreImage restaura una imagen de sistema operativo.
- updateBootCache despliega o actualiza el kernel e initrd en el cache.
- updateCache actualiza la cache del cliente con imagen o fichero iso.
Plantillas para personalización de operaciones:
@ -46,8 +45,7 @@ importantes. Para activar una plantilla debe renombrase el ficheros quitando la
extensión ".template" y añadir permisos de ejecución. Las plantillas activadas
no seránn modificadas por el actualizador de OpenGnsys.
- bootOsCustom.template arranque personalizado de sistema operativo.
- configureOsCustom.template postconfiguración personalizada de sistema operativo.
- createImageCustom.template creación personalizada de imagen.
- restoreImageCustom.template restauración personalizada de imagen.
- bootOsCustomtemplate arranque personalizado de sistema operativo.
- configureOsCustomtemplate postconfiguración personalizada de sistema operativo.
- createImageCustomtemplate creación personalizada de imagen.
- restoreImageCustomtemplate restauración personalizada de imagen.

View File

@ -45,9 +45,9 @@ if not mount_out or not re.search (rf'{mntdir}.*\(rw', mount_out):
ogUnmount (disk, par)
ogMount (disk, par)
if shutil.which ('bootOsCustom.py'):
if shutil.which ('bootOsCustom'):
print ('[10] Configuración personalizada del inicio.')
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/bootOsCustom.py', disk, par])
subprocess.run ([f'{ogGlobals.OGSCRIPTS}/bootOsCustom', disk, par])
print ('[70] Desmontar todos los sistemas de archivos.')
subprocess.run (['sync'])

View File

@ -1,11 +1,11 @@
#!/usr/bin/python3
#/**
# bootOsCustomTemplate.py
# bootOsCustomTemplate
#@brief Plantilla para script de configuración personalizada de sistema operativo restaurado.
#@param $1 nº de disco
#@param $2 nº de partición
#@warning Renombrar este fichero como "bootOsCustom.py" para personalizar el script estándar "bootOs.py".
#@warning Renombrar este fichero como "bootOsCustom" para personalizar el script estándar "bootOs".
#@note La partición a inicializar debe estar montada
#**/
@ -29,7 +29,7 @@ disk, par = sys.argv[1:]
device = ogDiskToDev (disk, par)
if not device: sys.exit (1)
# Nota: el script "bootOs.py" llama al script "bootOsCustom.py" después de realizar la operaciones de inicio estándar y antes de desmontar las particiones e iniciar el sistema operativo.
# 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, par)
if not mntdir: sys.exit (1)

View File

@ -1,65 +0,0 @@
import sys
#!/usr/bin/env python3
"""
BuildToOrder
@brief Script de ejemplo para realizar una configuracion del sistema operativo antes de generar imagen o de restaurado.
@brief Activa el uso de los contralodres de disco más usados en windows 7.
@brief (puede usarse como complemento para el programa de creación de imágenes o de restauración).
@param 1 disco
@param 2 particion
@return
@TODO
@exception
@version 1.0.4 - Discos ide + SATA.
@date 2012-10-05
@version 1.1.1b - Funciona para Windows8 y Windows 10. Si la clave no existe (tiene valor vacío) se crea.
@date 2020-05-04
"""
def main():
PROG = sys.argv[0]
if len(sys.argv) != 3:
ogRaiseError("OG_ERR_FORMAT", f"Formato: {PROG} ndisco nparticion")
disk = sys.argv[1]
partition = sys.argv[2]
MNTDIR = ogMount(disk, partition)
OSTYPE = ogGetOsType(disk, partition)
if OSTYPE == "Windows":
print("Filtro versión de sistema operativo windows.")
TYPE = ogGetOsVersion(disk, partition)
if "Windows XP" in TYPE:
print("Versión de sistema operativo Windows XP no soportado")
sys.exit()
elif "Windows 7" in TYPE:
KEYS = ["intelide", "pciide", "msahci", "iaStorV", "iaStor", "LSI_SAS"]
elif "Windows 8" in TYPE or "Windows 10" in TYPE:
KEYS = ["intelide", "pciide", "storahci", "iaStorV", "iaStorAC", "iaStorAVC", "LSI_SAS"]
else:
KEYS = []
print(TYPE)
CONTROLSET = ["ControlSet001", "ControlSet002"]
for C in CONTROLSET:
if ogListRegistryKeys(MNTDIR, "SYSTEM", f'\\{C}') == "":
continue
for K in KEYS:
FULLK = f'\\{C}\\Services\\{K}\\Start'
VALUE = ogGetRegistryValue(MNTDIR, "SYSTEM", FULLK)
if VALUE == "":
ogDeleteRegistryValue(MNTDIR, "SYSTEM", FULLK)
ogAddRegistryValue(MNTDIR, "SYSTEM", FULLK, "DWORD")
ogSetRegistryValue(MNTDIR, "SYSTEM", FULLK, '0')
print(f" * {C} {K} enabled")
elif OSTYPE == "Linux":
print("Versión de Sistema Operativo GNU/Linux no soportado")
else:
print("Sistema Operativo no soportado")
if __name__ == "__main__":
main()

View File

@ -27,7 +27,7 @@ repo = other[0].upper() if len (other) > 0 else ''
imgname = other[1] if len (other) > 1 else ''
# Nota: incluye llamada al script "configureOs" para realizar previamente una configuración estándar.
subprocess.run ([f'configureOs.py', disk, par, imgname])
subprocess.run ([f'configureOs', disk, par, imgname])
ostype = ogGetOsType (disk, par)
if 'Windows' == ostype:

View File

@ -63,7 +63,7 @@ def main (disk, par, repo, imgname):
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
# salvo si es llamado desde createImageCustom
if 'createImageCustom.py' != SystemLib.ogGetCaller():
if 'createImageCustom' != SystemLib.ogGetCaller():
with open (ogGlobals.OGLOGSESSION, 'w') as fd: fd.write ('')
with open (ogGlobals.OGLOGCOMMAND, 'w') as fd: fd.write ('')
with open (f'{ogGlobals.OGLOGCOMMAND}.tmp', 'w') as fd: fd.write ('')

View File

@ -22,4 +22,4 @@ if len (sys.argv) != 5:
disk, par, repo, imgname = sys.argv[1:]
repo = repo.upper()
subprocess.run (['createImage.py', disk, par, repo, imgname])
subprocess.run (['createImage', disk, par, repo, imgname])

View File

@ -89,7 +89,7 @@ def main (repo, imgname, disk, par, proto='UNICAST', protoopt=''):
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
retval = subprocess.run (['updateCache', 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:
@ -138,12 +138,12 @@ def main (repo, imgname, disk, par, proto='UNICAST', protoopt=''):
params = [repo, imgname, disk, par, proto, protoopt]
# Si existe, ejecuta script personalizado "restoreImageCustom"; si no, llama al genérico "restoreImage".
if shutil.which ('restoreImageCustom.py'):
if shutil.which ('restoreImageCustom'):
SystemLib.ogEcho (['log', 'session'], None, f'[55] {ogGlobals.lang.MSG_HELP_ogRestoreImage}: restoreImageCustom {params}')
retval = subprocess.run (['restoreImageCustom.py'] + params).returncode
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
retval = subprocess.run (['restoreImage'] + params).returncode
# Mostrar resultados.
resumerestoreimage = subprocess.run (['grep', '--max-count', '1', 'Total Time:', ogGlobals.OGLOGCOMMAND], capture_output=True, text=True).stdout
@ -160,12 +160,12 @@ def main (repo, imgname, disk, par, proto='UNICAST', protoopt=''):
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.py'):
if shutil.which ('configureOsCustom'):
SystemLib.ogEcho (['log', 'session'], None, '[90] configureOsCustom')
subprocess.run (['configureOsCustom.py', disk, par, repo, imgname])
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, imgname])
subprocess.run (['configureOs', disk, par, imgname])
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')

View File

@ -1,93 +0,0 @@
#!/usr/bin/env python3
import os
import subprocess
# 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.
DEVICE = os.getenv('DEVICE', 'eth0')
with open(f'/tmp/net-{DEVICE}.conf') as f:
exec(f.read())
FILEINFOHTML = f"{os.getenv('OGLOG')}/{subprocess.getoutput('ogGetIpAddress')}.info.html"
FILEINFOCACHE = f"{os.getenv('OGLOG')}/{subprocess.getoutput('ogGetIpAddress')}.cache.txt"
subprocess.run(['ogMountCache'], stderr=subprocess.DEVNULL)
CACHECONTENIDO = f"ls -m {os.getenv('OGCAC')}/{os.getenv('OGIMG')} 2>/dev/null"
SPEED = subprocess.getoutput(f"LANG=C ethtool {DEVICE} 2>/dev/null | awk '$1~/Speed/ {{print $2}}'")
SPEED = SPEED.lower()
if SPEED == "1000mb/s":
pass
elif SPEED == "100mb/s":
SPEED = f"<font color=\"blue\">{SPEED}</font>"
elif SPEED == "10mb/s":
SPEED = f"<font color=\"grey\">{SPEED}</font>"
else:
SPEED = f"<font color=\"red\">{SPEED}</font>"
DUPLEX = subprocess.getoutput(f"LANG=C ethtool {DEVICE} 2>/dev/null | awk '$1~/Duplex/ {{print $2}}'")
DUPLEX = DUPLEX.lower()
if DUPLEX == "full":
pass
else:
DUPLEX = f"<font color=\"red\">{DUPLEX}</font>"
CACHESIZEFREE = int(subprocess.getoutput('ogGetFreeSize $(ogFindCache)'))
with open(FILEINFOCACHE, 'w') as f:
if CACHESIZEFREE == 0:
f.write('0.MB,')
else:
f.write(f"{CACHESIZEFREE // 1024}.MB,")
# Crear menú por defecto.
with open(FILEINFOHTML, 'w') as f:
f.write(f"""
<div align="center" style="font-family: Arial, Helvetica, sans-serif;">
<p style="color:#999999; font-size: 16px; margin: 2em;">
<table border="1" width="100%">
<tr>
<td rowspan="2"><p align="left"><img border="0" src="../images/iconos/logoopengnsys.png"><p> </td>
<td> {os.getenv('MSG_HOSTNAME')} </td> <td> {os.getenv('MSG_IPADDR')} </td> <td> {os.getenv('MSG_MACADDR')} </td> <td> {os.getenv('MSG_SPEED')} </td> <td> {os.getenv('MSG_DUPLEX')} </td> </tr>
<tr> <td>{os.getenv('HOSTNAME')} </td> <td> {subprocess.getoutput('ogGetIpAddress')} </td> <td> {subprocess.getoutput('ogGetMacAddress')} </td> <td> {SPEED} </td> <td> {DUPLEX} </td> </tr>
</table>
</p>
<h1>{os.getenv('MSG_MENUTITLE')}</h1>
""")
# Si existe el fichero de configuración creado por el script getConfiguration, ...
cfgfile = '/tmp/getconfig'
if os.path.isfile(cfgfile):
# Tomar los datos del fichero.
with open(cfgfile) as f_cfg, open(FILEINFOHTML, 'a') as f_html:
for line in f_cfg:
sep = line.split(';')
for item in sep:
dua = item.split(':')
if len(dua) > 4 and dua[4] and dua[4] != "DATA":
f_html.write(f"<p><a href=\"command:bootOs {dua[0]} {dua[1]}\">{os.getenv('MSG_BOOT')} {dua[4]} ({dua[0]}, {dua[1]})</a></p>\n")
else:
# Si no, obtener los datos de los discos.
num_disks = int(subprocess.getoutput('ogDiskToDev | wc -w'))
with open(FILEINFOHTML, 'a') as f_html:
for d in range(1, num_disks + 1):
num_partitions = int(subprocess.getoutput(f'ogGetPartitionsNumber {d}'))
for p in range(1, num_partitions + 1):
version = subprocess.getoutput(f'ogGetOsVersion {d} {p} 2>/dev/null').split(':')[1]
if version:
f_html.write(f"<p><a href=\"command:bootOs {d} {p}\">{os.getenv('MSG_BOOT')} {version} ({d}, {p})</a></p>\n")
# Añadir opción de apagado.
with open(FILEINFOHTML, 'a') as f:
f.write(f"""
<p><a href="command:poweroff">{os.getenv('MSG_POWEROFF')}</a></p>
</div>
""")
# Crear contenido de la caché.
with open(FILEINFOCACHE, 'a') as f:
f.write(subprocess.getoutput(CACHECONTENIDO))

View File

@ -1,82 +0,0 @@
import os
import subprocess
import sys
import SystemLib
import NetLib
#!/usr/bin/env python3
"""
installOfflineMode
Prepara el equipo cliente para el modo offline.
@exception OG_ERR_NOTFOUND Fichero o dispositivo no encontrado.
@exception OG_ERR_NOTCACHE No existe cache.
@author Irina Gomez. ETSII. Universidad de Sevilla
@date 2013/12/5
"""
PROG = os.path.basename(__file__)
if len(sys.argv) > 1 and sys.argv[1] == "help":
SystemLib.ogHelp()
SystemLib.ogEcho("log", "session $MSG_HELP_installOfflineMode")
# Cargamos las variables de entorno.
OGENGINECONFIGURATE = os.getenv('OGENGINECONFIGURATE')
if not OGENGINECONFIGURATE:
exec(open('/opt/opengnsys/etc/engine.cfg').read())
DIRTFTP = "/opt/oglive/tftpboot"
DIROGCLIENT = os.path.join(DIRTFTP, "ogclient")
# Comprobamos que el DIROGCLIENT esta montado desde repo
repo_ip = NetLib.ogGetRepoIp()
result = subprocess.run(['df'], capture_output=True, text=True)
if f"{repo_ip} {DIRTFTP}" not in result.stdout:
SystemLib.ogRaiseError("OG_ERR_NOTFOUND", "REPO OGclient")
# Copiamos el kernel y el initrd.
SystemLib.ogEcho("log", "session [10] updateBootCache")
if not update_boot_cache():
SystemLib.ogRaiseError("OG_ERR_NOTCACHE", "")
# Creamos los dir necesarios.
OGCAC = "/path/to/ogcac" # Placeholder for OGCAC path
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
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()
except FileNotFoundError:
SERVEROGCLIENT = None
try:
with open(os.path.join(OGCAC, "ogclient/ogclient.sqfs.sum"), 'r') as f:
CACHEOGCLIENT = f.read().strip()
except FileNotFoundError:
CACHEOGCLIENT = None
if CACHEOGCLIENT != SERVEROGCLIENT:
subprocess.run(['cp', os.path.join(DIROGCLIENT, "ogclient.sqfs"), os.path.join(OGCAC, "ogclient/")])
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 = 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()
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://{NetLib.ogGetRepoIp()}/opengnsys/{ICONO}", '-O', os.path.join(OGCAC, f"menus/{ICONO}")])

View File

@ -1,151 +0,0 @@
import os
import sys
import subprocess
import json
import FileLib
import FileSystemLib
import InventoryLib
import SystemLib
#!/usr/bin/env python3
def download_file(url, output):
try:
if subprocess.call(['which', 'curl'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
subprocess.check_call(['curl', '-k', '-f', '--connect-timeout', '1', '-o', output, url])
else:
subprocess.check_call(['wget', '--no-check-certificate', '-T', '1', '-O', output, url])
except subprocess.CalledProcessError:
return False
return True
def main():
prog = os.path.basename(__file__)
if len(sys.argv) == 2 and sys.argv[1] == "help":
show_help(prog)
if not callable(globals().get('ogRaiseError')):
SystemLib.ogRaiseError(f"{prog}: it can only be executed by an ogLive client.")
if len(sys.argv) not in [3, 4]:
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 = FileSystemLib.ogMount(ndisk, npart)
if not mntdir:
sys.exit(1)
ogversion = None
try:
response = subprocess.check_output(['curl', '-k', '-f', '--connect-timeout', '1', '-o', '-', f'https://{ogGetServerIp()}/opengnsys/rest/info'])
ogversion = json.loads(response).get('version')
except subprocess.CalledProcessError:
pass
if not ogversion:
SystemLib.ogRaiseError(f"GET /rest/info")
os_type = Inventory.ogGetOsType(ndisk, npart)
if os_type == "Windows":
hive = FileSystemLib.ogGetHivePath(mntdir, windowsadmin)
if not hive:
SystemLib.ogRaiseError(f"{ndisk} {npart} {windowsadmin}/NTUSER.DAT")
ogagentfile = f"OGAgentSetup-{ogversion.replace('pre', '')}.exe"
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}"):
try:
subprocess.check_call(['hivexsh', '-w'], input=f"""
load {hive}
cd \\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce
setval 1
Install OGAgent
string:C:\\Windows\\Temp\\{ogagentfile} /S /server {ogGetServerIp()}
commit
close
exit
""".encode())
print(f'Scheduled OGAgent installation after "{windowsadmin}" logon')
print(" (for connection problems, check configuration file).")
except subprocess.CalledProcessError:
SystemLib.ogRaiseError(f"{ndisk} {npart} .../{windowsadmin}/NTUSER.DAT")
else:
SystemLib.ogRaiseError(f"{ndisk} {npart} /Windows/Temp/{ogagentfile}")
elif os_type == "Linux":
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'))):
SystemLib.ogRaiseError(f"{ndisk} {npart} systemd")
ogagentfile = None
code = None
if os.path.exists(f"{mntdir}/etc/debian_version"):
ogagentfile = f"ogagent_{ogversion.replace('pre', '')}_all.deb"
code = f"if ! dpkg -l ogagent &>/dev/null && [ -f /var/tmp/{ogagentfile} ]; then apt-get update; apt-get install -y /var/tmp/{ogagentfile}; fi"
elif os.path.exists(f"{mntdir}/etc/redhat-release"):
ogagentfile = f"ogagent-{ogversion.replace('pre', '')}-1.noarch.rpm"
code = f"if ! rpm -q ogagent &>/dev/null && [ -f /var/tmp/{ogagentfile} ]; then yum install -y /var/tmp/{ogagentfile}; fi"
if not ogagentfile:
SystemLib.ogRaiseError(f"{ndisk} {npart} ogagent")
tmpdir = f"{mntdir}/var/tmp"
if download_file(f"https://{ogGetServerIp()}/opengnsys/descargas/{ogagentfile}", f"{tmpdir}/{ogagentfile}"):
with open(f"{systemddir}/systemd-launchogagent", 'w') as f:
f.write(f"""#!/bin/bash
[ $EUID = 0 ] || exit 4
start() {{
{code}
sed -i "0,/remote=/ s,remote=.*,remote=https://{ogGetServerIp()}/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg
service ogagent start
}}
restart() {{
service ogagent stop
if [ -f /var/tmp/{ogagentfile} ]; then
apt-get update
apt-get install -y --reinstall /var/tmp/{ogagentfile}
fi
sed -i "0,/remote=/ s,remote=.*,remote=https://{ogGetServerIp()}/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg
service ogagent start
}}
case "$1" in
start|restart) "$1" ;;
esac
""")
os.chmod(f"{systemddir}/systemd-launchogagent", 0o755)
with open(f"{systemddir}/system/launchogagent.service", 'w') as f:
f.write(f"""[Unit]
Description=Installing and configuring OGAgent
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/lib/systemd/systemd-launchogagent start
TimeoutStartSec=5min
[Install]
WantedBy=multi-user.target
""")
os.symlink(f"/lib/systemd/system/launchogagent.service", f"{systemddir.replace('/lib', '/etc')}/system/multi-user.target.wants")
print("Scheduled OGAgent installation at next boot")
print(" (process will be executed in the background, do not shutdown until finish).")
else:
SystemLib.ogRaiseError(f"{ndisk} {npart} /var/tmp/{ogagentfile}")
elif os_type == "MacOS":
print("OGAgent installer for macOS is not implemented yet.")
else:
SystemLib.ogRaiseError(f"{ndisk} {npart}")
if __name__ == "__main__":
main()

View File

@ -1,16 +0,0 @@
import sys
import DiskLib
import SystemLib
def list_partitions(*args):
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:])

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
#/**
#@file restoreImage.py
#@file restoreImage
#@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)
@ -8,7 +8,7 @@
#@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
#@ejemplo restoreImage 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.

View File

@ -25,4 +25,4 @@ repo = repo.upper()
proto = other[0].upper() if len (other) > 0 else 'UNICAST'
protoopt = other[1] if len (other) > 1 else ''
subprocess.run (['restoreImage.py', repo, imgname, disk, par, proto, protoopt])
subprocess.run (['restoreImage', repo, imgname, disk, par, proto, protoopt])

View File

@ -1,8 +0,0 @@
#/bin/bash
/usr/X11R6/bin/Xvesa :0 -ac -shadow -screen 1024x768x24 -br -mouse /dev/input/mice &
/bin/sleep 0.1
export DISPLAY=:0
#/usr/bin/lxde-logout
#/usr/bin/openbox
/usr/bin/roxterm
#/usr/sbin/gparted

View File

@ -1,18 +0,0 @@
import os
import subprocess
import time
#!/usr/bin/env python3
def start_xvesa():
subprocess.Popen(['/usr/X11R6/bin/Xvesa', ':0', '-ac', '-shadow', '-screen', '1024x768x24', '-br', '-mouse', '/dev/input/mice'])
time.sleep(0.1)
os.environ['DISPLAY'] = ':0'
def start_roxterm():
subprocess.Popen(['/usr/bin/roxterm'])
if __name__ == "__main__":
start_xvesa()
start_roxterm()

View File

@ -1,22 +0,0 @@
#!/bin/bash
cp /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.back
cp /etc/lighttpd/conf-enabled/10-cgi.conf /etc/lighttpd/conf-enabled/10-cgi.conf.back
cp /opt/opengnsys/lib/httpd/lighttpd.conf /etc/lighttpd/
cp /opt/opengnsys/lib/httpd/10-cgi.conf /etc/lighttpd/conf-enabled/
chmod 755 /opt
mkdir -p /usr/lib/cgi-bin
cp /opt/opengnsys/lib/httpd/* /usr/lib/cgi-bin
/etc/init.d/lighttpd start
## dstat fails because /var/lib/pcp/pmns/root does not exist.
## we work around that by starting/stopping pmcd once. When it starts, it creates the missing file.
if [[ ! -f /var/lib/pcp/pmns/root ]]; then
/etc/init.d/pmcd start &>/dev/null
/etc/init.d/pmcd stop &>/dev/null
fi
dstat --disk --net > /tmp/bandwidth &
echo "WAITING" >> $OGLOGSESSION

View File

@ -1,65 +0,0 @@
#!/bin/bash
#/**
#@file configureGroup
#@brief Script de ejemplo de post-configuracion del sistema operativo especifica de cada grupo de ordenadores.
#@brief El directorio del grupo en el repositorio se situa en /opt/opengnsys/groups/Nombre_Grupo
#@brief Se ponen archivos o marcas dentro del directorio del grupo (si queremos que afecte a todas las imagenes)
#@brief o del subdirectorio de la imagen dentro del grupo. Los archivos se copian en el sitio correcto del sistema
#@brief y las marcas se comprueba que existen para inicar una accion (ej: cambiar registro)
#@param str_repo repositorio de imágenes (remoto o caché local)
#@param path_image camino de la imagen (sin extensión)
#@param int_ndisk nº de orden del disco
#@param int_npartition nº de orden de la particion
#@return
#@exception OG_ERR_FORMAT Formato incorrecto.
#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
#@warning License: GNU GPLv3+
#*/
# Si se solicita, mostrar ayuda.
if [ "$*" == "help" ]; then
ogHelp "$0" "$0 path_dir str_image int_ndisk int_npart" \
"$0 REPO /aula1/winxp 1 1"
exit
fi
# Error si no se reciben 4 parámetros.
[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT || exit $?
# Procesar parámetros.
PART=$(ogMount $3 $4) || ogRaiseError $OG_ERR_PARTITION "$3 $4" || exit $?
IMGNAME=$(basename $2)
GROUPDIR=$(ogGetGroupDir)
IMGDIR=$GROUPDIR/$IMGNAME
# Comprobamos que exista GROUPDIR. Si no existe no es error, nada que configurar
[ ! -x "$GROUPDIR" ] && exit 0
TYPE=$(ogGetOsVersion $3 $4)
case "$TYPE" in
Linux*) echo "PostConfiguracion de Linux para el grupo $group"
# Si existen estos ficheros en el directorio del grupo o de la imagen se copian a la particion
[ -e $IMGDIR/menu.lst ] && echo "cp -f $IMGDIR/menu.lst $PART/boot/grub/menu.lst" && cp -f $IMGDIR/menu.lst $PART/boot/grub/menu.lst
[ -e $IMGDIR/grub.cfg ] && echo "cp $IMGDIR/grub.cfg $PART/boot/grub/grub.cfg" && cp -f $IMGDIR/grub.cfg $PART/boot/grub/grub.cfg
[ -e $IMGDIR/hosts ] && echo "cp -f $IMGDIR/hosts $PART/etc/hosts" && cp -f $IMGDIR/hosts $PART/etc/hosts
[ -e $IMGDIR/fstab ] && echo "cp -f $IMGDIR/fstab $PART/etc/fstab" && cp -f $IMGDIR/fstab $PART/etc/fstab
[ -e $IMGDIR/xorg.conf ] && echo "cp -f $IMGDIR/xorg.conf $PART/etc/X11/xorg.conf" && cp -f $IMGDIR/xorg.conf $PART/etc/X11/xorg.conf
[ -e $IMGDIR/rc.local ] && echo "cp -f $IMGDIR/rc.local $PART/etc/rc.local" && cp -f $IMGDIR/rc.local $PART/etc/rc.local
[ -e $IMGDIR/interfaces ] && echo "cp -f $IMGDIR/interfaces $PART/etc/network/interfaces" && cp -f $IMGDIR/interfaces $PART/etc/network/interfaces
[ -e $IMGDIR/passwd ] && echo "cp -f $IMGDIR/passwd $PART/etc/passwd" && cp -f $IMGDIR/passwd $PART/etc/passwd
;;
*Windows\ XP) echo "PostConfiguracion de XP para el grupo $group"
# Si existen estos ficheros en el directorio del grupo o de la imagen se copian a la particion
[ -e $IMGDIR/SAM ] && echo "cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM" && cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM
;;
*Windows\ 7*) echo "Postconfiguracion de W7 para el grupo $group"
# Si existen estos ficheros en el directorio del grupo o de la imagen se copian a la particion
[ -e $IMGDIR/SAM ] && echo "cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM" && cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM
;;
*) exit 0
;;
esac

View File

@ -1,68 +0,0 @@
#!/bin/bash
#/**
#@file FirstRunOnceWindows
#@brief Guión de rutinas que se ejecutarán en los windows con teclado y raton desactivados.
#@param $1 número de disco
#@param $2 número de particion
#@exception OG_ERR_FORMAT 1 formato incorrecto.
#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados.
#@exception OG_ERR_PARTITION 3 # Error en partición de disco.
#@exception OG_ERR_LOCKED 4 partición bloqueada por otra operación.
#@version 1.0.1 - primera version: desactivar/activar ratón y teclado
#@author Antonio J. Doblas Viso.
#@date 2017-02-23
#**/
PROG="$(basename $0)"
if [ $# -lt 2 ]; then
ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion"
exit $?
fi
# Asignación de variables
## Bloque de variables de parámetros
DISK=$1
PART=$2
POSTCONF=postconf.cmd
### Bloque de variables basada en un archivo de claves: ADMIN PASSADMIN USER PASSUSER
source $OGETC/os.cfg $DISK $PART
OSVERSION=$(ogGetOsVersion $1 $2)
case "$OSVERSION" in
*Windows*)
# Desactivamos el telcado y el ratón
ogSetRegistryValue $(ogMount $DISK $PART) SYSTEM '\ControlSet001\Services\kbdclass\Start' 4
ogSetRegistryValue $(ogMount $DISK $PART) SYSTEM '\ControlSet001\Services\mouclass\Start' 4
## Indicación del proceso (variable $POSTCONF), usuario que lo ejecutará ($ADMIN) y configuración del windows para que arranque con autologin tras la postconfiguración (1 "$USER" "$PASSUSER")
echo "ogInstallMiniSetup $DISK $PART $POSTCONF $ADMIN $PASSADMIN 1 \"$USER\" \"$PASSUSER\" "
ogInstallMiniSetup $DISK $PART $POSTCONF $ADMIN $PASSADMIN 1 "$USER" "$PASSUSER"
ogAddCmd $DISK $PART $POSTCONF '@echo off'
ogAddCmd $DISK $PART $POSTCONF 'start "C:\Program Files\Internet Explorer\iexplore.exe" wwww.opengnsys.es'
ogAddCmd $DISK $PART $POSTCONF "timeout /t 200 /NOBREAK"
ogAddCmd $DISK $PART $POSTCONF "shutdown -r -t 300"
ogAddCmd $DISK $PART $POSTCONF 'start winword.exe'
ogAddCmd $DISK $PART $POSTCONF 'taskkill /F /IM winword.exe'
ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\CurrentControlSet\Services\kbdclass\ /v Start /t REG_DWORD /d 3 /f'
ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\CurrentControlSet\Services\mouclass\ /v Start /t REG_DWORD /d 3 /f'
ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\ControlSet001\Services\kbdclass\ /v Start /t REG_DWORD /d 3 /f'
ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\ControlSet001\Services\mouclass\ /v Start /t REG_DWORD /d 3 /f'
#ogAddCmd $DISK $PART $POSTCONF '"c:\Program Files\Toolwiz Time Freeze 2017\ToolwizTimeFreeze.exe" /freezealways /usepass='
#ogAddCmd $DISK $PART $POSTCONF 'reg query "HKCU\SOFTWARE\Toolwiz\TimefreezeNew"'
#ogAddCmd $DISK $PART $POSTCONF "cscript \"c:\Archivo de Programas (x86)\agua\aguac\scripts\MSOfficeActivate.vbs\" "
#ogAddCmd $DISK $PART $POSTCONF "del \"c:\Program Files (x86)\agua\aguac\scripts\MSWinActivate.vbs\" "
#unix2dos /mnt/sda1/Windows/System32/postconf.cmd
### reiniciamos el equipo
ogAddCmd $DISK $PART $POSTCONF "shutdown -r"
### consultamos
cat $(ogMount $DISK $PART)/Windows/System32/$POSTCONF
;;
esac

View File

@ -1,62 +0,0 @@
#!/bin/bash
#/**
# smartPartition.template
#@brief particiona los clientes del laboratorio virtual.
#@param 1
#@ejemplo:
#@return: Scripts de ejemplo para establecer particionado según tamaño.
#@exception OG_ERR_ NOTFOUND Disco duro no encontrador.
#@note
#@todo:
#@version 0.1 primera version
#@author adv
#@date 2018/07/08
#Calculamos el numero de discos
NDISK=$(ogDiskToDev | wc -w)
#Si no hay discos, error
[ -z $NDISK ] && exit $(ogRaiseError $OG_ERR_NOTFOUND "ogDiskToDev | wc -w")
#asignamos contador al primer disco de OpenGnsys
COUNTER=1
until [ $COUNTER -gt $NDISK ]; do
ogUnmountAll $COUNTER
ogDeletePartitionTable $COUNTER
ogCreatePartitionTable $COUNTER MSDOS
ogUpdatePartitionTable $COUNTER
let COUNTER=COUNTER+1
done
#Establecemos las Particiones CACHE con tamaños diferentes según la capacidad del disco.
#Si el PC tiene dos discos duros, el segundo será completo para la CACHE.
#establecemos rangos de las capacidades con expresiones regulares: https://goo.gl/gJnK7g
case $NDISK in
1)
#Calcular el tamaño máximo del disco duro redondeando a la baja en 500 MB para evitar problemas de calculo"
SIZE_DISK1=$(expr $(ogGetDiskSize 1) - 500000)
#entre 70 y 73'9GB
ogCheckStringInReg $SIZE_DISK1 "^7[0-3][0-9]{6}$" && initCache 1 4 32000000 NOMOUNT
#entre 50 y 52'9
ogCheckStringInReg $SIZE_DISK1 "^5[0-2][0-9]{6}$" && initCache 1 4 12000000 NOMOUNT
;;
2)
#Calcular el tamaño máximo del disco duro redondeando a la baja en 500 MB para evitar problemas de calculo"
SIZE_DISK2=$(expr $(ogGetDiskSize 1) - 500000)
initCache 2 4 $SIZE_DISK2 NOMOUNT
;;
esac
#El particionado para los sistemas operativos identicos para todos.
#Requiere tener una tabla de particiones previa.
ogCreatePartitions 1 NTFS:19000000 LINUX:19000000 EMPTY:0;
#asignamos contador al primer disco de OpenGnsys
COUNTER=1
until [ $COUNTER -gt $NDISK ]; do
ogBootMbrGeneric $COUNTER
ogSetPartitionActive 1 $COUNTER
ogListPartitions $COUNTER
ogGetPartitionActive $COUNTER
let COUNTER=COUNTER+1
done

View File

@ -7,7 +7,7 @@
#@param 3 str_protoco. TORRENT | MULTICAST | UNICAST.
#@param 4 str_opcionesprotocolo
#@param 4 str_opcionesupdatecache
#@ejemplo: updateCache.py REPO imgname.img UNICAST 8042:42
#@ejemplo: updateCache REPO imgname.img UNICAST 8042:42
#@return
#@exception OG_ERR_FORMAT formato incorrecto.
#@exception OG_ERR_NOTCACHE No existe cache -15-