难易程度:★★★
阅读点:python;web安全;
文章作者:xiaoye
文章来源:i春秋
关键字:网络渗透技术

前言

python是门简单易学的语言,强大的第三方库让我们在编程中事半功倍,今天,我们来谈谈python多线程在渗透测试中的应用,本文,我们将编写一个简易c段存活主机扫描脚本,以及一个python版本的多线程御剑--目录扫描工具

一、python 多线程
python多线程有几种写法
1. thread模块
python的一个多线程模块,小脚本可以用,但是有瑕疵,比如不稳定,线程数不好控制

下方贴出一个c段存活主机扫描脚本,这个脚本i春秋ado老师也有教过哦
思想:输入一个ip,经过字符拆分,获取c段,多线程地ping -c 2 ip ,根据返回的信息来判断主机是否存活
demo ping_thread.py:

'''
Created on -- @author: xiaoye
'''
#coding: utf-
import thread
import time
from subprocess import Popen,PIPE def scan_ip(ip):
process = Popen('ping -c 2 ' + ip, stdin=PIPE, stdout=PIPE, shell=True)
data = process.stdout.read()
if 'ttl' in data:
print '%s is live ,now time is %s' % (ip, time.strftime('%H:%M:%S')) if __name__ == '__main__':
#scan_ip('111.13.147.229')
ips = raw_input()
ip_header = '.'.join(ips.split('.')[:])
for i in range(,):
ip = ip_header + '.' + str(i)
#print ip
thread.start_new_thread(scan_ip, (ip,))
time.sleep(0.1)

运行情况:

速度还行,稳定性一般

thread模块,核心在:

[Python] 纯文本查看 复制代码
1
2
thread.start_new_thread(scan_ip, (ip,))
        time.sleep(0.1)

scan_ip是要执行的函数,(ip,)是传入的参数,记得sleep一下

2.threading模块用法:
demo:

'''
Created on --
@author: xiaoye
'''
#coding: utf-
import threading
import time def test(th):
print 'i am doing %s %s' % (th, time.strftime('%H:%M:%S')) def main():
thread = []
keys = ['movie_th','swim_th','listen_th','learn_th','movie_th','swim_th','listen_th','learn_th','movie_th','swim_th','listen_th','learn_th','movie_th','swim_th','listen_th','learn_th']
thread_count = len(keys)
#print thread_count
for i in range(thread_count):
t = threading.Thread(target=test, args=(keys[i],))
thread.append(t)
for i in range(thread_count):
thread[i].start()
for i in range(thread_count):
thread[i].join() if __name__ == '__main__':
main()

运行情况:

可以看到,基本是同时运行的,threading.Thread模块的一种用法就是这样:

for i in range(thread_count):
t = threading.Thread(target=test, args=(keys[i],))
thread.append(t)
for i in range(thread_count):
thread[i].start()
for i in range(thread_count):
thread[i].join()

模式1.:一个列表存放所有线程,start()执行列表中线程,join()等待运行完毕

模式1?,还有模式2吗?
当然,模式2就是从threading.Thread继承一个子类class,重写父类run方法,实现多线程运行run函数,而这种也是非常良好的写法
demo:

# -*- coding: utf- -*-
import threading class T(threading.Thread): def __init__(self):
threading.Thread.__init__(self) def run(self): #继承,threading.Thread子类, 重写run方法, run方法在start()后自动执行
print 'i love you' def main():
thread = []
for i in range():
thread.append(T())
for i in thread:
i.start()
for i in thread:
i.join() if __name__ == '__main__':
main()

运行情况:

二、线程间的数据守护
Queue绝对是保护线程间数据安全的好选择,有关于Queue,大家可以自行百度其用法,我发出一点经常用的:

Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.full 与 maxsize 大小对应
Queue.get([block[, timeout]]) 获取队列,timeout等待时间
Queue.get_nowait() 相当Queue.get(False)
非阻塞 Queue.put(item) 写入队列,timeout等待时间
Queue.put_nowait(item) 相当Queue.put(item, False)
Queue.task_done() 在完成一项工作之后,Queue.task_done() 函数向任务已经完成的队列发送一个信号
Queue.join() 实际上意味着等到队列为空,再执行别的操作

三、多线程threading.Thread+Queue实现渗透测试工具编写
脚本放出来:
1.多线程c段存活主机扫描:

