-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathecnu_net.py
executable file
·275 lines (228 loc) · 8.71 KB
/
ecnu_net.py
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
#!/usr/bin/env python3
description = """
ECNU internet login/logout script
Copyright (C) 2019 Jiuning Chen <johnnychen94@hotmail.com>
Distributed under terms of the MIT license.
This script is hosted at both LAN and WAN network:
* Github: https://github.com/johnnychen94/ecnu-net-login
* Gitlab@LFLab.ECNU: https://gitlab.lflab.cn/lflab/ecnu-net-login
"""
from urllib.request import urlopen, Request
from urllib.parse import urlencode, quote_plus
from urllib.error import URLError
import socket
from getpass import getpass
import time
from datetime import datetime
import os
import configparser
from argparse import ArgumentParser
import math
from random import shuffle
CONFIG_FILE_PATH = os.path.expanduser("~/.config/ecnu_net/config")
# Only when ipv4 network is connected can we connect urls in this list
TEST_URLS = ['https://www.baidu.com/',
'https://www.taobao.com/',
'https://www.amazon.cn/',
'https://www.jd.com/',
'https://www.bing.com',
'http://www.cnki.net/',
'https://www.qq.com/',
'https://www.csdn.net/',
'https://gitee.com/',
'https://www.zhihu.com/',
'https://www.aliyun.com/',
'https://arxiv.org/']
AC_ID = '4'
LOGIN_URL = 'https://login.ecnu.edu.cn/srun_portal_pc.php?ac_id=' + str(AC_ID)
POSTDATA_TEMPLATE = {
'action':'login',
'username': '',
'password': '',
'ac_id': AC_ID,
'save_me':'0',
'ajax':'1',
}
def send_request(postdata: dict):
"""send request filled with postdata"""
postdata = urlencode(postdata, quote_via=quote_plus).encode("utf-8")
action_request = Request(url=LOGIN_URL, data=postdata)
return urlopen(action_request).read()
def internet_on(test_urls= None, pass_ratio=0.6, timeout=1, verbose=True):
"""
check if internet is connected
args
- test_urls : list of urls for test
- pass_count : if there're at least `pass_count` urls are connected,
the test passes
"""
if not test_urls:
test_urls = TEST_URLS
test_urls = test_urls.copy()
shuffle(test_urls)
def _internet_on(url, timeout):
try:
urlopen(url, timeout=timeout)
return True
except (socket.timeout, URLError, ConnectionResetError):
return False
on_count = 0
off_count = 0
pass_count = math.floor(pass_ratio * len(test_urls))
fail_count = len(test_urls) - pass_count
def _get_test_urls(test_urls, verbose):
return test_urls
if verbose:
print("check internet connection...")
for url in _get_test_urls(test_urls, verbose):
rst = _internet_on(url, timeout)
on_count += rst
off_count += 1-rst
if on_count == pass_count:
return True # return immediately
if off_count == fail_count:
return False
class Loginer():
"""ECNU network login class"""
def __init__(self, postdata, force_reread=False):
"""
initialize Loginer instance
args
- force_reread : True to update/force_reread the config
methods:
- logout : logout internet
- login : login internet
"""
self._read_config(force_reread)
self._postdata = postdata.copy()
self._postdata['username'] = self._username
self._postdata['password'] = self._password
def logout(self, verbose=True, prompt=True):
"""log out internet"""
if not internet_on(verbose=verbose):
print("Internet is already off, no ops.")
else:
# send exactly same package as login
print("Logout...")
send_request(self._postdata)
# the request result is useless, hence we
# manually check internet connection
if not internet_on(verbose=verbose):
print("Success!")
elif prompt:
if input("Failed! Retry? [Y/n]") not in ['n', 'N', 'no', 'NO']:
# infinite recursion until success
self.logout(verbose=verbose)
else:
print("Failed!")
def login(self, verbose=True, prompt=True):
"""login internet"""
if internet_on(verbose=verbose):
print("Internet is already on, no ops.")
else:
print("Login...")
send_request(self._postdata)
# the request result is useless, hence we
# manually check internet connection
if internet_on(verbose=verbose):
print("Success!")
elif prompt:
if input("Failed! Retry? [Y/n]") not in ['n', 'N', 'no', 'NO']:
# infinite recursion until success
self.login(verbose=verbose)
else:
print("Failed!")
def _write_config(self, ask_write_password=True):
config = configparser.ConfigParser()
data = {'username': self._username}
if ask_write_password:
write_pass = input("write plain password? [y/N]") in ['y', 'Y', 'yes', 'YES']
confirm = input("This can be risky if others have access to your data, are you sure?") in ['y', 'Y', 'yes', 'YES']
write_pass = write_pass and confirm
else:
write_pass = False
if write_pass:
print("Store plain password, Make sure nobody sees your password.")
data['password'] = self._password
config['user'] = data
root_dir = os.path.split(CONFIG_FILE_PATH)[0]
if not os.path.isdir(root_dir):
os.makedirs(os.path.split(CONFIG_FILE_PATH)[0])
with open(CONFIG_FILE_PATH, 'w') as configfile:
config.write(configfile)
def _read_config(self, force_reread=False, write_config=False):
config = configparser.ConfigParser()
has_config_file = config.read(CONFIG_FILE_PATH)
if has_config_file:
config = config['user']
else:
config = None
write_config = False
if config and (not force_reread):
read_username = 'username' not in config.keys()
read_password = 'password' not in config.keys()
ask_write_password = False
else:
read_username = True
read_password = True
ask_write_password = True
write_username = read_username
write_password = read_password
write_config = write_username or write_password
# read config from stdin
self._username = input("Student ID: ") if read_username else config['username']
password = getpass("Password: ") if read_password else config['password']
again_password = getpass("Type again: ") if read_password else config['password']
if password == again_password:
self._password = password
else:
raise ValueError("Two passwords don't match, try again.")
if write_config:
self._write_config(ask_write_password)
def login(**kwargs):
"""login ECNU internet"""
Loginer(POSTDATA_TEMPLATE).login(**kwargs)
def logout(**kwargs):
"""logout ECNU internet"""
Loginer(POSTDATA_TEMPLATE).logout(**kwargs)
def update():
"""update configuration"""
# update is done in initialization
Loginer(POSTDATA_TEMPLATE, force_reread=True)
def main():
"""main function of module ecnu_net"""
parser = ArgumentParser(description=description)
group_parser = parser.add_mutually_exclusive_group()
group_parser.add_argument('--login', action='store_true', help='internet login')
group_parser.add_argument('--logout', action='store_true', help='internet login')
group_parser.add_argument('--update', action='store_true', help='update configuration')
parser.add_argument('--verbose', action='store_true', help='show detail information')
parser.add_argument('--daemon', action='store_true', help='login/logout as a daemon service')
args = parser.parse_args()
if args.daemon:
while True:
try:
print(datetime.now().ctime())
Loginer(POSTDATA_TEMPLATE, force_reread=False)
if args.update:
raise ValueError("update doesn't support daemon mode.")
if args.login:
login(verbose=args.verbose, prompt=False)
if args.logout:
logout(verbose=args.verbose, prompt=False)
except OSError:
pass
finally:
time.sleep(120)
if args.login:
login(verbose=args.verbose)
exit()
if args.logout:
logout(verbose=args.verbose)
exit()
if args.update:
update()
exit()
parser.print_help()
if __name__ == '__main__':
main()