python 解析.lnk文件,获取源文件地址的简单方法

http://stackoverflow.com/questions/397125/reading-the-target-of-a-lnk-file-in-python



点击(此处)折叠或打开

  1. import struct

  2. target = ''

  3. try:
  4.     with open(path, 'rb') as stream:
  5.         content = stream.read()

  6.         # skip first 20 bytes (HeaderSize and LinkCLSID)
  7.         # read the LinkFlags structure (4 bytes)
  8.         lflags = struct.unpack('I', content[0x14:0x18])[0]
  9.         position = 0x18

  10.         # if the HasLinkTargetIDList bit is set then skip the stored IDList
  11.         # structure and header
  12.         if (lflags & 0x01) == 1:
  13.             position = struct.unpack('H', content[0x4C:0x4E])[0] + 0x4E

  14.         last_pos = position
  15.         position += 0x04

  16.         # get how long the file information is (LinkInfoSize)
  17.         length = struct.unpack('I', content[last_pos:position])[0]

  18.         # skip 12 bytes (LinkInfoHeaderSize, LinkInfoFlags, and VolumeIDOffset)
  19.         position += 0x0C

  20.         # go to the LocalBasePath position
  21.         lbpos = struct.unpack('I', content[position:position+0x04])[0]
  22.         position = last_pos + lbpos

  23.         # read the string at the given position of the determined length
  24.         size= (length + last_pos) - position - 0x02
  25.         temp = struct.unpack('c' * size, content[position:position+size])
  26.         target = ''.join([chr(ord(a)) for a in temp])
  27. except:
  28.     # could not read the file
  29.     pass

  30. return target

可以正确获取Program Files下的文件路径

获取desktop下文件的时候会拆分为 用户目录   空格   相对目录

其他诸如或去扫雷.lnk估计也不行,但是大致可用了

顺别贴一个lnk文件结构
https://ithreats.files.wordpress.com/2009/05/lnk_the_windows_shortcut_file_format.pdf

看了下好像不太对得上, 不知道是不是我数错了偏移量,反正也懒得纠结了

09-11 07:29