This commit is contained in:
@@ -1,58 +1,91 @@
|
||||
import os
|
||||
import string
|
||||
import random
|
||||
import xml.etree.ElementTree as ET
|
||||
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 generate_random_string(length):
|
||||
|
||||
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
|
||||
result_str = ''.join(random.choice(letters) for i in range(length))
|
||||
return result_str
|
||||
return "".join(random.choice(letters) for _ in range(length))
|
||||
|
||||
# Set up logging
|
||||
logging.basicConfig(filename='/sdsat/logs/change_hostname.log', level=logging.INFO, format='%(asctime)s %(message)s')
|
||||
|
||||
host = socket.gethostname()
|
||||
print (host)
|
||||
logging.info(f"Hostname recupere : {host}")
|
||||
|
||||
if host == "sd-satxx.dtx.io" :
|
||||
new_hostname = "DTX-SDSAT-" + generate_random_string(10)
|
||||
logging.info('New hostname is: ' + new_hostname)
|
||||
|
||||
# Parse the XML configuration file
|
||||
|
||||
tree = ET.parse('/conf/config.xml')
|
||||
|
||||
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
|
||||
|
||||
# Find the hostname element and update it
|
||||
|
||||
for elem in root.iter('hostname'):
|
||||
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
|
||||
|
||||
|
||||
# Log the old and new hostname
|
||||
|
||||
logging.info('Changed hostname from ' + str(old_hostname) + ' to ' + new_hostname)
|
||||
def apply_hostname(new_hostname: str) -> int:
|
||||
# Retourne le code retour de la commande
|
||||
return os.system(f"sudo hostname {new_hostname}")
|
||||
|
||||
|
||||
# Save the modified XML configuration file
|
||||
def main(
|
||||
expected_hostname: str = "sd-satxx.dtx.io",
|
||||
config_path: str = "/conf/config.xml",
|
||||
) -> None:
|
||||
configure_logging()
|
||||
|
||||
tree.write('/conf/config.xml')
|
||||
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})")
|
||||
|
||||
|
||||
# Apply the new hostname immediately (this will require root privileges)
|
||||
|
||||
os.system("sudo hostname " + new_hostname)
|
||||
|
||||
|
||||
# Log the completion of the script
|
||||
|
||||
logging.info('Hostname change completed successfully')
|
||||
|
||||
else:
|
||||
logging.info('No need to change, changed already YBT')
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user