1
This commit is contained in:
72
backend.py
72
backend.py
@@ -1962,6 +1962,78 @@ def chroot_and_repair_grub(mount_point: str, target_disk: str,
|
||||
else:
|
||||
log_warning(f"✗ EFI 目录不存在: {efi_check_path}")
|
||||
|
||||
# ===== 清空并重建 GRUB 环境(针对严重损坏的系统)=====
|
||||
log_step("清空并重建 GRUB 环境")
|
||||
|
||||
# 确定正确的 GRUB 目录名
|
||||
if distro_type in ["centos", "rhel", "fedora", "rocky", "almalinux", "opensuse"]:
|
||||
grub_dir_name = "grub2"
|
||||
else:
|
||||
grub_dir_name = "grub"
|
||||
|
||||
# 1. 清空 /boot/grub* 目录
|
||||
boot_grub_paths = [
|
||||
os.path.join(mount_point, "boot", "grub"),
|
||||
os.path.join(mount_point, "boot", "grub2"),
|
||||
]
|
||||
for grub_path in boot_grub_paths:
|
||||
if os.path.exists(grub_path):
|
||||
log_info(f"清空目录: {grub_path}")
|
||||
try:
|
||||
# 删除目录内所有内容但保留目录本身
|
||||
for item in os.listdir(grub_path):
|
||||
item_path = os.path.join(grub_path, item)
|
||||
if os.path.isfile(item_path) or os.path.islink(item_path):
|
||||
os.unlink(item_path)
|
||||
log_debug(f" 删除文件: {item}")
|
||||
elif os.path.isdir(item_path):
|
||||
import shutil
|
||||
shutil.rmtree(item_path)
|
||||
log_debug(f" 删除目录: {item}")
|
||||
log_success(f"✓ 已清空: {grub_path}")
|
||||
except Exception as e:
|
||||
log_warning(f"清空失败: {e}")
|
||||
|
||||
# 2. 清空 EFI 分区中的 GRUB 相关目录
|
||||
efi_cleanup_dirs = ["GRUB", "grub", "Boot", "boot", "centos", "redhat", "fedora"]
|
||||
for efi_dir in efi_cleanup_dirs:
|
||||
efi_dir_path = os.path.join(mount_point, "boot/efi/EFI", efi_dir)
|
||||
if os.path.exists(efi_dir_path):
|
||||
log_info(f"清空 EFI 目录: {efi_dir_path}")
|
||||
try:
|
||||
import shutil
|
||||
shutil.rmtree(efi_dir_path)
|
||||
log_success(f"✓ 已删除: {efi_dir_path}")
|
||||
except Exception as e:
|
||||
log_warning(f"删除失败: {e}")
|
||||
|
||||
# 3. 重建目录结构
|
||||
log_info("重建 GRUB 目录结构...")
|
||||
dirs_to_create = [
|
||||
os.path.join(mount_point, "boot", grub_dir_name),
|
||||
os.path.join(mount_point, "boot/efi/EFI", efi_bootloader_id),
|
||||
os.path.join(mount_point, "boot/efi/EFI", "Boot"),
|
||||
]
|
||||
for dir_path in dirs_to_create:
|
||||
try:
|
||||
os.makedirs(dir_path, exist_ok=True)
|
||||
log_info(f"✓ 创建目录: {dir_path}")
|
||||
except Exception as e:
|
||||
log_warning(f"创建目录失败: {e}")
|
||||
|
||||
# 4. 创建 grubenv 文件(普通文件,不是符号链接)
|
||||
grubenv_path = os.path.join(mount_point, "boot", grub_dir_name, "grubenv")
|
||||
try:
|
||||
with open(grubenv_path, 'w') as f:
|
||||
f.write("# GRUB Environment Block\n")
|
||||
f.write("saved_entry=\n")
|
||||
f.write("#" * 1024 + "\n")
|
||||
log_success(f"✓ 创建 grubenv: {grubenv_path}")
|
||||
except Exception as e:
|
||||
log_warning(f"创建 grubenv 失败: {e}")
|
||||
|
||||
log_success("✓ GRUB 环境重建完成")
|
||||
|
||||
grub_install_cmd = chroot_cmd_prefix + [
|
||||
_grub_install_cmd,
|
||||
f"--target={efi_target}",
|
||||
|
||||
Reference in New Issue
Block a user