osgos_postinstall/deb_dist/postinstall-1.0.1/build/lib/postinstall/option/hostname.py

76 lines
No EOL
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import subprocess
from dialog import Dialog
import os
HOSTNAME_FILE = "/etc/hostname"
HOSTS_FILE = "/etc/hosts"
def get_current_hostname():
try:
with open(HOSTNAME_FILE, 'r') as f:
return f.read().strip()
except IOError as e:
print(f"Ошибка при чтении hostname: {e}")
return "localhost"
def change_hostname():
d = Dialog(dialog="dialog")
current_hostname = get_current_hostname()
code, new_hostname = d.inputbox(
f"Текущее доменное имя: {current_hostname}\nВведите новое доменное имя:",
init=current_hostname
)
if code != d.OK:
return None
if new_hostname == current_hostname:
d.msgbox("Введенное доменное имя совпадает с текущим. Изменения не требуются.")
return None
# Проверка валидности hostname
if not is_valid_hostname(new_hostname):
d.msgbox("Недопустимое доменное имя. Используйте только буквы, цифры и дефисы.")
return None
# Подтверждение изменения
code = d.yesno(f"Вы уверены, что хотите изменить доменное имя на {new_hostname}?")
if code != d.OK:
return None
return new_hostname
def is_valid_hostname(hostname):
if len(hostname) > 63:
return False
if hostname[-1] == "-":
return False
allowed = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
return all(char in allowed for char in hostname)
def apply_hostname_change(new_hostname):
try:
subprocess.run(["sudo", "hostnamectl", "set-hostname", new_hostname], check=True)
if os.path.exists(HOSTS_FILE):
subprocess.run(["sudo", "sed", "-i", f"s/^127.0.1.1.*/127.0.1.1\t{new_hostname}/", HOSTS_FILE], check=True)
return True
except subprocess.CalledProcessError as e:
Dialog(dialog="dialog").msgbox(f"Ошибка при изменении доменного имени: {e}")
return False
def run_change_hostname():
return change_hostname()
if __name__ == "__main__":
new_hostname = run_change_hostname()
if new_hostname:
print(f"Новое доменное имя: {new_hostname}")
else:
print("Изменение доменного имени отменено.")