學校校園網的網絡連接有免費連接和收費連接兩種類型,可想而知收費連接瀏覽體驗更佳,比如可以訪問更多的網站。之前收費地址只能開通包月服務才可使用,后來居然有了每個月60小時的免費使用收費地址的優惠。但是,一旦連接了收費地址而忘記及時斷開,60小時會很快用完。
為了節約收費地址的使用時間,采用如下方案:每隔1個小時,都在本機上斷開校園網的收費連接,同時連接免費連接,這樣,每次手動連接收費連接之后,最多使用1個小時,就會被自動斷開。
1. python實現連接/斷開網絡連接
通過執行python腳本,實現訪問 its.pku.edu.cn 並設置連接/斷開。
通過fiddler抓包,分析從訪問 its.pku.edu.cn,到填寫賬號密碼,再到最后登陸成功的過程中,瀏覽器和網關交互的http request和response。
python代碼實現
#!/usr/bin/env python """python crawler """ #encoding:UTF-8 import requests import sys def login(type): """login work""" headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36'} s = requests.Session() s.headers = headers post_data = {'username': 'username', 'password': 'password', 'iprange': type} r = s.post('https://its.pku.edu.cn/cas/webLogin', data=post_data, verify=False) print "log in, status = %s" % r.status_code def logout(type): """logout work""" headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36'} s = requests.Session() s.headers = headers post_data = {'username': 'username', 'password': 'password', 'iprange': 'no'} s.post('https://its.pku.edu.cn/cas/webLogin', data=post_data, verify=False) #to logout!! r = s.get('https://its.pku.edu.cn/netportal/ITSipgw?cmd=close&type=%s&sid=478' % type, verify=False, headers=headers) print "log out, status = %s" % r.status_code if __name__ == '__main__': if len(sys.argv) != 2: print "usage <option: 1 (connect free), 2 (connect global), 3 (disconnect this computer), 4 (disconnect all), 5(disconnect this computer and connect free)" exit(1) option = int(sys.argv[1]) if option == 1: print "try to connect free" login('no') elif option == 2: print "try to connect global" login('yes') elif option == 3: print "try to disconnect self" logout('self') elif option == 4: print "try to disconnect all" logout('all')
2. 每1小時自動執行
linux下比較方便,直接設置 crontab即可。
windows下可以設置機器的自動任務計划,具體步驟如下:
(1)開始->所有工具->windows管理工具->任務計划程序
(2)創建任務
(2.1)常規 ——填寫程序名稱(隨意)
(2.2)觸發器 ——新建,設置為每天固定時間開始執行,每隔一個小時重復一次
(2.3)操作 ——新建,設置為執行python腳本,且設置正確的命令行參數 (包括python腳本路徑和參數5)