1、你曾经去过哪里?——在注册表中分析无线访问热点:

以管理员权限开启cmd,输入如下命令来列出每个网络显示出profile Guid对网络的描述、网络名和网关的MAC地址:

reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\
CurrentVersion\NetworkList\Signatures\Unmanaged" /s

使用WinReg读取Windows注册表中的内容:

这里需要用到Python的_winreg库,在Windows版是默认安装好的。

连上注册表后,使用OpenKey()函数打开相关的键,在循环中依次分析该键下存储的所有网络network profile,其中FirstNetwork网络名和DefaultGateway默认网关的Mac地址的键值打印出来。

#!/usr/bin/python
#coding=utf-8
from _winreg import *# 将REG_BINARY值转换成一个实际的Mac地址
def val2addr(val):addr = ""for ch in val:addr += ("%02x " % ord(ch))addr = addr.strip(" ").replace(" ", ":")[0:17]return addr# 打印网络相关信息
def printNets():net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged"key = OpenKey(HKEY_LOCAL_MACHINE, net)print "\n[*]Networks You have Joined."for i in range(100):try:guid = EnumKey(key, i)netKey = OpenKey(key, str(guid))(n, addr, t) = EnumValue(netKey, 5)(n, name, t) = EnumValue(netKey, 4)macAddr = val2addr(addr)netName = nameprint '[+] ' + netName + '  ' + macAddrCloseKey(netKey)except:breakdef main():printNets()if __name__ == '__main__':main()

运行结果:

注意一点的是,是需要管理员权限开启cmd来执行脚本才行得通。

使用Mechanize把Mac地址传给Wigle:

此处增加了对Wigle网站的访问并将Mac地址传递给Wigle来获取经纬度等物理地址信息。

#!/usr/bin/python
#coding=utf-8
from _winreg import *
import mechanize
import urllib
import re
import urlparse
import os
import optparse# 将REG_BINARY值转换成一个实际的Mac地址
def val2addr(val):addr = ""for ch in val:addr += ("%02x " % ord(ch))addr = addr.strip(" ").replace(" ", ":")[0:17]return addr# 打印网络相关信息
def printNets(username, password):net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged"key = OpenKey(HKEY_LOCAL_MACHINE, net)print "\n[*]Networks You have Joined."for i in range(100):try:guid = EnumKey(key, i)netKey = OpenKey(key, str(guid))(n, addr, t) = EnumValue(netKey, 5)(n, name, t) = EnumValue(netKey, 4)macAddr = val2addr(addr)netName = nameprint '[+] ' + netName + '  ' + macAddrwiglePrint(username, password, macAddr)CloseKey(netKey)except:break# 通过wigle查找Mac地址对应的经纬度
def wiglePrint(username, password, netid):browser = mechanize.Browser()browser.open('http://wigle.net')reqData = urllib.urlencode({'credential_0': username, 'credential_1': password})browser.open('https://wigle.net/gps/gps/main/login', reqData)params = {}params['netid'] = netidreqParams = urllib.urlencode(params)respURL = 'http://wigle.net/gps/gps/main/confirmquery/'resp = browser.open(respURL, reqParams).read()mapLat = 'N/A'mapLon = 'N/A'rLat = re.findall(r'maplat=.*\&', resp)if rLat:mapLat = rLat[0].split('&')[0].split('=')[1]rLon = re.findall(r'maplon=.*\&', resp)if rLon:mapLon = rLon[0].splitprint '[-] Lat: ' + mapLat + ', Lon: ' + mapLondef main():parser = optparse.OptionParser('usage %prog ' + '-u <wigle username> -p <wigle password>')parser.add_option('-u', dest='username', type='string', help='specify wigle password')parser.add_option('-p', dest='password', type='string', help='specify wigle username')(options, args) = parser.parse_args()username = options.usernamepassword = options.passwordif username == None or password == None:print parser.usageexit(0)else:printNets(username, password)if __name__ == '__main__':main()

运行结果:

看到只显示一条信息,且没有其物理地址相关信息,存在问题。

调试查看原因:

发现是网站的robots.txt文件禁止对该页面的请求因而无法访问。

2、用Python恢复被删入回收站中的内容:

使用OS模块寻找被删除的文件/文件夹:

Windows系统中的回收站是一个专门用来存放被删除文件的特殊文件夹。

子目录中的字符串表示的是用户的SID,对应机器里一个唯一的用户账户。

寻找被删除的文件/文件夹的函数:

#!/usr/bin/python
#coding=utf-8
import os# 逐一测试回收站的目录是否存在,并返回第一个找到的回收站目录
def returnDir():dirs=['C:\\Recycler\\', 'C:\\Recycled\\', 'C:\\$Recycle.Bin\\']for recycleDir in dirs:if os.path.isdir(recycleDir):return recycleDirreturn None

用Python把SID和用户名关联起来:

可以使用Windows注册表把SID转换成一个准确的用户名。

以管理员权限运行cmd并输入命令:

reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-2595130515-3345905091-1839164762-1000" /s

代码如下:

#!/usr/bin/python
#coding=utf-8
import os
import optparse
from _winreg import *# 逐一测试回收站的目录是否存在,并返回第一个找到的回收站目录
def returnDir():dirs=['C:\\Recycler\\', 'C:\\Recycled\\', 'C:\\$Recycle.Bin\\']for recycleDir in dirs:if os.path.isdir(recycleDir):return recycleDirreturn None# 操作注册表来获取相应目录属主的用户名
def sid2user(sid):try:key = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + '\\' + sid)(value, type) = QueryValueEx(key, 'ProfileImagePath')user = value.split('\\')[-1]return userexcept:return siddef findRecycled(recycleDir):dirList = os.listdir(recycleDir)for sid in dirList:files = os.listdir(recycleDir + sid)user = sid2user(sid)print '\n[*] Listing Files For User: ' + str(user)for file in files:print '[+] Found File: ' + str(file)def main():recycledDir = returnDir()findRecycled(recycledDir)if __name__ == '__main__':main()

回收站的内容:

运行结果:

3、元数据:

使用PyPDF解析PDF文件中的元数据:

pyPdf是管理PDF文档的第三方Python库,在Kali中是已经默认安装了的就不需要再去下载安装。

#!/usr/bin/python
#coding=utf-8
import pyPdf
import optparse
from pyPdf import PdfFileReader# 使用getDocumentInfo()函数提取PDF文档所有的元数据
def printMeta(fileName):pdfFile = PdfFileReader(file(fileName, 'rb'))docInfo = pdfFile.getDocumentInfo()print "[*] PDF MeataData For: " + str(fileName)for meraItem in docInfo:print "[+] " + meraItem + ": " + docInfo[meraItem]def main():parser = optparse.OptionParser("[*]Usage: python pdfread.py -F <PDF file name>")parser.add_option('-F', dest='fileName', type='string', help='specify PDF file name')(options, args) = parser.parse_args()fileName = options.fileNameif fileName == None:print parser.usageexit(0)else:printMeta(fileName)if __name__ == '__main__':main()

解析一个PDF文件的运行结果:

理解Exif元数据:

Exif,即exchange image file format交换图像文件格式,定义了如何存储图像和音频文件的标准。

用BeautifulSoup下载图片:

import urllib2
from bs4 import BeautifulSoup as BS
from os.path import basename
from urlparse import urlsplit# 通过BeautifulSoup查找URL中所有的img标签
def findImages(url):print '[+] Finding images on ' + urlurlContent = urllib2.urlopen(url).read()soup = BS(urlContent, 'lxml')imgTags = soup.findAll('img')return imgTags# 通过img标签的src属性的值来获取图片URL下载图片
def downloadImage(imgTag):try:print '[+] Dowloading image...'imgSrc = imgTag['src']imgContent = urllib2.urlopen(imgSrc).read()imgFileName = basename(urlsplit(imgSrc)[2])imgFile = open(imgFileName, 'wb')imgFile.write(imgContent)imgFile.close()return imgFileNameexcept:return ' '

用Python的图像处理库读取图片中的Exif元数据:

这里使用到Python的图形处理库PIL,在Kali中默认安装了。

这里查看下载图片的元数据中是否含有Exif标签“GPSInfo”,若存在则输出存在信息。

