-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSortWindowsISOs.py
executable file
·332 lines (278 loc) · 13.5 KB
/
SortWindowsISOs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File name : SortWindowsISOs.py
# Author : Podalirius (@podalirius_)
# Date created : 19 Jan 2022
import argparse
import hashlib
import os
import re
from rich.progress import Progress
import sys
import tempfile
import xml.etree.ElementTree as ET
def translate(display_name):
display_name = display_name.strip()
if display_name.startswith("Ознакомительная версия"):
a, b = display_name.replace("Ознакомительная версия", "Evaluation Version").split(' (',1)
display_name = a + " Evaluation Version (" + b
if display_name.startswith("Evaluación de "):
a, b = display_name.replace("Evaluación de ", "Evaluation Version").split(' (',1)
display_name = a + " Evaluation Version (" + b
if display_name.startswith("Version d’évaluation de "):
a, b = display_name.replace("Version d’évaluation de ", "Evaluation Version").split(' (',1)
display_name = a + " Evaluation Version (" + b
translate_table = {
# fr-fr
"(installation minimale)": "(Minimal Installation)",
# ru-ru
"Ознакомительная версия": "Evaluation Version",
"(полная установка)": "(Full Installation)",
"(установка основных серверных компонентов)": "(Server Core Installation)",
"Домашняя": "Home",
"Начальная": "Initial", # "Initial"
# zh-cn
"评估版": "Evaluation Version",
"(完全安装)": "(Full Installation)",
"(服务器核心安装)": "(Server Core Installation)",
"家庭版": "Home",
"教育版": "Education",
#
# "": "Evaluation Version",
"(installazione dei componenti core del server)": "(Server Core Installation)",
#
# "": " Evaluation Version",
"(Instalação Server Core)": "(Server Core Installation)",
# ja-jp
"(フル_インストール)": "(Full Installation)"
}
for original in sorted(translate_table.keys(), key=lambda x:len(x), reverse=True):
display_name = display_name.replace(original, " "+translate_table[original])
display_name = re.sub('[ ]+', ' ', display_name)
return display_name
def sha256sum(path_to_file):
# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536 # lets read stuff in 64kb chunks!
sha256 = hashlib.sha256()
with Progress() as progress:
task1 = progress.add_task("[green] | Hashing SHA256 ...", total=os.path.getsize(path_to_file))
with open(path_to_file, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if len(data) != 0:
progress.update(task1, advance=len(data))
sha256.update(data)
else:
break;
return sha256.hexdigest()
def parse_1_xml():
versions, version_string, display_name, languages_string = None, None, None, None
archs = {
"0": "x86",
"1": "arch=1",
"2": "arch=2",
"3": "arch=3",
"4": "arch=4",
"5": "arm",
"6": "ia64",
"7": "arch=7",
"8": "arch=8",
"9": "amd64",
"10": "arch=10",
"11": "arch=11",
"12": "arm64"
}
tree = ET.parse('[1].xml')
image = tree.findall('IMAGE')[0]
windows = image.find('WINDOWS')
name = image.find('NAME')
# Architecture
arch = windows.find('ARCH')
arch_string = None
if arch is not None:
if arch.text.strip() in archs.keys():
arch_string = archs[arch.text.strip()]
else:
print(" [\x1b[91merror\x1b[0m] Unknown ARCH %s." % arch.text.strip())
# Versions
versions = {c.tag.lower(): c.text for c in list(windows.find('VERSION'))}
version_string = "%s.%s.%s.%s" % (versions['major'], versions['minor'], versions['build'], versions['spbuild'])
# Languages
languages = [l.text for l in windows.findall('LANGUAGES/LANGUAGE')]
languages_string = ("multi" if len(languages) > 1 else languages[0].lower())
# Display name
display_name = image.find('DISPLAYNAME')
if display_name is not None:
display_name = display_name.text.strip()
else:
if versions['minor'] != "0":
display_name = "Windows %s.%s" % (versions['major'], versions['minor'])
else:
display_name = "Windows %s" % (versions['major'])
display_name = display_name.replace(" ", " ")
return (arch_string, versions, version_string, display_name, languages_string)
def check_windows_version(isofile, verbose=False):
arch_string, versions, version_string, display_name, languages_string = None, None, None, None, None
# Mount iso read-only
oldpwd = os.getcwd()
iso_mount_dir = tempfile.TemporaryDirectory()
work_dir = tempfile.TemporaryDirectory()
if verbose:
print(" [>] Work dir is %s/" % work_dir.name)
if verbose:
print(" [>] Mounting ISO to %s/" % iso_mount_dir.name)
print(" | mount -o ro '%s' %s/ 2>&1" % (isofile, iso_mount_dir.name))
os.system("mount -o ro '%s' %s/ 2>&1" % (isofile, iso_mount_dir.name))
else:
os.popen("mount -o ro '%s' %s/ 2>&1" % (isofile, iso_mount_dir.name)).read()
os.chdir(iso_mount_dir.name)
# Parse files in the ISO to get the Windows build
os.chdir(work_dir.name)
try:
found = False
if os.path.isfile(iso_mount_dir.name + "/sources/install.wim") and not found:
if verbose:
print(" [>] Parsing Windows build number from install.wim ...")
if verbose:
print(" [>] Extracting install.wim '[1].xml' file ...")
os.popen("7z e '%s/sources/install.wim' '[1].xml' -aoa 2>&1" % iso_mount_dir.name).read()
else:
os.popen("7z e '%s/sources/install.wim' '[1].xml' -aoa 2>&1" % iso_mount_dir.name).read()
if verbose:
print(" [>] Parsing install.wim '[1].xml' file ...")
if os.path.exists('[1].xml'):
(arch_string, versions, version_string, display_name, languages_string) = parse_1_xml()
found = True
else:
if verbose:
print(" [\x1b[91merror\x1b[0m] File '[1].xml' does not exist.")
if os.path.isfile(iso_mount_dir.name + "/sources/boot.wim") and not found:
if verbose:
print(" [>] Parsing Windows build number from boot.wim ...")
if verbose:
print(" [>] Extracting boot.wim '[1].xml' file ...")
os.popen("7z e '%s/sources/boot.wim' '[1].xml' -aoa 2>&1" % iso_mount_dir.name).read()
else:
os.popen("7z e '%s/sources/boot.wim' '[1].xml' -aoa 2>&1" % iso_mount_dir.name).read()
if verbose:
print(" [>] Parsing boot.wim '[1].xml' file ...")
if os.path.exists('[1].xml'):
(arch_string, versions, version_string, display_name, languages_string) = parse_1_xml()
found = True
else:
if verbose:
print(" [\x1b[91merror\x1b[0m] File '[1].xml' does not exist.")
except Exception as e:
print(" [\x1b[91merror\x1b[0m] %s" % e)
arch_string, versions, version_string, display_name, languages_string = None, None, None, None, None
os.chdir(oldpwd)
# Unmount ISO and remove temporary directory
if verbose:
print(" [>] Unmounting ISO from %s ..." % iso_mount_dir.name)
os.system("umount %s 2>&1" % iso_mount_dir.name)
else:
os.popen("umount %s 2>&1" % iso_mount_dir.name).read()
work_dir.cleanup()
iso_mount_dir.cleanup()
return (arch_string, versions, version_string, display_name, languages_string)
def archive_iso(archive_dir, path_to_iso, versions, version_string, arch_string, display_name, languages_string, verbose=False):
os_type = ""
display_name = display_name.strip()
m = re.match('^(Windows [0-9]+(\.[0-9]+)?)', display_name)
if m is not None:
os_type = m.group(0)
m = re.match('^(Windows Server [0-9]+)', display_name)
if m is not None:
os_type = m.group(0)
if os_type == "":
os_type = display_name
display_name = translate(display_name)
h = sha256sum(path_to_iso)
# basedir = "%s/%s/%s - %s/%s/%s/%s/%s/" % (archive_dir, os_type, version_string, display_name, languages_string, arch_string, versions['branch'], h)
isoname = display_name.replace(' ', '_')
if "branch" in versions.keys():
basedir = "%s/%s/%s - %s/%s/%s/%s/%s/" % (archive_dir, os_type, version_string, display_name, languages_string, arch_string, versions['branch'], h)
isoname = "%s.%s.%s.%s.%s.iso" % (version_string, isoname, arch_string, versions['branch'], languages_string)
else:
basedir = "%s/%s/%s - %s/%s/%s/%s/" % (archive_dir, os_type, version_string, display_name, languages_string, arch_string, h)
isoname = "%s.%s.%s.%s.iso" % (version_string, isoname, arch_string, languages_string)
if not os.path.exists(basedir):
os.makedirs(basedir, exist_ok=True)
print(" [>] Archiving to %s%s" % (basedir, isoname))
os.rename(iso, "%s/%s" % (basedir, isoname))
def print_windows_version(versions, arch_string, display_name, languages_string, no_colors=False):
_os, _arch, _build, _lang, _branch = "", "", "", "", ""
# Windows version
if no_colors:
_os = "%s" % display_name
else:
_os = "\x1b[92m%s\x1b[0m" % display_name
# Arch
if arch_string is not None:
if no_colors:
_arch = "(arch:%s)" % arch_string
else:
_arch = "(\x1b[94march\x1b[0m:\x1b[96m%s\x1b[0m)" % arch_string
# Build
if no_colors:
_build = "(build:%s.%s)" % (versions['build'], versions['spbuild'])
else:
_build = "(\x1b[94mbuild\x1b[0m:\x1b[96m%s.%s\x1b[0m)" % (versions['build'], versions['spbuild'])
# Branch
if "branch" in versions.keys():
if no_colors:
_branch = "(branch:%s)" % (versions['branch'])
else:
_branch = "(\x1b[94mbranch\x1b[0m:\x1b[96m%s\x1b[0m)" % (versions['branch'])
# Languages
if no_colors:
_lang = "(lang:%s)" % languages_string
else:
_lang = "(\x1b[94mlang\x1b[0m:\x1b[96m%s\x1b[0m)" % languages_string
print(" [+] %s %s %s %s %s" % (_os, _arch, _build, _branch, _lang))
def parseArgs():
parser = argparse.ArgumentParser(description="Extract Windows Build number from ISO files. v1.1")
group_iso_source = parser.add_mutually_exclusive_group(required=True)
group_iso_source.add_argument("-i", "--iso", default=None, help='Path to iso file.')
group_iso_source.add_argument("-d", "--iso-dir", default=None, help='Directory containing multiple ISOs to parse.')
parser.add_argument("-a", "--archive-dir", default=None, help='Archive dir. (default: False)')
parser.add_argument("-v", "--verbose", default=False, action="store_true", help='Verbose mode. (default: False)')
parser.add_argument("--no-colors", default=False, action="store_true", help='No colors mode. (default: False)')
return parser.parse_args()
if __name__ == '__main__':
options = parseArgs()
if options.iso is not None:
if not os.path.isfile(options.iso):
print("[!] Cannot access ISO file. Wrong path or bad permissions maybe ?")
sys.exit(-1)
print("[iso] %s " % options.iso)
try:
arch_string, versions, version_string, display_name, languages_string = check_windows_version(options.iso, verbose=options.verbose)
if versions is not None and version_string is not None and display_name is not None and languages_string is not None:
print_windows_version(versions, arch_string, display_name, languages_string, no_colors=options.no_colors)
if options.archive_dir is not None:
archive_iso(options.archive_dir, options.iso, versions, version_string, arch_string, display_name, languages_string, verbose=options.verbose)
except Exception as e:
print(" [\x1b[91merror\x1b[0m] %s" % e)
elif options.iso_dir is not None:
if not os.path.isdir(options.iso_dir):
print("[!] Cannot access ISO directory. Wrong path or bad permissions maybe ?")
sys.exit(-1)
iso_files = []
if options.verbose:
print("[debug] Searching for iso files ...")
for root, dirs, files in os.walk(options.iso_dir):
for filename in files:
if filename.lower().endswith(".iso"):
name = os.path.join(root, filename)
iso_files.append(name)
for iso in iso_files:
print("[iso] %s " % iso)
try:
arch_string, versions, version_string, display_name, languages_string = check_windows_version(iso, verbose=options.verbose)
if versions is not None and version_string is not None and display_name is not None and languages_string is not None:
print_windows_version(versions, arch_string, display_name, languages_string, no_colors=options.no_colors)
if options.archive_dir is not None:
archive_iso(options.archive_dir, iso, versions, version_string, arch_string, display_name, languages_string, verbose=options.verbose)
except Exception as e:
print(" [\x1b[91merror\x1b[0m] %s" % e)