python学习笔记1——简单多线程的目录遍历脚本

对使用已知CMS系统的目录遍历
若目标系统使用了CMS模板,那么我们可以对该系统进行已知目录的遍历。首先下载该CMS模板到本地,然后对本地的目录进行一个提取,将提取到的文件目录作为字典,对目标系统进行访问,通过状态码来查看目标系统是否存在该文件。
代码:

from queue import Queue
import threading
import os
import urllib
import urllib.request as urllib2

threads = 10

target = "http://192.168.137.131"
directory = "F:/test/directory"
filters = [".jpg",".gif",".png",".css",".htm",".js"]

os.chdir(directory)

web_paths = Queue()

#获取本地目录结构
for r,d,f in os.walk("."):
    for files in f:
        r1 = r.replace("\\","/")
        remote_path = "%s/%s" %(r1,files)
        if remote_path.startswith("."):
            remote_path = remote_path[1:]
        if os.path.splitext(files)[1] not in filters:
            web_paths.put(remote_path)

#根据获取到的本地目录结构对目标系统进行遍历
def test_remote():
    while not web_paths.empty():
        path = web_paths.get()
        url = "%s%s" % (target,path)
        #print(url)
        request = urllib2.Request(url)
        try:
            response = urllib2.urlopen(request)
            content = response.read()
            print("[%d] => %s" % (response.code,url))
            response.close()
        except urllib2.HTTPError as err:
            print("ERROR[%s]%s"% (err.code,url))
            pass
        except urllib2.URLError as err:
            print("ERROR[%s]%s"% (err,url))
            pass

#创建多线程
for i in range(threads):
    print("开始运行线程【%d】" % i)
    t = threading.Thread(target=test_remote)
    t.start()

总结:

  1. os.walk(top)函数
    top – 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。
    root 所指的是当前正在遍历的这个文件夹的本身的地址
    dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
    files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
  2. 反斜线处理
    Windows下的目录分隔符是反斜线"",若直接将反斜线带入url,通过request函数进行访问时回出现报错,因此将提取到的目录带入url之前,需要进行一步处理,将反斜线 ““转换为斜线”/”:
    r1 = r.replace("\","/")
    3.多线程的实现方式
    创建多线程的方法应写在主函数,通过调用线程函数来实现多线程。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值