'''
Created on --
@author: xiaoye
'''
#coding: utf-
import time
import sys
import threading
import Queue
from subprocess import Popen,PIPE class Quethread(threading.Thread):
def __init__(self, que):
threading.Thread.__init__(self)
self._que = que def run(self):
while not self._que.empty():
ip = self._que.get()
process = Popen('ping -c 2 ' + ip, stdin=PIPE, stdout=PIPE, shell=True)
data = process.stdout.read()
if 'ttl' in data:
sys.stdout.write('%s is live %s\n' % (ip, time.strftime('%H:%M:%S'))) def main():
que = Queue.Queue()
ips = raw_input()
thread = []
thread_count =
ip_head = '.'.join(ips.split('.')[:])
#print ip_head
for i in range(, ):
que.put(ip_head + '.' + str(i))
'''for i in range(1,255):
print que.get()''' for i in range(thread_count):
thread.append(Quethread(que)) for i in thread:
i.start() for i in thread:
i.join() if __name__ == '__main__':
main()

 

ubuntu下运行成功,win下需要修改Popen里的命令等,截图:

速度很快,稳定性较强
c段主机存活脚本:https://github.com/xiaoyecent/ping_threading_Queue

2.py版多线程御剑--目录扫描--支持自定义字典、输出文件位置以及自定义线程数:

'''
@author: xiaoye
'''
#coding: utf-
import requests
import sys
import threading
#import time
import Queue
from optparse import OptionParser reload(sys)
sys.setdefaultencoding('utf8') class Doscan(threading.Thread):
def __init__(self, que):
threading.Thread.__init__(self)
self._que = que def run(self):
while not self._que.empty():
d = self._que.get()
try:
r = requests.get(url + d, headers=headers, timeout=)
sys.stdout.write(d + ' is scan status:' + str(r.status_code) + '\n')
if r.status_code == :
with open(option.outfile, 'a') as f:
f.write(url + d + '\n')
except:
pass def main():
thread = []
thread_count = option.threadcount
que = Queue.Queue() with open(option.dictname, 'r') as f:
for d in f.readlines():
d = d.strip('\n')
que.put(d) for i in range(thread_count):
thread.append(Doscan(que)) for i in thread:
i.start() for i in thread:
i.join() if __name__ == '__main__':
parse = OptionParser()
parse.add_option('-u', '--url', dest='input_url', type='string', help='the url you wan to scan dir')
parse.add_option('-o', '--out', dest='outfile', type='string', help='output filename', default='result.txt')
parse.add_option('-s', '--speed', dest='threadcount', type='int', default=, help='the thread_count')
parse.add_option('-d', '--dict', dest='dictname', type='string', help='dict filename')
(option, args) = parse.parse_args()
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
url = option.input_url
main()
Usage: scan_dir.py [options]

Options:
-h, --help show this help message and exit
-u INPUT_URL, --url=INPUT_URL
the url you wan to scan dir
-o OUTFILE, --out=OUTFILE
output filename
-s THREADCOUNT, --speed=THREADCOUNT
the thread_count
-d DICTNAME, --dict=DICTNAME
dict filename



参数用法贴出来
运行情况
举个例子:
-u http://localhost -s 30 -d d://PHP.txt -o d://ichunqiu.txt:

结果:

运行速度取决于线程数(默认60)和实际环境
源码:https://github.com/xiaoyecent/scan_dir

四、总结
多线程加队列实现线程间的数据保护是很好的搭配,threading.Thread+Queue的用法希望大家能够掌握,另外,继承threading.Thread写出子类,重写父类run方法来实现多线程的写法也值得借鉴

