WIM挂载脚本
原创
Qiuguo
Qiuguo
沉思安全
2026年10月22日 15:36
河南
去阅读
wim_boot.py
code
-\- coding: utf-8 -\-
\"\"\"
WIM 开机工具 (分享版) —— 把裸 WIM 文件(boot.wim / 各种PE的WIM)包成可启动ISO并在VMware开机
用法: python wim\_boot.py
或直接把 WIM 拖到 WIM开机.bat 上
依赖: Python 3.8+ / pywin32 (pip install pywin32) / VMware Workstation(可选)
材料: 默认用 C:\\Windows\\Boot 自带引导件(任何Win10/11都有);
若提供 Win10官方ISO 则优先借用其引导件(更标准)。
首次运行会询问并记住 7z / Win10ISO / vmrun 路径(存到本目录 wim\_boot\_paths.cfg,可删掉重配)
\"\"\"
import sys, os, shutil, subprocess, winreg
CFG\FILE = os.path.join(os.path.dirname(os.path.abspath(\\file\\_)), \"wim\_boot\_paths.cfg\")
---- Windows 自带引导材料(所有Win10/11都存在,零外部依赖) ----
BUILTIN = {
\"bootmgr\": r\"C:\Windows\Boot\PCAT\bootmgr\",
\"bcd\": r\"C:\Windows\Boot\DVD\PCAT\BCD\",
\"boot.sdi\": r\"C:\Windows\Boot\DVD\PCAT\boot.sdi\",
\"etfsboot\": r\"C:\Windows\Boot\DVD\PCAT\etfsboot.com\",
\"fonts\": r\"C:\Windows\Boot\Fonts\",
}
VMX\_TMPL = \"\"\".encoding = \"windows-1252\"
config.version = \"8\"
virtualHW.version = \"14\"
displayName = \"{name} (WIM)\"
guestOS = \"windows10-64\"
firmware = \"bios\"
memsize = \"4096\"
numvcpus = \"2\"
uuid.action = \"create\"
msg.autoAnswer = \"TRUE\"
ide1:0.present = \"TRUE\"
ide1:0.deviceType = \"cdrom-image\"
ide1:0.fileName = \"{iso}\"
ide1:0.startConnected = \"TRUE\"
ethernet0.present = \"TRUE\"
ethernet0.connectionType = \"nat\"
ethernet0.virtualDev = \"e1000\"
sound.present = \"FALSE\"
\"\"\"
def die(msg):
print(\"[X]\", msg)
try:
input(\"按回车退出...\")
except EOFError:
pass
sys.exit(1)
---------- 路径配置: cfg文件 -> 自动探测 -> 交互询问 ----------
def load\_cfg():
cfg = {}
if os.path.isfile(CFG\_FILE):
for line in open(CFG\_FILE, encoding=\"utf-8-sig\"):
line = line.strip()
if \"=\" in line and not line.startswith(\"#\"):
k, v = line.split(\"=\", 1)
cfg[k.strip()] = v.strip()
return cfg
def save\_cfg(cfg):
with open(CFG\_FILE, \"w\", encoding=\"utf-8\") as f:
f.write(\"# wim\_boot 路径配置(可删除本文件重新配置)\
\")
for k, v in cfg.items():
f.write(f\"{k}={v}\
\")
def ask\_path(key, desc, optional=True):
tip = \" (直接回车=跳过,此功能不可用)\" if optional else \"\"
while True:
s = input(f\"请输入{desc}路径{tip}: \").strip().strip('\"')
if not s:
if optional:
return \"\"
die(f\"缺少必需路径: {desc}\")
if os.path.isfile(s):
return os.path.abspath(s)
print(\" 文件不存在,请重输\")
def autodetect():
found = {}
# 7z
for p in [r\"C:\Program Files\7-Zip\7z.exe\",
r\"C:\Program Files (x86)\7-Zip\7z.exe\"]:
if os.path.isfile(p):
found[\"sevenz\"] = p
break
# vmrun: 注册表 + 常见位置
vmrun = None
for root, wow in [(winreg.HKEY\LOCAL\_MACHINE, True), (winreg.HKEY\_LOCAL\_MACHINE, False)]:
try:
key = winreg.OpenKey(root, r\"SOFTWARE\WOW6432Node\VMware, Inc.\VMware Workstation\")
v, \ = winreg.QueryValueEx(key, \"InstallPath\")
cand = os.path.join(v, \"vmrun.exe\")
if os.path.isfile(cand):
vmrun = cand
break
except OSError:
pass
if not vmrun:
for p in [r\"C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe\",
r\"C:\Program Files\VMware\VMware Workstation\vmrun.exe\",
r\"D:\VMware\vmrun.exe\", r\"E:\VMware\vmrun.exe\"]:
if os.path.isfile(p):
vmrun = p
break
if vmrun:
found[\"vmrun\"] = vmrun
return found
def get\_paths(interactive=True):
cfg = load\_cfg()
auto = autodetect()
need = {\"sevenz\": \"7z.exe (用于从Win10 ISO提取引导件,可选)\",
\"shell\_iso\": \"Win10官方安装ISO (可选,提供更标准的引导件)\",
\"vmrun\": \"vmrun.exe (VMware,用于自动开机,可选)\"}
changed = False
for k, desc in need.items():
if k in cfg and os.path.isfile(cfg[k]):
continue
if k in auto:
print(f\"[\*] 自动检测到 {desc}: {auto[k]}\")
cfg[k] = auto[k]
changed = True
continue
if interactive:
cfg[k] = ask\_path(k, desc, optional=True)
changed = True
else:
cfg.pop(k, None)
if changed:
save\_cfg(cfg)
return cfg
---------- IMAPI2 打包可启动ISO (Windows自带组件,断网可用) ----------
def progid\_clsid(pid):
k = winreg.OpenKey(winreg.HKEY\_CLASSES\_ROOT, pid + r\"\CLSID\")
return winreg.QueryValueEx(k, \"\")[0]
def make\_bootable\_iso(stage\_dir, iso\_path):
import pythoncom, win32com.client
pythoncom.CoInitialize()
fsi = win32com.client.gencache.EnsureDispatch(progid\_clsid(\"IMAPI2FS.MsftFileSystemImage\"))
bo = win32com.client.gencache.EnsureDispatch(progid\_clsid(\"IMAPI2FS.BootOptions\"))
fsi.VolumeName = \"WIMBOOT\"
fsi.FileSystemsToCreate = 7 # ISO9660+Joliet+UDF; UDF必须加(CDBOOT走UDF找BOOTMGR)
fsi.FreeMediaBlocks = 2295104
fsi.Root.AddTree(stage\_dir, False)
bo.Manufacturer = \"Microsoft\"
bo.PlatformId = 0 # BIOS El Torito
bo.Emulation = 0
bootdata = open(BUILTIN[\"etfsboot\"], \"rb\").read()
stream = pythoncom.CreateStreamOnHGlobal(0, True)
stream.Write(bootdata)
stream.Seek(0, 0)
bo.AssignBootImage(stream)
fsi.BootImageOptions = bo
image = fsi.CreateResultImage()
st = image.ImageStream.QueryInterface(pythoncom.IID\_IStream)
n = 0
with open(iso\_path, \"wb\") as f:
while True:
b = st.Read(1024 \ 1024)
if not b:
break
f.write(b)
n += len(b)
if n % (64 \ 1024 \* 1024) == 0:
print(f\" 已写入 {n//1048576}MB...\", flush=True)
return n
def main():
args = sys.argv[1:]
flags = {a for a in args if a.startswith(\"--\")}
paths = [a for a in args if not a.startswith(\"--\")]
if not paths:
die(\"请把 WIM 文件拖到 WIM开机.bat 上,或: python wim\_boot.py
src = paths[0]
if not os.path.isfile(src):
die(\"找不到文件: \" + src)
stem = os.path.splitext(os.path.basename(src))[0]
with open(src, \"rb\") as fh:
if fh.read(8) != b\"MSWIM\x00\x00\x00\":
ext = os.path.splitext(src)[1].lower()
if ext.startswith(\".e0\") or ext in (\".ex01\",):
die(\"这是E01取证镜像,请使用整盘仿真工具(如 usbvm 启动盘仿真)\")
if ext in (\".dd\", \".raw\", \".img\"):
die(\"这是raw磁盘镜像,请使用整盘仿真工具\")
die(\"不是WIM文件(魔数不是MSWIM)\")
outdir = args[args.index(\"--out\") + 1] if \"--out\" in args else \
os.path.join(os.path.dirname(os.path.abspath(src)), stem + \"\_isovm\")
stage = os.path.join(outdir, \"iso\_root\")
os.makedirs(os.path.join(stage, \"boot\"), exist\_ok=True)
os.makedirs(os.path.join(stage, \"sources\"), exist\_ok=True)
print(\"=\" \* 56)
cfg = get\_paths(interactive=\"--no-ask\" not in flags)
use\_iso = (\"--builtin\" not in flags and cfg.get(\"sevenz\")
and cfg.get(\"shell\_iso\") and os.path.isfile(cfg[\"shell\_iso\"]))
print(\"[1/4] 准备引导材料 (bootmgr / bcd / boot.sdi)\")
if use\_iso:
print(\" 从 Win10 ISO 提取: \" + cfg[\"shell\_iso\"])
r = subprocess.run([cfg[\"sevenz\"], \"x\", \"-y\", \"-o\" + stage, cfg[\"shell\_iso\"],
\"bootmgr\", \"boot\"], capture\_output=True,
encoding=\"utf-8\", errors=\"ignore\")
if r.returncode != 0:
print(\" [!] 7z提取失败,退回Windows自带件: \" + r.stderr.strip()[:200])
use\_iso = False
if not use\_iso:
print(\" 使用 Windows 自带标准件 (C:\\Windows\\Boot)\")
shutil.copy(BUILTIN[\"bootmgr\"], os.path.join(stage, \"bootmgr\"))
shutil.copy(BUILTIN[\"bcd\"], os.path.join(stage, \"boot\", \"bcd\"))
shutil.copy(BUILTIN[\"boot.sdi\"], os.path.join(stage, \"boot\", \"boot.sdi\"))
fonts = os.path.join(stage, \"boot\", \"fonts\")
if not os.path.isdir(fonts):
try:
shutil.copytree(BUILTIN[\"fonts\"], fonts)
except Exception:
pass
print(\"[2/4] 放入 WIM -> sources\\boot.wim\")
dst\_wim = os.path.join(stage, \"sources\", \"boot.wim\")
if os.path.abspath(src) != os.path.abspath(dst\_wim):
shutil.copy(src, dst\_wim)
print(f\" {os.path.getsize(dst\_wim):,} 字节\")
print(\"[3/4] IMAPI2 打包可启动 ISO\")
iso\_path = os.path.join(outdir, stem + \"\_boot.iso\")
n = make\_bootable\_iso(stage, iso\_path)
print(f\" {iso\_path} ({n:,} 字节)\")
vmx\_path = os.path.join(outdir, stem + \"\_wim.vmx\")
with open(vmx\_path, \"w\", encoding=\"ascii\", newline=\"\r\
\") as w:
w.write(VMX\_TMPL.format(name=stem, iso=os.path.abspath(iso\_path)))
print(\" \", vmx\_path)
print(\"[4/4] 启动虚拟机 (光驱引导)\")
if \"--no-start\" in flags:
print(\" (按参数跳过) 双击 vmx 文件即可开机\")
return
vmrun = cfg.get(\"vmrun\")
if vmrun and os.path.isfile(vmrun):
r = subprocess.run([vmrun, \"-T\", \"ws\", \"start\", vmx\_path],
capture\_output=True, text=True,
encoding=\"utf-8\", errors=\"ignore\")
if r.returncode == 0:
print(\" 已启动! 黑屏1-2分钟属正常(WIM正在载入内存)\")
print(\" !! 若出现 'Press any key to boot from CD' 立刻按任意键!\")
return
print(\" [!] vmrun 失败,请手动双击 vmx 开机\")
else:
print(\" 未配置 vmrun,请手动双击 vmx 开机: \" + vmx\_path)
print(\"=\" \* 56)
if \\_name\\ == \"\\main\\_\":
main()
WIM开机.bat,注意要存成 UTF-8 编码
code
@echo off
chcp 65001 >nul
title WIM 开机 (WIM -> 可启动ISO -> VMware)
set PY=
where py >nul 2>nul && set PY=py -3
if not defined PY where python >nul 2>nul && set PY=python
if not defined PY (
echo [X] 未找到 Python,请先安装 Python 3 并勾选 Add to PATH
pause & exit /b
)
%PY% \"%~dp0wim\_boot.py\" %\*
echo.
pause
版权声明
本站仅做备份收录,仅供研究与教学参考之用。
读者将信息用于其他用途的,全部法律及连带责任由读者自行承担,本站不承担任何责任。









评论