#!/usr/bin/python
#coding=utf-8
import optparse
from PIL import Image
from PIL.ExifTags import TAGS
import urllib2
from bs4 import BeautifulSoup as BS
from os.path import basename
from urlparse import urlsplit# 通过BeautifulSoup查找URL中所有的img标签
def findImages(url):print '[+] Finding images on ' + urlurlContent = urllib2.urlopen(url).read()soup = BS(urlContent, 'lxml')imgTags = soup.findAll('img')return imgTags# 通过img标签的src属性的值来获取图片URL下载图片
def downloadImage(imgTag):try:print '[+] Dowloading image...'imgSrc = imgTag['src']imgContent = urllib2.urlopen(imgSrc).read()imgFileName = basename(urlsplit(imgSrc)[2])imgFile = open(imgFileName, 'wb')imgFile.write(imgContent)imgFile.close()return imgFileNameexcept:return ' '# 获取图像文件的元数据,并寻找是否存在Exif标签“GPSInfo”
def testForExif(imgFileName):try:exifData = {}imgFile = Image.open(imgFileName)info = imgFile._getexif()if info:for (tag, value) in info.items():decoded = TAGS.get(tag, tag)exifData[decoded] = valueexifGPS = exifData['GPSInfo']if exifGPS:print '[*] ' + imgFileName + ' contains GPS MetaData'except:passdef main():parser = optparse.OptionParser('[*]Usage: python Exif.py -u <target url>')parser.add_option('-u', dest='url', type='string', help='specify url address')(options, args) = parser.parse_args()url = options.urlif url == None:print parser.usageexit(0)else:imgTags = findImages(url)for imgTag in imgTags:imgFileName = downloadImage(imgTag)testForExif(imgFileName)if __name__ == '__main__':main()

书中样例的网址为https://www.flickr.com/photos/dvids/4999001925/sizes/o

运行结果:

4、用Python分析应用程序的使用记录:

使用Python和SQLite3自动查询Skype的数据库:

这里没有下载Skype聊天程序,感兴趣的自己下载测试即可。

#!/usr/bin/python
#coding=utf-8
import sqlite3
import optparse
import os# 连接main.db数据库,申请游标,执行SQL语句并返回结果
def printProfile(skypeDB):conn = sqlite3.connect(skypeDB)c = conn.cursor()c.execute("SELECT fullname, skypename, city, country, datetime(profile_timestamp,'unixepoch') FROM Accounts;")for row in c:print '[*] -- Found Account --'print '[+] User           : '+str(row[0])print '[+] Skype Username : '+str(row[1])print '[+] Location       : '+str(row[2])+','+str(row[3])print '[+] Profile Date   : '+str(row[4])# 获取联系人的相关信息
def printContacts(skypeDB):conn = sqlite3.connect(skypeDB)c = conn.cursor()c.execute("SELECT displayname, skypename, city, country, phone_mobile, birthday FROM Contacts;")for row in c:print '\n[*] -- Found Contact --'print '[+] User           : ' + str(row[0])print '[+] Skype Username : ' + str(row[1])if str(row[2]) != '' and str(row[2]) != 'None':print '[+] Location       : ' + str(row[2]) + ',' + str(row[3])if str(row[4]) != 'None':print '[+] Mobile Number  : ' + str(row[4])if str(row[5]) != 'None':print '[+] Birthday       : ' + str(row[5])def printCallLog(skypeDB):conn = sqlite3.connect(skypeDB)c = conn.cursor()c.execute("SELECT datetime(begin_timestamp,'unixepoch'), identity FROM calls, conversations WHERE calls.conv_dbid = conversations.id;")print '\n[*] -- Found Calls --'for row in c:print '[+] Time: ' + str(row[0]) + ' | Partner: ' + str(row[1])def printMessages(skypeDB):conn = sqlite3.connect(skypeDB)c = conn.cursor()c.execute("SELECT datetime(timestamp,'unixepoch'), dialog_partner, author, body_xml FROM Messages;")print '\n[*] -- Found Messages --'for row in c:try:if 'partlist' not in str(row[3]):if str(row[1]) != str(row[2]):msgDirection = 'To ' + str(row[1]) + ': 'else:msgDirection = 'From ' + str(row[2]) + ' : 'print 'Time: ' + str(row[0]) + ' ' + msgDirection + str(row[3])except:passdef main():parser = optparse.OptionParser("[*]Usage: python skype.py -p <skype profile path> ")parser.add_option('-p', dest='pathName', type='string', help='specify skype profile path')(options, args) = parser.parse_args()pathName = options.pathNameif pathName == None:print parser.usageexit(0)elif os.path.isdir(pathName) == False:print '[!] Path Does Not Exist: ' + pathNameexit(0)else:skypeDB = os.path.join(pathName, 'main.db')if os.path.isfile(skypeDB):printProfile(skypeDB)printContacts(skypeDB)printCallLog(skypeDB)printMessages(skypeDB)else:print '[!] Skype Database ' + 'does not exist: ' + skpeDBif __name__ == '__main__':main()

这里直接用该书作者提供的数据包进行测试:

用Python解析火狐浏览器的SQLite3数据库:

在Windows7以上的系统中,Firefox的sqlite文件保存在类似如下的目录中:C:\Users\win7\AppData\Roaming\Mozilla\Firefox\Profiles\8eogekr4.default

主要关注这几个文件:cookie.sqlite、places.sqlite、downloads.sqlite

然而在最近新的几个版本的Firefox中已经没有downloads.sqlite这个文件了,具体换成哪个文件可以自己去研究查看一下即可。

#!/usr/bin/python
#coding=utf-8
import re
import optparse
import os
import sqlite3# 解析打印downloads.sqlite文件的内容,输出浏览器下载的相关信息
def printDownloads(downloadDB):conn = sqlite3.connect(downloadDB)c = conn.cursor()c.execute('SELECT name, source, datetime(endTime/1000000, \'unixepoch\') FROM moz_downloads;')print '\n[*] --- Files Downloaded --- 'for row in c:print '[+] File: ' + str(row[0]) + ' from source: ' + str(row[1]) + ' at: ' + str(row[2])# 解析打印cookies.sqlite文件的内容,输出cookie相关信息
def printCookies(cookiesDB):try:conn = sqlite3.connect(cookiesDB)c = conn.cursor()c.execute('SELECT host, name, value FROM moz_cookies')print '\n[*] -- Found Cookies --'for row in c:host = str(row[0])name = str(row[1])value = str(row[2])print '[+] Host: ' + host + ', Cookie: ' + name + ', Value: ' + valueexcept Exception, e:if 'encrypted' in str(e):print '\n[*] Error reading your cookies database.'print '[*] Upgrade your Python-Sqlite3 Library'# 解析打印places.sqlite文件的内容,输出历史记录
def printHistory(placesDB):try:conn = sqlite3.connect(placesDB)c = conn.cursor()c.execute("select url, datetime(visit_date/1000000, 'unixepoch') from moz_places, moz_historyvisits where visit_count > 0 and moz_places.id==moz_historyvisits.place_id;")print '\n[*] -- Found History --'for row in c:url = str(row[0])date = str(row[1])print '[+] ' + date + ' - Visited: ' + urlexcept Exception, e:if 'encrypted' in str(e):print '\n[*] Error reading your places database.'print '[*] Upgrade your Python-Sqlite3 Library'exit(0)# 解析打印places.sqlite文件的内容,输出百度的搜索记录
def printBaidu(placesDB):conn = sqlite3.connect(placesDB)c = conn.cursor()c.execute("select url, datetime(visit_date/1000000, 'unixepoch') from moz_places, moz_historyvisits where visit_count > 0 and moz_places.id==moz_historyvisits.place_id;")print '\n[*] -- Found Baidu --'for row in c:url = str(row[0])date = str(row[1])if 'baidu' in url.lower():r = re.findall(r'wd=.*?\&', url)if r:search=r[0].split('&')[0]search=search.replace('wd=', '').replace('+', ' ')print '[+] '+date+' - Searched For: ' + searchdef main():parser = optparse.OptionParser("[*]Usage: firefoxParse.py -p <firefox profile path> ")parser.add_option('-p', dest='pathName', type='string', help='specify skype profile path')(options, args) = parser.parse_args()pathName = options.pathNameif pathName == None:print parser.usageexit(0)elif os.path.isdir(pathName) == False:print '[!] Path Does Not Exist: ' + pathNameexit(0)else:downloadDB = os.path.join(pathName, 'downloads.sqlite')if os.path.isfile(downloadDB):printDownloads(downloadDB)else:print '[!] Downloads Db does not exist: '+downloadDBcookiesDB = os.path.join(pathName, 'cookies.sqlite')if os.path.isfile(cookiesDB):passprintCookies(cookiesDB)else:print '[!] Cookies Db does not exist:' + cookiesDBplacesDB = os.path.join(pathName, 'places.sqlite')if os.path.isfile(placesDB):printHistory(placesDB)printBaidu(placesDB)else:print '[!] PlacesDb does not exist: ' + placesDBif __name__ == '__main__':main()

