92 lines
2.4 KiB
Python
92 lines
2.4 KiB
Python
import logging
|
|
import os
|
|
import random
|
|
import socket
|
|
import string
|
|
import xml.etree.ElementTree as ET
|
|
from logging.handlers import RotatingFileHandler
|
|
from pathlib import Path
|
|
|
|
|
|
def configure_logging():
|
|
current_file = Path(__file__).resolve()
|
|
sdsat_root = current_file.parent.parent
|
|
log_dir = sdsat_root / "logs"
|
|
log_dir.mkdir(parents=True, exist_ok=True)
|
|
log_file = log_dir / "change_hostname.log"
|
|
|
|
handler = RotatingFileHandler(
|
|
str(log_file),
|
|
maxBytes=2 * 1024 * 1024,
|
|
backupCount=2,
|
|
)
|
|
formatter = logging.Formatter("%(asctime)s %(message)s")
|
|
handler.setFormatter(formatter)
|
|
|
|
root = logging.getLogger()
|
|
root.setLevel(logging.INFO)
|
|
root.handlers.clear()
|
|
root.addHandler(handler)
|
|
|
|
|
|
def generate_random_string(length: int) -> str:
|
|
letters = string.ascii_lowercase
|
|
return "".join(random.choice(letters) for _ in range(length))
|
|
|
|
|
|
def update_config_hostname(config_path: str, new_hostname: str) -> tuple[str | None, bool]:
|
|
"""
|
|
Met à jour <hostname> dans le XML.
|
|
Retourne (old_hostname, changed)
|
|
"""
|
|
tree = ET.parse(config_path)
|
|
root = tree.getroot()
|
|
|
|
old_hostname = None
|
|
changed = False
|
|
|
|
for elem in root.iter("hostname"):
|
|
old_hostname = elem.text
|
|
elem.text = new_hostname
|
|
changed = True
|
|
|
|
if changed:
|
|
tree.write(config_path)
|
|
|
|
return old_hostname, changed
|
|
|
|
|
|
def apply_hostname(new_hostname: str) -> int:
|
|
# Retourne le code retour de la commande
|
|
return os.system(f"sudo hostname {new_hostname}")
|
|
|
|
|
|
def main(
|
|
expected_hostname: str = "sd-satxx.dtx.io",
|
|
config_path: str = "/conf/config.xml",
|
|
) -> None:
|
|
configure_logging()
|
|
|
|
host = socket.gethostname()
|
|
logging.info(f"Hostname recupere : {host}")
|
|
|
|
if host != expected_hostname:
|
|
logging.info("No need to change, changed already YBT")
|
|
return
|
|
|
|
new_hostname = "DTX-SDSAT-" + generate_random_string(10)
|
|
logging.info(f"New hostname is: {new_hostname}")
|
|
|
|
old_hostname, changed = update_config_hostname(config_path, new_hostname)
|
|
if changed:
|
|
logging.info(f"Changed hostname from {old_hostname} to {new_hostname}")
|
|
else:
|
|
logging.info("No <hostname> element found in config.xml")
|
|
|
|
rc = apply_hostname(new_hostname)
|
|
logging.info(f"Hostname change completed successfully (rc={rc})")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|