-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrun.py
More file actions
executable file
·429 lines (358 loc) · 15.8 KB
/
Copy pathsrun.py
File metadata and controls
executable file
·429 lines (358 loc) · 15.8 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
srun - 深澜软件校园网自动登录工具
北京理工大学网络认证系统命令行客户端
"""
import argparse
import requests
import json
import os
import sys
import getpass
import time
from pathlib import Path
from urllib.parse import urlencode, urlparse, parse_qs
# 导入我们的模块
from config import SrunConfig
from crypto import SrunCrypto
class SrunClient:
"""深澜网络认证客户端"""
def __init__(self, base_url='http://10.0.0.55'):
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
})
# 初始化加密模块
self.crypto = SrunCrypto()
# 认证参数(从HTML页面分析得出)
self.auth_params = {
'ac_id': '8',
'user_ip': '10.107.10.179',
'nas_ip': '',
'user_mac': '',
'url': '',
'viewType': 'list'
}
def _get_portal_info(self, verbose=False):
"""获取门户信息和参数"""
try:
response = self.session.get(self.base_url, timeout=10)
response.raise_for_status()
# 尝试解析页面中的隐藏参数
try:
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
for field in ['ac_id', 'user_ip', 'nas_ip', 'user_mac', 'url', 'viewType']:
input_elem = soup.find('input', {'name': field})
if input_elem:
value = input_elem.get('value', '')
if value: # 只更新非空值
self.auth_params[field] = value
if verbose:
print(f"解析到的认证参数: {self.auth_params}")
except ImportError:
if verbose:
print("警告: 未安装 beautifulsoup4,使用默认参数")
return True
except Exception as e:
print(f"错误: 无法连接到认证服务器: {e}")
return False
def _get_challenge(self, username):
"""获取challenge令牌"""
try:
challenge_url = f"{self.base_url}/cgi-bin/get_challenge"
# 添加时间戳参数
timestamp = str(int(time.time() * 1000))
params = {
'username': username, # 需要提供用户名
'ip': self.auth_params['user_ip'],
'callback': 'jQuery', # JSONP回调
'_': timestamp # 时间戳,防止缓存
}
response = self.session.get(challenge_url, params=params, timeout=10)
if response.status_code == 200:
# 解析JSONP响应
text = response.text.strip()
if text.startswith('jQuery('):
text = text[7:-1] # 移除jQuery()包装
try:
data = json.loads(text)
if data.get('error') == 'ok':
return data.get('challenge'), data.get('client_ip')
except json.JSONDecodeError:
pass
print(f"警告: 无法获取challenge")
print(f"请求URL: {challenge_url}")
print(f"请求参数: {params}")
print(f"响应状态: {response.status_code}")
print(f"响应内容: {response.text[:200]}...")
return None, None
except Exception as e:
print(f"警告: challenge请求失败: {e}")
return None, None
def login(self, username, password, verbose=False):
"""执行登录"""
if not self._get_portal_info(verbose):
return False
print("正在获取challenge...")
token, client_ip = self._get_challenge(username)
if not token:
print("错误: 无法获取challenge令牌")
return False
if verbose:
print(f"Challenge获取成功: {token[:20]}...")
# 使用客户端IP(如果可用)
user_ip = client_ip or self.auth_params['user_ip']
# 使用crypto模块创建登录参数
hmd5_password = self.crypto.hmac_md5(password, token)
# 使用完整的xEncode加密的info参数
info = self.crypto.create_info_string(username, password, user_ip, self.auth_params['ac_id'], token)
if verbose:
print(f"调试信息 - 使用xEncode加密的info: {info[:80]}...")
chksum = self.crypto.create_chksum(
token, username, hmd5_password, self.auth_params['ac_id'], user_ip, info
)
os_info = self.crypto.get_os_info()
login_data = {
'action': 'login',
'username': username,
'password': '{MD5}' + hmd5_password,
'ac_id': self.auth_params['ac_id'],
'ip': user_ip,
'chksum': chksum,
'info': info,
'n': str(self.crypto.n),
'type': str(self.crypto.type),
'os': os_info['device'],
'name': os_info['platform'],
'double_stack': '0',
'ignore': '2',
'cas_account': '',
'cas_password': ''
}
# 执行登录请求
try:
login_url = f"{self.base_url}/cgi-bin/srun_portal"
if verbose:
print(f"正在登录: {login_url}")
# 隐藏密码的调试信息
debug_data = login_data.copy()
debug_data['password'] = '{MD5}***hidden***'
print(f"登录参数: {debug_data}")
# 修复: JS 使用 JSONP (GET) 请求, 而不是 POST.
# 需要添加 callback 参数并使用 GET 方法.
login_data['callback'] = 'jQuery'
response = self.session.get(login_url, params=login_data, timeout=15)
if response.status_code == 200:
if verbose:
print(f"服务器响应: {response.text[:500]}...")
result = self._parse_login_response(response.text)
if result['success']:
print("✓ 登录成功")
return True
else:
print(f"✗ 登录失败: {result['message']}")
if verbose:
print(f"完整响应: {response.text}")
return False
else:
print(f"✗ 登录请求失败,状态码: {response.status_code}")
return False
except Exception as e:
print(f"✗ 登录过程中出现错误: {e}")
return False
def _parse_login_response(self, response_text):
"""解析登录响应"""
try:
# 尝试解析JSONP响应
if 'jQuery' in response_text and response_text.strip().endswith(')'):
start = response_text.find('(') + 1
end = response_text.rfind(')')
json_str = response_text[start:end]
data = json.loads(json_str)
if data.get('error') == 'ok':
return {'success': True, 'message': '登录成功'}
else:
error_msg = data.get('error_msg') or str(data.get('error', '未知错误'))
return {'success': False, 'message': error_msg}
# 检查纯文本响应中的成功标识
response_lower = response_text.lower()
success_indicators = ['login_ok', '认证成功', 'success']
failure_indicators = ['error', 'fail', 'wrong', 'invalid']
for indicator in success_indicators:
if indicator in response_lower:
return {'success': True, 'message': '登录成功'}
for indicator in failure_indicators:
if indicator in response_lower:
return {'success': False, 'message': '登录失败'}
# 默认情况:短响应包含ok认为成功
if len(response_text) < 100 and 'ok' in response_text:
return {'success': True, 'message': '登录成功'}
return {'success': False, 'message': f'未知响应: {response_text[:100]}...'}
except Exception as e:
return {'success': False, 'message': f'响应解析错误: {e}'}
def logout(self):
"""注销登录"""
try:
logout_url = f"{self.base_url}/cgi-bin/srun_portal"
logout_data = {
'action': 'logout',
'ac_id': self.auth_params['ac_id'],
'ip': self.auth_params['user_ip']
}
response = self.session.get(logout_url, params=logout_data, timeout=10)
if response.status_code == 200:
response_lower = response.text.lower()
if 'logout_ok' in response_lower or '注销成功' in response_lower:
print("✓ 注销成功")
return True
else:
print("✗ 注销失败")
print(f"响应: {response.text[:200]}...")
return False
else:
print(f"✗ 注销请求失败,状态码: {response.status_code}")
return False
except Exception as e:
print(f"错误: 注销过程中出现问题: {e}")
return False
def check_status(self):
"""检查当前登录状态"""
try:
# 方法1: 检查用户信息接口
info_url = f"{self.base_url}/cgi-bin/rad_user_info"
response = self.session.get(info_url, timeout=10)
if response.status_code == 200:
text = response.text.strip()
# 深澜系统返回用户信息格式:user_info,flow,etc...
if ',' in text and len(text.split(',')) >= 3:
parts = text.split(',')
if len(parts) >= 8:
username = parts[0] if parts[0] != '0' else None
if username:
print(f"✓ 当前状态: 已登录 (用户: {username})")
return True
print("✗ 当前状态: 未登录")
return False
else:
print("? 无法确定登录状态")
return False
except Exception as e:
print(f"错误: 状态检查失败: {e}")
return False
def main():
"""主函数"""
parser = argparse.ArgumentParser(
description='srun - 深澜软件校园网自动登录工具',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
使用示例:
srun # 使用配置文件中的凭据自动登录
srun -p # 提示输入用户名和密码登录
srun -s # 检查当前登录状态
srun --logout # 注销当前登录
srun --config # 配置用户名和密码
srun --auto # 启动后台自动登录模式
"""
)
parser.add_argument('-p', '--prompt', action='store_true',
help='提示输入用户名和密码')
parser.add_argument('-s', '--status', action='store_true',
help='检查当前登录状态')
parser.add_argument('--logout', action='store_true',
help='注销登录')
parser.add_argument('--config', action='store_true',
help='配置用户名和密码')
parser.add_argument('--auto', action='store_true',
help='启动后台自动登录模式')
parser.add_argument('--interval', type=int, default=300,
help='自动模式下的检测间隔(秒),默认300')
parser.add_argument('--server', default='http://10.0.0.55',
help='认证服务器地址 (默认: http://10.0.0.55)')
parser.add_argument('-v', '--verbose', action='store_true',
help='详细输出')
args = parser.parse_args()
client = SrunClient(args.server)
config = SrunConfig()
if args.auto:
print("启动后台自动登录模式...")
print(f"检测间隔: {args.interval} 秒")
credentials_loaded = False
username, password = None, None
while True:
try:
print(f"[{time.ctime()}] 正在检查登录状态...")
if not client.check_status():
print("状态:未登录,尝试自动登录...")
if not credentials_loaded:
username, password = config.get_credentials()
if not username or not password:
print("错误: 未找到保存的凭据,请先运行 'srun --config' 配置")
break
print(f"已加载用户 [{username}] 的凭据")
credentials_loaded = True
client.login(username, password, args.verbose)
else:
print("状态:已登录,无需操作。")
print(f"下一次检测将在 {args.interval} 秒后...")
time.sleep(args.interval)
except KeyboardInterrupt:
print("\n用户中断,退出自动登录模式。")
break
except Exception as e:
print(f"错误: 自动登录循环中出现异常: {e}")
print(f"将在 {args.interval} 秒后重试...")
time.sleep(args.interval)
return
# 处理不同的命令
if args.config:
# 配置用户名和密码
username = input("用户名: ").strip()
password = getpass.getpass("密码: ")
if username and password:
config.save_credentials(username, password)
print("✓ 凭据已保存")
else:
print("✗ 用户名和密码不能为空")
return
if args.status:
# 检查登录状态
client.check_status()
return
if args.logout:
# 注销登录
client.logout()
return
# 登录逻辑
if args.prompt:
# 提示输入凭据
username = input("用户名: ").strip()
password = getpass.getpass("密码: ")
if not username or not password:
print("✗ 用户名和密码不能为空")
sys.exit(1)
else:
# 从配置文件读取凭据
username, password = config.get_credentials()
if not username or not password:
print("✗ 未找到保存的凭据,请先运行 'srun --config' 配置")
print("或使用 'srun -p' 手动输入凭据")
sys.exit(1)
if args.verbose:
print(f"使用保存的凭据: {username}")
# 执行登录
if client.login(username, password, args.verbose):
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("\n用户中断")
sys.exit(1)
except Exception as e:
print(f"未知错误: {e}")
sys.exit(1)