上述脚本对原本的脚本进行了一点修改,修改的地方是对查找Google搜索记录部分改为对查找Baidu搜索记录,这样在国内更普遍使用~

运行结果:

除了downloads.sqlite文件找不到外,其他的文件都正常解析内容了。在查找搜索内容部分,若为中文等字符则显示为编码的形式。

5、用Python调查iTunes的手机备份:

自己测试一下吧 。

#!/usr/bin/python
#coding=utf-8
import os
import sqlite3
import optparsedef isMessageTable(iphoneDB):try:conn = sqlite3.connect(iphoneDB)c = conn.cursor()c.execute('SELECT tbl_name FROM sqlite_master WHERE type==\"table\";')for row in c:if 'message' in str(row):return Trueexcept:return Falsedef printMessage(msgDB):try:conn = sqlite3.connect(msgDB)c = conn.cursor()c.execute('select datetime(date,\'unixepoch\'), address, text from message WHERE address>0;')for row in c:date = str(row[0])addr = str(row[1])text = row[2]print '\n[+] Date: '+date+', Addr: '+addr + ' Message: ' + textexcept:passdef main():parser = optparse.OptionParser("[*]Usage: python iphoneParse.py -p <iPhone Backup Directory> ")parser.add_option('-p', dest='pathName', type='string',help='specify skype profile path')(options, args) = parser.parse_args()pathName = options.pathNameif pathName == None:print parser.usageexit(0)else:dirList = os.listdir(pathName)for fileName in dirList:iphoneDB = os.path.join(pathName, fileName)if isMessageTable(iphoneDB):try:print '\n[*] --- Found Messages ---'printMessage(iphoneDB)except:passif __name__ == '__main__':main()

转载于:https://www.cnblogs.com/LyShark/p/9101159.html

