用python发送和接收http请求,也需要发送会话cookie

时间:2011-02-08 14:23:35

标签: python http cookies post http-headers

我在我的服务器上测试我的登录功能(x尝试失败后自动禁止禁用)。我找到了一个发送http请求的简单python脚本:

import urllib, urllib2, re, os, sys, cookielib

def main():
    host = 'http://192.168.1.133/intro.php'
    user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)'
    headers = {'User-Agent': user_agent}
    username = 'admin'
    error =  '<p class="highlight">Login failed. Please try again.</p>'
    word_file = 'pass.txt'
    word_pos = 1

    file = open(word_file, 'r')
    word_list = file.read().split('\n')
    file.close

    for word in word_list:
        form = {'username': username, 'password': word}

        print 'Tring password: %s (%d/%d)' % (word, word_pos, len(word_list))
        word_pos = word_pos + 1

        data = urllib.urlencode(form)
        request = urllib2.Request(host, data, headers)
        response = urllib2.urlopen(request)

        size = response.headers.get("content-length")

        #print 'response %s' % (response.read())
        #print 'size: %s' % (size)

        if not re.search(error, response.read()):
            print 'Login Combination: [%s:%s]' % (username, word)
            save_combo = open('login comination.txt', 'w')
            save_combo.write(username + ':' + word)
            save_combo.close
            break

if __name__ == '__main__':
    main()

但是我的intro.php文件看起来像这样:

$a = session_id();
if ($a == '') session_start();

我必须发送会话cookie。这是典型的登录请求:

POST /intro.php HTTP/1.1
Host: 192.168.1.133
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 AlexaToolbar/alxf-2.01 Firefox/3.6.13
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Proxy-Connection: keep-alive
Referer: http://192.168.1.133/intro.php
Cookie: __utma=48024167.372656243.1297092510.1297169678.1297174274.6; __utmz=48024167.1297117542.3.2.utmcsr=search.genieo.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmc=48024167; lang=en_US; PHPSESSID=7v8tt2ln0kaavo0ko7a7pklho6; __utmb=48024167.1.10.1297174274
Content-Type: application/x-www-form-urlencoded
Content-Length: 39

username=yeyeye&pwd=123456&submit=Login

我想制作cookie变量,这样我就可以发送每个请求的cookie,而不仅仅是我现在发送的POST,Host,User-Agent。我刚刚安装了python,所以我不太确定如何使用cookielib ..

1 个答案:

答案 0 :(得分:0)

替换

headers = {'User-Agent': user_agent}

headers = {
    'User-Agent': user_agent,
    'Cookie': '__utma=48024167.372656243.1297092510.1297169678.1297174274.6...'
}