Skip to content

Instantly share code, notes, and snippets.

@YieldNull

YieldNull/ruijie.py

Last active Nov 17, 2015
Embed
What would you like to do?
Login in WHU Dormitory Network(登陆武汉大学宿舍校园网)网页认证
#!/usr/bin/env python
# coding:utf-8
"""
Login in WHU Dormitory Network
Usage:
Usage: ruijie.py [-l]
-l to logout
By hejunjie.net 2015.10.25
Update 2015.10.26
"""
import urllib
import urllib2
import re
import sys
import os
import json
# logout url config file
CONF_DIR = os.path.join(os.path.expanduser('~'), '.ruijie')
CONF_FILE = os.path.join(CONF_DIR, 'config')
# the headers is not necessary
HEADERS = [
('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
('Accept-Encoding', 'gzip, deflate, sdch'),
('Accept-Language', 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4'),
('Connection', 'keep-alive'),
('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)'
'Ubuntu Chromium/45.0.2454.101 Chrome/45.0.2454.101 Safari/537.36'),
#('Referer','')
]
def error(msg):
"""
When encountered error, print message and exit
"""
print msg
sys.exit(0)
def load_conf():
"""
load config file and parse as json
"""
try:
f = open(CONF_FILE, 'r')
except IOError:
return None
conf = json.load(f)
f.close()
return conf
def login():
# load Config
conf = load_conf()
if not conf:
conf = {}
conf['user'] = raw_input('Username:')
conf['password'] = raw_input('Password:')
conf['login'] = 'true'
conf['logout'] = ''
if not os.path.exists(CONF_DIR):
os.mkdir(CONF_DIR)
json.dump(conf, open(CONF_FILE, 'w'))
user = conf['user']
password = conf['password']
# try to connect baidu
# if have not connected, server returns the redirect url
redir = urllib.urlopen('http://www.baidu.com').read()
url = re.match(r"<script>top.self.location.href='(.*)'</script>", redir)
if url is None:
error('Already Logged in')
else:
url = url.group(1)
# get host. form "ip:port"
host = re.search(r'http://(.*?)/', url).group(1)
# POST URL Config
query = re.search(r'^.*\?(.*)$', url).group(1)
post_url = 'http://%s/eportal/userV2.do?method=login&param=true&%s' % (
host, '%s&username=%s&pwd=%s' % (query, user, password))
params = {
'is_auto_land': 'false',
'usernameHidden': user,
'username_tip': 'Username',
'username': user,
'strTypeAu': '',
'uuidQrCode': '',
'authorMode': '',
'pwd_tip': 'Password',
'pwd': password,
}
# build opener
opener = urllib2.build_opener()
HEADERS.append(('Referer', url))
opener.addheaders = HEADERS
# POST to Login and get login info
info = opener.open(post_url, urllib.urlencode(params)).read().decode('gbk')
account = re.search(r"d.accountInfo.innerText='(.*?)';", info, re.S)
if account:
print u'Login Success.'
print u'Leaving Account Fee: %s' % account.group(1).strip()
else:
error('Encountered an unknown error')
# write logout url to config file
logout_url = re.search(r"d.toLogOut.href='(.*?)'", info, re.S).group(1)
f = open(CONF_FILE, 'w')
conf['login'] = 'true'
conf['logout'] = 'http://%s%s' % (host, logout_url)
json.dump(conf, f)
f.close()
def logout():
# load config
conf = load_conf()
if not conf or not conf['logout']:
error('You have never used this program to login')
# check login
url = conf['logout']
logged = conf['login']
#if logged != 'true':
#error('Please login first')
# logout
res = urllib.urlopen(url).read().decode('gbk')
if res.find('window.location.replace("./userV2.do?method=goToLogout");'):
conf['login'] = 'false'
json.dump(conf, open(CONF_FILE, 'w'))
print 'Logout Success'
else:
error('Encountered an unknown error')
if __name__ == '__main__':
if len(sys.argv) == 1:
login()
elif len(sys.argv) == 2 and sys.argv[1] == '-l':
logout()
else:
print 'Usage: ruijie.py [-l]'
print ' -l to logout'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment