直接上源码
# -*- coding:utf-8 -*- """ Created on 2017/7/1 @author: jj 模拟 csrf csrf 验证cookie 中的 csrftoken 和 post 请求中的 csrfmiddlewaretoken 是否一致 再验证是否为 服务其发出的 csrftoken cas 验证规则 在 csrf 的基础上验证 post 请求中 lt """ import urllib import urllib2 import requests import re import cookielib headers = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36')] login_url = "http://127.0.0.1:8000/cas/login" # POST发送到的网址 # login_url = "http://127.0.0.1:8000/admin/login/?next=/admin/" # POST发送到的网址 filename = 'cookie.txt' def login(par1): cookie = cookielib.MozillaCookieJar() # 从文件中读取cookie内容到变量 cookie.load(filename, ignore_discard=True, ignore_expires=True) # 创建请求的request postdata = urllib.urlencode(par1) # 利用urllib2的build_opener方法创建一个opener opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) opener.addheaders.append(headers[0]) opener.addheaders.append(headers[1]) response = opener.open(login_url, postdata) print response.read() def save_cookie(): ckjar = cookielib.MozillaCookieJar(filename) ckproc = urllib2.HTTPCookieProcessor(ckjar) opener = urllib2.build_opener(ckproc) f = opener.open(login_url) content = f.read() pattern_csrf = re.compile(r"name='csrfmiddlewaretoken' value='(.*?)' />", re.S) pattern_lt = re.compile(r'<input id="id_lt" name="lt" type="hidden" value="(.*?)" />', re.S) csrf = re.findall(pattern_csrf, content) lt = re.findall(pattern_lt, content) f.close() ckjar.save(ignore_discard=True, ignore_expires=True) return csrf[0], lt[0] if __name__ == "__main__": csrf, lt = save_cookie() headers.append(('csrftoken', csrf)) data = {"username": "admin", "password": "admin", "csrfmiddlewaretoken": csrf, "lt": lt, "renew": 'False', "warn": 'on'} login(data)
返回结果