Skip to content

Instantly share code, notes, and snippets.

@tomazas
Last active July 31, 2024 12:55
Show Gist options
  • Select an option

  • Save tomazas/c542035a073017c1eb86d9eafe06c58f to your computer and use it in GitHub Desktop.

Select an option

Save tomazas/c542035a073017c1eb86d9eafe06c58f to your computer and use it in GitHub Desktop.
Java JAR compiler version checker
# script detects Java compiler version for a provided input JAR filename
# usage: python script <input.jar>
import zipfile
import sys
import os
import shutil
import struct
def check_jar(filename):
p = "temp/"+filename+"_dir"
try: shutil.rmtree(p)
except: pass
try: os.mkdir(p)
except: pass
print("checking",filename)
with zipfile.ZipFile(filename, 'r') as zip_ref:
zip_ref.extractall(p)
ver = {
68:"Java SE 24",
67:"Java SE 23",
66:"Java SE 22",
65:"Java SE 21",
64:"Java SE 20",
63:"Java SE 19",
62:"Java SE 18",
61:"Java SE 17",
60:"Java SE 16",
59:"Java SE 15",
58:"Java SE 14",
57:"Java SE 13",
56:"Java SE 12",
55:"Java SE 11",
54:"Java SE 10",
53:"Java SE 9",
52:"Java SE 8",
51:"Java SE 7",
50:"Java SE 6.0",
49:"Java SE 5.0",
48:"JDK 1.4",
47:"JDK 1.3",
46:"JDK 1.2",
45:"JDK 1.1"
}
highest = 0
for root, dirs, files in os.walk(p):
end = False
for file in files:
abspath = root + os.sep + file
if ".class" in abspath:
with open(abspath, "rb") as fp:
cafebabe, = struct.unpack(">I",fp.read(4))
if cafebabe != 0xCAFEBABE:
print("wrong header bytecode version: %d"%(cafebabe))
else:
minor, = struct.unpack(">H", fp.read(2))
major, = struct.unpack(">H", fp.read(2))
s = "unknown"
if major in ver:
s = ver[major]
elif major > max(ver.keys()):
s = ver[max(ver.keys())] + "+"
print("minor: %d, major: %d, version: %s"%(minor, major, s))
end = True
break
if end: break
# cleanup
try:
shutil.rmtree(p)
except: pass
if __name__ == "__main__":
if len(sys.argv) < 2:
print("usage: python %s <jarfile>"%(sys.argv[0]))
sys.exit(1)
check_jar(sys.argv[1])
print("done.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment