跳到主要内容

修改ventoy启动配置

目录

用Ventoy启动WTG两年了,已经是深度用户了。之前还特意买了个1T的U盘,放了很多系统,Win10、Win11、Linux什么的,基本上每个都有用,但是每次要切换系统重启的时候都得守在电脑前选启动项。所以就让GPT写了个脚本,在重启前就设置好启动项,然后重启就能自动进入了。

以前一直都是用的bat命令,但是bat脚本处理文件真的一言难尽,它总是将文本文件的编码改为GBK,而大多数软件认可的都是UTF-8。不得不抛弃了bat,要说什么语言最适合写脚本,那必然是Python了。

Ventoy配置文件

Ventoy的启动配置是写在一个json文件里的,首先用Ventoy提供的的配置软件打开设置一遍,就会生成相应的配置文件。

以下为Ventoy配置文件的内容,只需要修改第7行和第10行:

{
    "control":[
        { "VTOY_SORT_CASE_SENSITIVE": "1" },
        { "VTOY_MAX_SEARCH_LEVEL": "0" },
        { "VTOY_LINUX_REMOUNT": "1" },
        { "VTOY_SECONDARY_BOOT_MENU": "0" },
        { "VTOY_MENU_TIMEOUT": "3" },
        { "VTOY_MENU_LANGUAGE": "zh_CN" },
        { "VTOY_DEFAULT_SEARCH_ROOT": "/镜像" }

    ],
    "theme":{
        "file": "/ventoy/themes/Vimix-1080p/Vimix/theme.txt",
        "gfxmode": "1920x1080",
        "ventoy_color": "#282629"
    },
    "menu_class":[
        {
            "key": "vhdx",
            "class": "windows"
        },
        {
            "key": "Ubuntu",
            "class": "ubuntu"
        },
        {
            "key": "Mint",
            "class": "linuxmint"
        },
        {
            "key": "Manjaro",
            "class": "manjaro"
        },
        {
            "key": "Arch",
            "class": "arch"
        },
        {
            "key": "Debian",
            "class": "debian"
        },
        {
            "key": "Kubuntu",
            "class": "kubuntu"
        },
        {
            "key": "iso",
            "class": "windows"
        }
    ],
    "persistence":[
        {
            "image": "/镜像/B_Ubuntu-22.04.3-desktop-amd64.iso",
            "backend":[
                "/ventoy/1_persistence_10G.dat",
                "/ventoy/2_persistence_10G.dat",
                "/ventoy/3_persistence_10G.dat",
                "/ventoy/4_persistence_10G.dat",
                "/ventoy/5_persistence_10G.dat"
            ]
        }
    ]
}

文件的第7行设置“选择超时”,比如设置为“3”,3秒后就自动启动所选项。

第10行就是设置启动项,设置好就会在超时后自动启动。我的第10行是空行,就是默认选择第一项。

脚本内容

Python脚本,具体逻辑和功能看注释就能明白了:

import os

# 列出指定目录中的vhdx, vhd, iso文件
def list_files(directory):
    file_list = []
    for file_name in os.listdir(directory):
        if file_name.lower().endswith(('.vhdx', '.vhd', '.iso')) and os.path.isfile(os.path.join(directory, file_name)):
            file_list.append(file_name)
    return file_list

# 替换ventoy.json中的第10行
def replace_line_in_json(json_path, new_line):
    with open(json_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # 如果第10行为空,则在第九行末尾添加一个逗号
    if len(lines) >= 10 and lines[9].strip():
        pass
    else:
        lines[8] = lines[8][:-1] + ",\n"
        
    # 替换第10行
    if len(lines) >= 10:
        lines[9] = new_line + "\n"
    else:
        lines.append(new_line + "\n")
    
    with open(json_path, 'w', encoding='utf-8') as f:
        f.writelines(lines)

# 清空ventoy.json中的第10行
def clear_line_in_json(json_path):
    with open(json_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    if len(lines) >= 10 and lines[9].strip():
        if len(lines) >= 10:
            lines[9] = "\n"
        if len(lines) >= 9 and lines[8].strip():  # 检查第9行是否存在且非空
            lines[8] = lines[8][:-2] + "\n"  # 删除最后一个字符

        with open(json_path, 'w', encoding='utf-8') as f:
            f.writelines(lines)

# 主程序
def main():
    # 文件夹路径
    img_dir = "D:\\镜像"
    ventoy_json_path = "D:\\ventoy\\ventoy.json"

    # 列出文件
    files = list_files(img_dir)
    if not files:
        print("没有找到任何符合条件的文件!")
        return
    
    # 打印文件列表
    print("请选择启动项:\n")
    print("  [0] - 清除启动项配置\n")
    for i, file in enumerate(files, 1):
        print(f"  [{i}] - {file}\n")

    # 获取用户输入
    while True:
        try:
            choice = int(input("\n请输入选项序号:"))
            if 0 <= choice <= len(files):
                break
            else:
                print("\n无效的选项,请输入有效的序号。")
        except ValueError:
            print("\n输入无效,请输入一个数字。")
    
    # 根据选择进行操作
    if choice == 0:
        clear_line_in_json(ventoy_json_path)
        print("\n启动配置已清除,默认为第一项。")
    else:
        selected_file = files[choice - 1]
        new_line = f'        {{ "VTOY_DEFAULT_IMAGE": "/镜像/{selected_file}" }}'
        replace_line_in_json(ventoy_json_path, new_line)
        print(f"\n启动项已设置为: {selected_file}")

    # 询问是否重启
    restart = input("\n是否重启电脑?(y/n): ").strip().lower()
    if restart == 'y':
        print("\n重启电脑...")
        os.system("shutdown /r /t 0")
    else:
        print("\n程序结束。")

# 运行脚本
if __name__ == "__main__":
    main()