《Python绝技:运用Python成为顶级黑客》 用Python进行取证调查相关推荐

  1. python expect模块_成为顶级黑客--python绝技 阅读笔记(五)

    Python构建一个SSH僵尸网络 可以看一下我们自己的网站的入侵检测系统(IDE)日志/var/log/auth.log中最近的SSH攻击记录,我们可以观察到:攻击者试图使用用户登录系统,远程IP正 ...

  2. python怎么攻击服务器_资深黑客教python小白攻破一个网站!

    现在我们获取了网站服务器的IP地址为:173.236.138.113 寻找同一服务器上的其它网站,我们使用sameip.org. 我们需要关于你网站的以下信息: 让我们开始找你网站的DNS记录,我们用 ...

  3. 关于《Python绝技:运用Python成为顶级黑客》的学习笔记

    本篇文章主要把<Python绝技:运用Python成为顶级黑客>中的代码敲一遍,学学Python安全相关的编程与思路,然后根据具体的情况修改一下代码. 第一章--入门 1.准备开发环境 安 ...

  4. 书籍推荐——Python绝技:运用Python成为顶级黑客

    Python绝技:运用Python成为顶级黑客 本文推荐一本关于信息安全的图书:<Python绝技:运用Python成为顶级黑客>. 当您听到黑客这个词的时候是不是有点激动呢,尤其是顶级黑 ...

  5. 为什么黑客用python-《Python绝技》:运用Python成为顶级黑客

    点击"阅读原文"可以直接购买该书籍. 本月月考的奖品是<Python绝技>两本!敬请期待吧!Xcon&神话行动创始人呆神.Keenteam陈良.鹰总cnhawk ...

  6. 《Python绝技:运用Python成为顶级黑客》的学习笔记

    本篇文章主要把<Python绝技:运用Python成为顶级黑客>中的代码敲一遍,学学Python安全相关的编程与思路,然后根据具体的情况修改一下代码. 第一章--入门 1.准备开发环境 安 ...

  7. 《Python绝技:运用Python成为顶级黑客》读后感

    作为一个Java从业者,从网上了解到Python是一门简洁.高效的语言,而基本上每个热爱编程的人都大概有一种黑客梦,在二进制的世界里刀光剑影,于是就来试读下这本<Python绝技:运用Pytho ...

  8. python绝技:运用python成为顶级黑客

    python绝技:运用python成为顶级黑客 前言 有多少人是因为看了电视,看了那些牛逼的黑客选择成为程序员的. 我貌似也是其中一个,只是自从成为程序员以来,天天都是加班coding,到家就是睡倒床 ...

  9. python绝技运用python成为顶级pdf_python绝技:运用python成为顶级黑客 中文pdf完整版[42MB]...

    Python 是一门常用的编程语言,它不仅上手容易,而且还拥有丰富的支持库.对经常需要针对自己所 处的特定场景编写专用工具的黑客.计算机犯罪调查人员.渗透测试师和安全工程师来说,Python 的这些 ...

  10. python绝技运用python成为顶级pdf_python绝技运用Python成为顶级黑客PDF高清文档免费下载...

    提取码:2qyg Python 是一门常用的编程语言,它不仅上手容易,而且还拥有丰富的支持库.对经常需要针对自己所 处的特定场景编写专用工具的黑客.计算机犯罪调查人员.渗透测试师和安全工程师来说,Py ...

最新文章

  1. python使用textwrap包在已经生成的长字符串中嵌入回车符实战
  2. 【工程化】从0搭建VueJS移动端组件库开发框架
  3. 小程序入门学习15---数据库实战01
  4. eventlog analyzer 8.0
  5. Hexo+GitHub搭建个人博客
  6. 还在纠结蓝牙耳机哪款好用吗?2020我推荐这几款高性价比蓝牙耳机
  7. SaaS多租户管理系统是什么?SaaS多租户平台应用管理功能有哪些?
  8. Laravel第三方登录开发之实现QQ登录
  9. JVM垃圾收集—垃圾收集器及常见组合参数
  10. random.randint()用法
  11. PHP 数据类型划分(8种)、获取数据(变量)的类型函数、单引号和双引号的字符串区分转义符、定界符、拓展
  12. 使用Python处理百万数据量的Excel文件:删除列、切分换行、替换去重
  13. @Aspect无法使用的问题
  14. Java 中文 Unicode 编码转换
  15. CSDN的程序也让人不敢恭维!
  16. 一篇文章吃透Java ArrayList 面试别问,问就是滔滔不绝!
  17. 抢占智能制造“制高点” 个性化生产不可或缺
  18. 基于flask的天猫商城设计与实现
  19. 数美科技CTO梁堃:怎么样构建全栈式智能风控体系,在线业务安全的挑战与实践
  20. RuntimeError: context has already been set

热门文章

  1. 微软在 Build 2020 上“展示”新版 Edge for Linux
  2. c#:winform中多线程的使用
  3. 顺序图组合片段类型及属性
  4. 智能仪器原理及设计C语言,智能仪器仪表课程设计.doc
  5. qml 不刷新 放大还原_【显示器选择详解】你的电脑能否带动高分辨率,高刷新率显示器?...
  6. 因为计算机中丢失crlutl,crlutlintl.dll
  7. linux内核进程抢占,Re: Linux中进程能否被抢占
  8. qt connect函数_Qt Inside信号和槽之connect
  9. vue 设置每个页面的title
  10. c语言 北京时间转换utc时间_PHP时间戳和日期相互转换操作