Python Requests 实现某论坛模拟登录

某论坛需要登录才能看到帖子回复,通过逆向登录接口,使用 Requests 实现模拟登录,获取成功登录后的 cookie

目标网站

1
aHR0cHM6Ly9iYnMuaWNodWFuZ2xhbi5jb20v

逆向目标

请求头 Cookie
chuanglan_01

请求参数 loginhashfromhash
chuanglan_02

逆向分析

在响应头中 Set-Cookie
chuanglan_03

loginhash和fromhash

在响应内容中:
chuanglan_04

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import re

import requests


def set_data(html: str) -> tuple:
# 提取 loginhash、fromhash
loginhash_lish = re.findall(r'main_messaqge_(.*?)"', html, re.S)
fromhash_list = re.findall(r'formhash" value="(.*?)"', html, re.S)
return (
loginhash_lish[0],
fromhash_list[0]
)


def get_data() -> tuple:
url = ' https://bbs.ichuanglan.com/member.php'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
}
params = {
'mod': 'logging',
'action': 'login',
'infloat': 'yes',
'handlekey': 'login',
'inajax': '1',
'ajaxtarget': 'fwin_content_login',
}
res = requests.get(url, headers=headers, params=params)

return (
dict(res.cookies),
res.text
)


def login(username: str, password: str, loginhash: str, fromhash: str, cookies: dict) -> dict:
url = 'https://bbs.ichuanglan.com/member.php'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
}
params = {
'mod': 'logging',
'action': 'login',
'loginsubmit': 'yes',
'handlekey': 'login',
'loginhash': loginhash,
'inajax': '1',
}
data = {
'formhash': fromhash,
'referer': 'https://bbs.ichuanglan.com/',
'loginfield': 'username',
'username': username,
'password': password,
'questionid': '0',
'answer': '',
}

with requests.session() as session:
requests.utils.add_dict_to_cookiejar(session.cookies, cookies)
res = session.post(url, headers=headers, params=params, data=data)
# print(res.text)

return dict(res.cookies)


def main(username: str, password: str):
cookies, html = get_data()
loginhash, fromhash = set_data(html)
cookie = login(username, password, loginhash, fromhash, cookies)
print(cookie)


# 账号
username = '你的账号'
# 密码
password = '你的密码'

main(username, password)

如果账号密码正确,输出(数据已做脱敏处理):

1
2
3
4
5
6
7
8
9
{
'3fAm_2132_auth': 'xxx',
'3fAm_2132_checkfollow': '1',
'3fAm_2132_lastact': 'xxx',
'3fAm_2132_lastcheckfeed': 'xxx',
'3fAm_2132_lip': 'xxx',
'3fAm_2132_sid': 'xxx',
'3fAm_2132_ulastactivity': 'xxx'
}