import subprocess import sys import os import json import ogGlobals import NetLib import SystemLib #/** # ogChangeRepo IPREPO [ OgUnit ] #@brief Cambia el repositorio para el recurso remoto images. #@param 1 Ip Repositorio #@param 2 Abreviatura Unidad Organizativa #@return Cambio recurso remoto en OGIMG. #*/ def ogChangeRepo(ip_repo, og_unit=None): ogprotocol = "cifs" try: rw_option = ",rw" if "rw" in subprocess.getoutput("mount | grep 'ogimages'") else ",ro" current_repo = ogGetRepoIp() current_og_unit = subprocess.getoutput( "df | awk -F ' ' '/ogimages/ {sub(\"//.*/ogimages\",\"\",$1); sub(\"/\",\"\",$1); print $1}'" ).strip() new_repo = current_repo if ip_repo.upper() == "REPO" else ip_repo if new_repo == current_repo and og_unit == current_og_unit: return 0 subprocess.run(["umount", ogGlobals.OGIMG], check=True) src_img = "ogimages" if not og_unit else f"ogimages/{og_unit}" result = subprocess.run( ["ogConnect", new_repo, ogprotocol, src_img, ogGlobals.OGIMG, rw_option], text=True, ) if result.returncode != 0: subprocess.run( ["ogConnect", current_repo, ogprotocol, src_img, ogGlobals.OGIMG, rw_option], text=True, ) SystemLib.ogRaiseError( "session", ogGlobals.OG_ERR_REPO, f"Error connecting to the new repository: {new_repo}", ) return 1 SystemLib.ogEcho( "session", "log", f"Repository successfully changed to {new_repo} {og_unit or ''}".strip(), ) return 0 except Exception as e: SystemLib.ogRaiseError( "session", ogGlobals.OG_ERR_FORMAT, f"Error executing ogChangeRepo: {e}", ) return 1 #/** # ogGetGroupDir [ str_repo ] #@brief Devuelve el camino del directorio para el grupo del cliente. #@param str_repo repositorio de imágenes (opcional) #@return path_dir - Camino al directorio del grupo. #@note repo = { REPO, CACHE } REPO por defecto #@exception OG_ERR_FORMAT formato incorrecto. #*/ def ogGetGroupDir(): REPO = "" DIR = "" GROUP = "" if len(sys.argv) < 2: SystemLib.ogHelp("ogGetGroupDir", "ogGetGroupDir str_repo", "ogGetGroupDir REPO ==> /opt/opengnsys/images/groups/Grupo1") return if len(sys.argv) == 1: REPO = "REPO" else: REPO = sys.argv[1] GROUP = ogGetGroupName() if GROUP: DIR = FileLib.ogGetPath(REPO, "/groups/" + GROUP, stderr=subprocess.DEVNULL) if os.path.isdir(DIR): print(DIR) return 0 #/** # ogGetGroupName #@brief Devuelve el nombre del grupo al que pertenece el cliente. #@return str_group - Nombre de grupo. #*/ def ogGetGroupName(): try: group = globals().get("group", None) return group if group else None except Exception as e: print(f"Error in ogGetGroupName: {e}") return None #/** # ogGetHostname #@brief Muestra el nombre del cliente. #@return str_host - nombre de máquina #*/ ## def ogGetHostname(): HOST = "" if len(sys.argv) >= 2 and sys.argv[1] == "help": SystemLib.ogHelp("ogGetHostname", "ogGetHostname", "ogGetHostname => pc1") return # Tomar nombre de la variable HOSTNAME HOST = os.getenv("HOSTNAME") # Si no, tomar del DHCP, opción host-name if not HOST: with open("/var/lib/dhcp3/dhclient.leases", "r") as f: for line in f: if "option host-name" in line: HOST = line.split('"')[1] break # Si no, leer el parámetro del kernel hostname if not HOST: with open("/proc/cmdline", "r") as f: cmdline = f.read() HOST = re.search(r"hostname=([^ ]+)", cmdline) if HOST: HOST = HOST.group(1) if HOSTNAME != HOST: os.environ["HOSTNAME"] = HOST if HOST: print(HOST) #/** # ogGetIpAddress #@brief Muestra la dirección IP del sistema #@return str_ip - Dirección IP #@note Usa las variables utilizadas por el initrd "/etc/net-ethX.conf #*/ ## def ogGetIpAddress(): IP = "" if len(sys.argv) >= 2 and sys.argv[1] == "help": SystemLib.ogHelp("ogGetIpAddress", "ogGetIpAddress", "ogGetIpAddress => 192.168.0.10") return if "IPV4ADDR" in os.environ: IP = os.environ["IPV4ADDR"] else: # Obtener direcciones IP. if "DEVICE" in os.environ: IP = subprocess.run(["ip", "-o", "address", "show", "up", "dev", os.environ["DEVICE"]], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split() else: IP = subprocess.run(["ip", "-o", "address", "show", "up"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split() IP = [addr.split("/")[0] for addr in IP if "inet" in addr] # Mostrar solo la primera. if IP: print(IP[0]) return 0 #/** # ogGetMacAddress #@brief Muestra la dirección Ethernet del cliente. #@return str_ether - Dirección Ethernet #*/ ## def ogGetMacAddress(): try: if "DEVICE" in os.environ: device = os.environ["DEVICE"] result = subprocess.run( ["ip", "-o", "link", "show", "up", "dev", device], capture_output=True, text=True, check=True ).stdout else: result = subprocess.run( ["ip", "-o", "link", "show", "up"], capture_output=True, text=True, check=True ).stdout mac_addresses = [] for line in result.splitlines(): if "link/ether" in line: parts = line.split() for i, part in enumerate(parts): if part == "link/ether": mac_addresses.append(parts[i + 1].upper()) if mac_addresses: print(mac_addresses[0]) return mac_addresses[0] else: print("No active mac address found") return None except subprocess.CalledProcessError as e: print(f"Error executing ip command: {e.stderr}") return None except Exception as e: print(f"Unexpected error: {str(e)}") return None #/** # ogGetNetInterface #@brief Muestra la interfaz de red del sistema #@return str_interface - interfaz de red #@note Usa las variables utilizadas por el initrd "/etc/net-ethX.conf #*/ ## def ogGetNetInterface(): if len(sys.argv) >= 2 and sys.argv[1] == "help": SystemLib.ogHelp("ogGetNetInterface", "ogGetNetInterface", "ogGetNetInterface => eth0") return if "DEVICE" in os.environ: print(os.environ["DEVICE"]) return 0 #/** # ogGetRepoIp #@brief Muestra la dirección IP del repositorio de datos. #@return str_ip - Dirección IP #*/ ## def ogGetRepoIp(): out = subprocess.run (["findmnt", "--json", "--output", "SOURCE,FSTYPE", ogGlobals.OGIMG], capture_output=True, text=True).stdout try: j = json.loads (out) except json.decoder.JSONDecodeError: return None if 'filesystems' not in j: return None source = j['filesystems'][0]['source'] fstype = j['filesystems'][0]['fstype'] if 'nfs' == fstype: return source.split(":")[0] elif 'cifs' == fstype: return source.split("/")[2] return None #/** # ogGetServerIp #@brief Muestra la dirección IP del Servidor de OpenGnSys. #@return str_ip - Dirección IP #@note Comprobacion segun protocolo de conexion al Repo #*/ ## def ogGetServerIp(): try: output = subprocess.run( ["findmnt", "--json", "--output", "SOURCE,FSTYPE", ogGlobals.OGIMG], capture_output=True, text=True, check=True ).stdout except subprocess.CalledProcessError as e: SystemLib.ogEcho("session", "error", f"Error to run findmnt: {e.stderr}") return None try: mounts = json.loads(output) except json.decoder.JSONDecodeError: SystemLib.ogEcho("session", "error", "Error to decode JSON de findmnt.") return None if 'filesystems' not in mounts or not isinstance(mounts['filesystems'], list): SystemLib.ogEcho("session", "error", "'filesystems' is not present o not valid in JSON.") return None for fs in mounts['filesystems']: if 'source' in fs and 'fstype' in fs: source = fs['source'] fstype = fs['fstype'] if fstype == "nfs": return source.split(":")[0] elif fstype == "cifs": return source.split("/")[2] SystemLib.ogEcho("session", "info", "No valid file system found") return None #/** # ogMakeGroupDir [ str_repo ] #@brief Crea el directorio para el grupo del cliente. #@param str_repo repositorio de imágenes (opcional) #@return (nada) #@note repo = { REPO, CACHE } REPO por defecto #@exception OG_ERR_FORMAT formato incorrecto. #*/ def ogMakeGroupDir(): REPO = "" DIR = "" GROUP = "" if len(sys.argv) < 2: SystemLib.ogHelp("ogMakeGroupDir", "ogMakeGroupDir str_repo", "ogMakeGroupDir", "ogMakeGroupDir REPO") return if len(sys.argv) == 1: REPO = "REPO" else: REPO = sys.argv[1] DIR = FileLib.ogGetPath(REPO, "/groups/" + ogGetGroupName(), stderr=subprocess.DEVNULL) if DIR: subprocess.run(["mkdir", "-p", DIR], stderr=subprocess.DEVNULL) return 0