This commit is contained in:
zj
2026-02-12 03:11:52 +08:00
parent bd3c09ebf4
commit 8769ec5698

View File

@@ -2235,49 +2235,47 @@ def chroot_and_repair_grub(mount_point: str, target_disk: str,
else:
grub_dir_name = "grub"
# 尝试多种可能的路径(处理独立 /boot 分区的情况)
possible_grubenv_paths = [
grubenv_path, # 标准路径
os.path.join(mount_point, "boot", grub_dir_name, "grubenv"),
os.path.join(mount_point, "boot", "grub2", "grubenv"),
os.path.join(mount_point, "boot", "grub", "grubenv"),
os.path.join(mount_point, grub_dir_name, "grubenv"),
os.path.join(mount_point, "grub2", "grubenv"),
os.path.join(mount_point, "grub", "grubenv"),
]
for test_path in possible_grubenv_paths:
if os.path.exists(test_path):
log_info(f"✓ 发现 grubenv 已存在于: {test_path}")
grubenv_path = test_path
break
else:
# 没有找到现有文件,尝试创建
# 首先确保首选目录存在(通过主机直接创建)
preferred_dir = os.path.join(mount_point, "boot", grub_dir_name)
preferred_dir = os.path.dirname(grubenv_path) # 正确路径的目录
try:
os.makedirs(preferred_dir, exist_ok=True)
log_info(f"✓ 确保目录存在: {preferred_dir}")
except Exception as e:
log_warning(f"创建目录失败: {e}")
for test_path in possible_grubenv_paths:
# 尝试多种可能的路径,检查是否已有 grubenv 在错误位置
possible_wrong_paths = [
os.path.join(mount_point, "boot", "grub" if grub_dir_name == "grub2" else "grub2", "grubenv"),
os.path.join(mount_point, "grub" if grub_dir_name == "grub2" else "grub2", "grubenv"),
]
wrong_path_found = None
for wrong_path in possible_wrong_paths:
if os.path.exists(wrong_path):
wrong_path_found = wrong_path
log_info(f"发现 grubenv 在错误位置: {wrong_path}")
break
# 如果找到错误位置的 grubenv复制到正确位置
if wrong_path_found:
try:
import shutil
shutil.copy2(wrong_path_found, grubenv_path)
log_success(f"✓ 复制 grubenv 到正确位置: {grubenv_path}")
except Exception as e:
log_warning(f"复制失败: {e}")
# 如果仍未创建成功,尝试直接创建
if not os.path.exists(grubenv_path):
try:
dir_path = os.path.dirname(test_path)
os.makedirs(dir_path, exist_ok=True)
# 创建一个空的 grubenv 文件(包含必要的头部)
with open(test_path, 'w') as f:
with open(grubenv_path, 'w') as f:
f.write("# GRUB Environment Block\n")
f.write("saved_entry=\n")
f.write("#" * 1024 + "\n") # 填充到至少1KB
log_success(f"✓ 手动创建 grubenv 文件成功: {test_path}")
grubenv_path = test_path
break
log_success(f"✓ 手动创建 grubenv 文件成功: {grubenv_path}")
except Exception as e:
log_debug(f"尝试创建 {test_path} 失败: {e}")
continue
else:
log_warning(f"所有路径创建 grubenv 文件均失败")
log_warning(f"创建 grubenv 文件失败: {e}")
# 执行配置更新
success, stdout, stderr = run_command(