代码原文地址:
https://www.snip2code.com/Snippet/144008/Read-the-PE-Timestamp-from-a-Windows-Exe
https://gist.github.com/03152ba1a148d9475e81
直接上代码吧,引用过来以防链接失效:
#! /usr/bin/env python2.7
#
# Author: Pat Litke (C) 2014
#
# This code is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Baku. If not, see <http://www.gnu.org/licenses/>.
#
# Description:
# Quick and dirty module to read a binary file, look at the DOS header for the PE offset
# Seek to the PE offset, read the third DWORD in, unpack it, and return either EPOCH or GMTIMEs
#
# Returns 1 if the file doesn't havea a DOS header
# Returns 2 if file couldn't be read
# Returns the data in epoch or formatted otherwise from struct import unpack
from binascii import hexlify
from time import gmtime, strftime def getEpoch(filePath, epoch = True): # Open the file in Binary mode
try:
handle = open(filePath, 'rb')
if hexlify(handle.read(2)) != hexlify(u'MZ'):
handle.close()
return 1
except:
return 2 # Get PE offset (@60, DWORD) from DOS header
# It's little-endian so we have to flip it
# We also need the HEX representation which is an INT value
handle.seek(60, 0)
offset = handle.read(4)
offset = hexlify(offset[::-1])
offset = int(offset, 16) # Seek to PE header and read second DWORD
handle.seek(offset+8, 0)
dword = handle.read(4)
handle.close()
t = unpack(">L", dword[::-1])[0] if epoch:
return t
else:
return strftime('%Y-%m-%d %H:%M:%S', gmtime(float(t))) def getUTC(filePath):
return getEpoch(filepath, False) def getBoth(filePath):
return [getEpoch(filepath), getEpoch(filepath, False)]
如果想修改这个时间戳,按照上述规则,pack后写入即可,另外其中53行那句有些麻烦,其实这么写就可以了:t = unpack("<L", dword)[0] ,即按照小端直接解码即可。
更新:
更强大的修改PE文件时间戳的方式如下,而且支持PE文件与pdb一切修改,还可以顺道修改guid:
https://github.com/google/syzygy/tree/master/syzygy/zap_timestamp
这是谷歌syzygy工具链中的一个小公举(工具 O(∩_∩)O~)。
syzygy也是个好东西,可以改善软件的启动速度,体积较大的软件,本身启动已经没有什么优化空间时,可以考虑使用syzygy来提高加载速度