python多线程在渗透测试中的应用的更多相关文章

  1. 详述MySQL服务在渗透测试中的利用

    本文作者:i春秋签约作家——Binghe 致力于书写ichunqiu社区历史上最长篇最细致最真实的技术复现文章. 文章目录: MySQL之UDF提权 MySQL之MOF提权 MySQL之常规写启动项提 ...

  2. 反向代理在Web渗透测试中的运用

    在一次Web渗透测试中,目标是M国的一个Win+Apache+PHP+MYSQL的网站,独立服务器,对外仅开80端口,网站前端的业务系统比较简单,经过几天的测试也没有找到漏洞,甚至连XSS都没有发现, ...

  3. Windows-NTFS-ADS在渗透测试中的利用

    0.什么是ADS Windows:微软公司的一款视窗操作系统,其内核为WindowsNT. NTFS:WindowsNT环境的限制级专用文件系统. ADS:NTFS的系统特性,交换数据流(Altern ...

  4. 渗透测试中的bypass技巧

    0x00 前言 许多朋友在渗透测试中因为遇到WAF而束手无策,本人应邀,与godkiller一同写下此文,希望能够对许多朋友的问题有所帮助. 此系列一共分为五篇文章,分别如下: 一.架构层绕过WAF ...

  5. Windows渗透测试中wmi的利用

    0x01 关于WMI WMI可以描述为一组管理Windows系统的方法和功能.我们可以把它当作API来与Windows系统进行相互交流.WMI在渗透测试中的价值在于它不需要下载和安装, 因为WMI是W ...

  6. WMI在渗透测试中的重要性

    0x01 什么是wmi WMI可以描述为一组管理Windows系统的方法和功能.我们可以把它当作API来与Windows系统进行相互交流.WMI在渗透测试中的价值在于它不需要下载和安装, 因为WMI是 ...

  7. 详述MSSQL服务在渗透测试中的利用(上篇)

    前言: 致力于复现最实用的漏洞利用过程. 本文将带领大家学习以下内容: 学习使用`xp_cmdshell`扩展存储过程 学习调用`wscript.shell` 学习MSSQL写文件 学习沙盘模式提权 ...

  8. 渗透测试中如何科学地使用V*P*N

    环境说明 Windows7 虚拟机,作为VPN网关,负责拨VPN.VPN可以直接OPENVPN,也可以使用ShadowSocks+SSTap. Kali 虚拟机, 渗透测试工作机 配置步骤 Windo ...

  9. MySQL在渗透测试中的应用

    原文地址:https://xz.aliyun.com/t/400 前言作为一个安全爱好者你不可能不知道MySQL数据库,在渗透过程中,我们也很经常遇到MySQL数据库的环境,本文就带大家了解MySQL ...

随机推荐

  1. Java多线程01(Thread类、线程创建、线程池)

    Java多线程(Thread类.线程创建.线程池) 第一章 多线程 1.1 多线程介绍 1.1.1 基本概念 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于 ...

  2. SQL Server 2008 通过C# CLR 使用正则表达式

    参考文章 MSSQLSERVER接入c#clr程序集,使c#函数变sql函数 正则表达式30分钟入门教程 SQL中采用Newtonsoft.Json处理json字符串 操作步骤 1.新建项目-> ...

  3. Image 图片

    随机矩阵画图 这一节我们讲解怎样在matplotlib中打印出图像.这里打印出的是纯粹的数字,而非自然图像.下面用 3x3 的 2D-array 来表示点的颜色,每一个点就是一个pixel. impo ...

  4. Ubuntu 18.04 下如何配置mysql 及 配置远程连接

    首先是大家都知道的老三套,啥也不说上来就放三个大招: sudo apt-get install mysql-server sudo apt isntall mysql-client sudo apt ...

  5. python 10 迭代器和三元运算符

    一.迭代器 1.迭代器协议:对象必须提供一种next方法,执行该方法要么返回迭代中的下一项,要么引起一个stopIteration异常,终止迭代 2.可迭代对象:实现了迭代器协议的对象 3.pytho ...

  6. vue中v-for的使用

    本人正在开始学习Vue,每天写写基础的记录,希望对大家有帮助,如有错误还望指出,我也是一个小白,也希望大家能一起进步 v-for指令的使用: 1.循环普通数组 item in list 中的item是 ...

  7. Gitlab使用时的一些注意事项

    1 gitlab-runner 不选中,在commit没有tab的时候,runner不会进行运行 2 在新安装的gitlab的环境上更改@localhost为远程地址 2.1  vim /opt/gi ...

  8. 移动端 去除onclick点击事件出现的背景色框

    这个特效是实现在移动端点击某个地方的时候,比如说按钮或者超链接的时候,系统会默认加上一些灰色的背景和一些高亮的效果.但是有的时候我们并不想要这些效果.并且希望点击的时候实现神不知鬼不觉的感觉,,这个时 ...

  9. ThinkPHP 3.2.3+ORACLE插入数据BUG修复及支持获取自增Id的上次记录

    TP+ORACLE插入数据BUG修复以及获取自增Id支持getLastInsID方法 这些天在做Api接口时候,发现用TP操作Oracle数据库,发现查询修改删除都能执行, 但一旦执行插入操作老是报错 ...

  10. C语言内存四区的学习总结(三)---- 栈区

    接上篇内存四区的堆区的总结,下面做一些栈区的相关总结. 一.栈区的分析: 就下面测试程序 #include "stdio.h" #include "string.h&qu ...