Author: Ali0thphp
Email: martin2877@foxmail.comcss
Date: 20181104html
众所周知信息收集是渗透测试最早且最重要一步,并且不只渗透,平时作的不少事情都须要用到爬虫。因此我也本身常常写爬虫脚本。这一个是去年末时写的超迷你爬虫,一方面是有须要,一方面是写着玩,因而把代码使用各类装逼型写法缩到行数最少。以后也在不断地使用中优化,目前应该不会有太大的改动,也欢迎你们提 issue。(走过路过,点个赞呗。)python
Tiny Crawler
是一个 150 行代码实现的简单爬虫,是一个 python class 文件。它可以应付平常的渗透测试工做,由于它具有多种功能。git
代码的写法上,尽可能让代码量少而精、通用、易用,以便于实现平常的大量爬虫需求。能够随时集成到其它工具当中。github
代码地址:github.com/Martin2877/…web
语言: python3cookie
行数:去掉注释约150行app
直接两步,一步是初始化实例,一步是爬取,最后即可以经过实例中的 urls
变量看到爬取结果。默认为爬取深度为1的同源地址。dom
def testphp_vulnweb():
url = "http://testphp.vulnweb.com/"
webcrawler = Webcrawler(url)
webcrawler.crawl()
urls = webcrawler.urls
print(urls)
复制代码
def testphp_vulnweb():
url = "http://testphp.vulnweb.com/"
webcrawler = Webcrawler(url,3)
webcrawler.crawl()
urls = webcrawler.urls
print(urls)
复制代码
能够看到,爬取的是同源的地址连接,而且对每一个新的地址进行爬取,直到达到设定的层级深度为止。
def testphp_vulnweb():
url = "https://www.acunetix.com/"
webcrawler = Webcrawler(url,2)
webcrawler.crawl(None,False,None,True)
urls = webcrawler.urls
print(urls)
复制代码
能够看到,全部非同源的地址被爬取了出来。而且也是对每一个新的地址进行爬取,直到达到设定的层级广度为止。
这些不一一介绍,下面以爬取的示例展现
def testphp_vulnweb():
cookie = {
'Proxy-Connection' : 'keep-alive',
'Cache-Control' : 'max-age=0',
'Upgrade-Insecure-Requests' : '1',
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Referer' : 'https://www.google.com.hk/',
'Accept-Encoding' : 'gzip, deflate',
'Accept-Language' : 'zh-CN,zh;q=0.9'
}
url = "http://testphp.vulnweb.com/"
webcrawler = Webcrawler(url,2,"http://127.0.0.1:8081",cookie)
match = {"css":False,"php":True} # 过滤含 css 的连接,但要 php 的
webcrawler.crawl(match,True,100,None,None)
# 分别意思为:
# 使用match过滤,同源,最多获取 100 个连接,不找新域名,爬取 html 标签
urls = webcrawler.urls
print(urls)
复制代码
有时候,连接写在 js 中,而不是放在 html 的中,这个时候,就要经过正则的形式去获取。如上面的代码修改为下面的形式。
webcrawler.crawl(None,True,100,None,"regex")
复制代码
结果能够看到爬取到以匹配形式获取的连接。
只要引用此模块即可快速爬取目录遍历的全部连接。
from tinycrawler import Webcrawler
def fetch(_url):
webcrawler = Webcrawler(_url,5)
webcrawler.crawl()
print(webcrawler.urls)
复制代码
由于平时还会有一些其它的需求,好比爬取时候,同一类型的类似地址爬取过多,或要根据页面内容来过滤连接等,因此本爬虫还在不断改进中。
为了将代码量和行数缩减到最少,脚本中包含了大量装逼型代码写法,下面罗列一些,仅供欣赏。
一、检查已经存在的url
# check for exist url
source = self.urls if self.new_domain else self.website
return [x for x in _urls if x not in self.urls and comp_netloc(x,source)]
复制代码
装逼写法有三,使用了 x if a else b
x for x in
和 加[]
返回list。
二、循环爬取
for dp in range(1,self.depth):
urls_new = self.comp(set(self.flat_list(list(map(self.url_html,urls_new)))))
if len(urls_new) == 0:break
if verbose : print("[result]urls_new:{0},self.urls:{1}".format(urls_new,self.urls))
self.urls.extend(urls_new)
复制代码
装逼写法为这里使用 for
进行循环爬取的加载,当新地址为 0 时才退出。而新地址 urls_new
使用了上面封装的self.comp
方法进行比较提取。