Skip to content

Instantly share code, notes, and snippets.

@creamidea
Created May 26, 2014 13:18
Show Gist options
  • Save creamidea/698530d2242de053d6da to your computer and use it in GitHub Desktop.
Save creamidea/698530d2242de053d6da to your computer and use it in GitHub Desktop.
锐捷 有线 网页 拨号, 刷新频率1s (哈哈,有点丧心病狂)。这次使用配置文件输入密码,配置文件将在第一次运行时生成,并在第二次运行之后删除密码。
# -*- coding: utf-8 -*-
import re
import urllib
import urllib2
import cookielib
import time
import getpass
import threading
from HTMLParser import HTMLParser
import ConfigParser
class RJLoginHTMLParser(HTMLParser):
# 解析登录页面
form = {}
def handle_starttag(self, tag, attrs):
if tag == "input":
# print tag, attrs
_attrs = filter(lambda x: x[0] == "name" or x[0] == "value", attrs)
if _attrs[0][1] == 'tipinfoHidden' or \
_attrs[0][1] == 'publishInfoHidden' or \
_attrs[0][1] == 'publishTextInfoHidden' or \
_attrs[0][1] == 'noticeOK':
# 这些都是废话,!!!!!!!!!!!!!!!!!!!!
return
self.form[_attrs[0][1]] = _attrs[1][1]
def handle_endtag(self, tag):
pass
def handle_data(self, data):
pass
class RuijieWeb(object):
REGEXLOGINURL = r"<script>self.location.href=\'(.*)\'\+\'(.*)\';</script>"
REGEXLOGOUTMSG = r"<isonline>(.*)</isonline>"
TESTURL = "http://www.baidu.com/"
LOGINURL = "http://10.28.102.14/eportal/webgateuser.do?method=login_ajax_pure_internet"
REFRESHURL = "http://10.28.102.14/eportal/webgateuser.do?method=refresh&userIndex=9a5552c4aceb923538eb4101cb9c553a_{userIp}_{username}"
LOGOUTURL = "http://10.28.102.14/eportal/user.do?method=logout&rnd=0.8901102892123163"
LOGINSUCCESSURL = "http://10.28.102.14/eportal/webgatemode/loginsuccess_pure_internet.jsp"
INTERVAL = 1 # 跟服务器刷新频率
RELOGINFLAG = True # 被迫下线,重新拨号
RUNNING = False # 运行状态
headers = {
'Use-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
}
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
def __init__(self, interval=1, re_login_flag=True, username=None, password=None):
"init"
self.INTERVAL = interval
self.username = username
self.password = password
self.RELOGINFLAG = re_login_flag
def start(self):
# 开始启动服务
(code, msg) = self.login()
print msg
if code:
self.RUNNING = True
self.flush() # 保持在线
else:
self.RUNNING = False
self.stop()
def stop(self, *args):
self.RUNNING = False
(code, msg) = self.logout()
if code: # 计算秒数
print msg, 's'
else:
print msg
exit(1)
def login(self):
print 'login...'
headers = self.headers
opener = self.opener
# 使用百度,获取登录页面
try:
req1 = urllib2.Request(url=self.TESTURL, headers=headers)
resp1 = opener.open(req1)
loginurl = resp1.geturl()
except urllib2.URLError, e:
print e
return (False, str(e))
else:
# print loginurl, self.TESTURL
if loginurl == self.TESTURL:
mesg = 'You have logined\nApplication exit.'
return (False, mesg)
else:
page = resp1.read()
loginurl = re.match(self.REGEXLOGINURL, page, re.I)
loginurl = ''.join(loginurl.groups())
# 在登录页面上获取一些新信息(这里还未登录)
try:
req2 = urllib2.Request(url=loginurl, headers=headers)
resp2 = opener.open(req2).read()
except Exception, e:
print e
return (False, str(e))
else:
parse = RJLoginHTMLParser()
parse.feed(resp2.decode('utf-8'))
form = parse.form
form["username"] = form["usernameHidden"] = self.username
form["pwd"] = self.password
# 这里设置刷新链接URL
self.REFRESHURL.format(userIp=form["userIp"], username=form["username"])
# 包装数据
postdata = urllib.urlencode(form)
# 这里发送用户信息去登录
try:
req3 = urllib2.Request(url=self.LOGINURL, headers=headers, data=postdata)
resp3 = opener.open(req3)
except Exception, e:
return (False, str(e))
else:
# print resp3.geturl()
if resp3.geturl() == self.LOGINSUCCESSURL:
return (True, 'login successfully!')
else:
return (False, 'login failed! You maybe input wrong password.')
def logout(self):
print 'logout...'
# 下线
try:
req = urllib2.Request(url=self.LOGOUTURL, headers=self.headers)
resp = self.opener.open(req).read()
except Exception, e:
print e
return(False, str(e))
else:
return(True, resp) # resp中有上网的秒数
def flush(self):
# 定时刷新
# print 'flush...'
try:
req = urllib2.Request(url=self.REFRESHURL, headers=self.headers)
resp = self.opener.open(req)
page = resp.read()
except Exception, e:
print e
self.stop()
else:
rlt = re.findall(self.REGEXLOGOUTMSG, page, re.I)
t = threading.Timer(self.INTERVAL, self.flush, ())
if rlt and rlt[0] == "false":
print '>>> Your account has logined another place.'
if self.RELOGINFLAG:
print '>>> Start again...'
self.start()
else:
self.stop()
elif self.RUNNING: # 没有被迫下线,并且还处于运行状态
t.start()
if __name__ == '__main__':
cfg = ConfigParser.ConfigParser()
cfg.read("ruijieweb.ini")
try:
username = cfg.get("account", "username")
password = cfg.get("account", "password")
interval = cfg.getint("system", "interval")
re_login_flag = cfg.get("system", "re_login_flag")
except ConfigParser.NoSectionError, e:
with open('ruijieweb.ini', 'w') as f:
f.write('''[account]\nusername = \npassword = \n\n[system]\ninterval = 1 \t\t;刷新频率\nre_login_flag=True \t\t;被迫下线是否重新连接''')
print '>>> Please input informaiton in ruijieweb.ini and run again.'
exit(1)
if username and password:
print username
# 清除用户信息
cfg.set("account", "username", "")
cfg.set("account", "password", "")
cfg.write(open('ruijieweb.ini', 'wb'))
print ">>> Clear your username and password."
else:
print '>>> Please input username and password in ruijieweb.ini.'
exit(1)
rjw = RuijieWeb(username=username, password=password, interval=interval, re_login_flag=re_login_flag)
rjw.start()
while True:
print "\nIf you want to EXIT, you can Ctrl+c or input exit/quit/q.\n"
t = raw_input(">>> ")
if t.lower() in ['exit', 'quit', 'q']:
rjw.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment