使用"pefile.py"获取文件(.exe)版本
3 个回答
0
Windows程序的版本号是存储在程序文件的资源部分,而不是在PE格式的头部。我对pefile.py
不太熟悉,所以不清楚它是否也直接处理资源部分。如果没有的话,你可以在这篇MSDN文章中找到你需要的信息。
2
假设你说的“可执行文件版本”是指在Windows系统上,查看文件属性时“详细信息”标签下的“文件版本”,你可以使用pywin32这个包来获取这个信息,命令大概是这样的:
>>> import win32api as w
>>> hex(w.GetFileVersionInfo('c:/windows/regedit.exe', '\\')['FileVersionMS'])
'0x60000'
>>> hex(w.GetFileVersionInfo('c:/windows/regedit.exe', '\\')['FileVersionLS'])
'0x17714650'
需要注意的是,0x60000代表的是主版本和次版本号(6.0),而0x17714650则是接下来的两个数字。如果把它分成两个部分(0x1771和0x4650,或者在十进制中是6001和18000),这些数字对应于我电脑上的版本信息,regedit显示的版本是6.0.6001.18000。
3
这里有一个完整的示例脚本,可以实现你想要的功能:
import sys
def main(pename):
from pefile import PE
pe = PE(pename)
if not 'VS_FIXEDFILEINFO' in pe.__dict__:
print "ERROR: Oops, %s has no version info. Can't continue." % (pename)
return
if not pe.VS_FIXEDFILEINFO:
print "ERROR: VS_FIXEDFILEINFO field not set for %s. Can't continue." % (pename)
return
verinfo = pe.VS_FIXEDFILEINFO
filever = (verinfo.FileVersionMS >> 16, verinfo.FileVersionMS & 0xFFFF, verinfo.FileVersionLS >> 16, verinfo.FileVersionLS & 0xFFFF)
prodver = (verinfo.ProductVersionMS >> 16, verinfo.ProductVersionMS & 0xFFFF, verinfo.ProductVersionLS >> 16, verinfo.ProductVersionLS & 0xFFFF)
print "Product version: %d.%d.%d.%d" % prodver
print "File version: %d.%d.%d.%d" % filever
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.stderr.write("ERROR:\n\tSyntax: verinfo <pefile>\n")
sys.exit(1)
sys.exit(main(sys.argv[1]))
关键的代码行是:
verinfo = pe.VS_FIXEDFILEINFO
filever = (verinfo.FileVersionMS >> 16, verinfo.FileVersionMS & 0xFFFF, verinfo.FileVersionLS >> 16, verinfo.FileVersionLS & 0xFFFF)
prodver = (verinfo.ProductVersionMS >> 16, verinfo.ProductVersionMS & 0xFFFF, verinfo.ProductVersionLS >> 16, verinfo.ProductVersionLS & 0xFFFF)
所有这些操作都是在确认这些属性里有有用的信息之后才进行的。