python接口自動化: CAS系統驗證,自動完成登陸並獲取token,遇到302請求重定向設置(requests模塊 allow_redirects=False)便可

import requests
import rephp

 1 import requests
 2 import re 
 3 
 4 class Crm_token(object):
 5     try:
 6         username=int(input("請輸入登陸手機號:\n"))
 7         password=input("請輸入登陸密碼:\n")
 8     except Exception as error:
 9         print("登陸信息輸入錯誤,錯誤信息%s"%(error))
10     def __init__(self):
11         self.url_login_in='http://xxxx'
12         self.login_server='http://xxx/cas/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.Imh0dHA6XC9cLzQ3LjEwNi4xNzguNDk6ODA4MlwvIg.8HSZHPyW7byY-MOVtFhdsiy_cpigL3RcStk9hGa8Su8'
13         self.return_url="http://xxxx/?return_url=xxx/"
14     def get_token(self,username=username,password=password):
15         headers_check_login={"Content-Type":"application/x-www-form-urlencoded"}
16         url_check_login='http://xxxx/Auth/checkLogin' #用戶名密碼驗證接口
17         check_login_data='username=%d&password=%s'%(username,password)
18         request_check_login=requests.post(url=url_check_login,headers=headers_check_login,data=check_login_data)
19         response_login_message=request_check_login.json()
20         # print(response_login_message)
21         if response_login_message['msg'] == '成功' and response_login_message['code']==200:
22             print('begin---login---')
23             try:
24                 session=requests.Session() #創建session會話
25                 headers1={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3493.3 Safari/537.36",
26                 "Referer":self.return_url,"Content-Type":'application/x-www-form-urlencoded'}
27                 url_login_1=self.url_login_in+'/CAS_server/login?action=getlt&service=%s&callback=jQuery33105752563290575323_1551706407492&_=1551706407493'%(self.login_server)
28                 request1=session.request("GET",url=url_login_1,headers=headers1,data=None) #登陸前動態參數獲取url
29                 response1=request1.text
30                 get_shouquan_str1=eval(re.search('{.*}',response1).group()) #匹配出字典內的內容並用eval方法將str轉換爲dict
31                 get_lt=get_shouquan_str1['lt'] #提取受權參數1
32                 get_execution=get_shouquan_str1['execution'] #提取受權參數2
33                 cookies_login_1=request1.cookies.get_dict() #獲取cookie:JSESSIONID
34                 seesionId=cookies_login_1['JSESSIONID']
35                 requestSeesionId=str('JSESSIONID='+seesionId) #拼接爲請求可用的cookie值
36                 # print(requestSeesionId)
37                 # print(get_lt)
38                 # print(get_execution)    
39                 headers2={"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
40                 "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3493.3 Safari/537.36",
41                 "Content-Type":'application/x-www-form-urlencoded',"Cookie":requestSeesionId,"Referer":self.return_url}
42                 url_login_2=self.url_login_in+'/CAS_server/login?service=%s'%(self.login_server) 
43                 #請求信息頭必須傳cookie,不然會一直返回登陸頁面
44                 login_data='lt=%s&execution=%s&_eventId=submit&username=%s&password=%s&submit=登陸'%(get_lt,get_execution,username,password)
45                 # login_data='lt=%s&execution=%s&_eventId=submit&username=%d&password=%s'%(get_lt,get_execution,username,password)
46                 #登陸body,將獲取到對的兩個動態參數也傳進去
47                 request2=session.post(url=url_login_2,headers=headers2,data=login_data.encode(),allow_redirects=False)
48                 #allow_redirects=False,禁止請求重定向:爲了獲取重定向url,requests模塊默認請求重定向
49                 # request2=session.post(url=url_login_2,headers=headers2,data=login_data.encode(),allow_redirects=True)
50                 response2=request2.text
51                 responseHeaders2=request2.headers #獲取reponse header
52                 # print(response2)
53                 # print(responseHeaders2)
54                 url_chongdingxiang_st=responseHeaders2["location"] #獲取重定向url
55                 requests3=session.get(url=url_chongdingxiang_st,headers=headers2,data=None,allow_redirects=False)
56                 response3=requests3.text
57                 responseHeaders3=requests3.headers
58                 php_session_cookie=responseHeaders3['Set-Cookie'] #獲取php_session
59                 php_session_id=re.search("(\w*\W*\w*)",php_session_cookie).group() #用正則匹配出所須要的php_session_id
60                 # print(php_session_id)
61                 # print(responseHeaders3)
62                 url_chongdingxiang_get_ticket=responseHeaders3['location']#獲取重定向url
63                 headers3={"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
64                 "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3493.3 Safari/537.36",
65                 "Content-Type":'application/x-www-form-urlencoded',"Set-Cookie":php_session_id,"Referer":self.return_url}
66                 requests4=session.get(url=url_chongdingxiang_get_ticket,headers=headers3,data=None,allow_redirects=False)
67                 response4=requests4.text
68                 responseHeaders4=requests4.headers
69                 # print(responseHeaders4)
70                 url_chongdingxiang_ticket=responseHeaders4['location'] #獲取重定向url
71                 requests5=session.get(url=url_chongdingxiang_ticket,headers=headers3,data=None,allow_redirects=False)
72                 response5=requests5.text
73                 responseHeaders5=requests5.headers
74                 # print(responseHeaders5)
75                 # print(response5)
76                 ticket_data=re.search('(ticket.*)',url_chongdingxiang_ticket).group() #用正則匹配出ticket以及對應的value
77                 headers4={"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
78                 "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3493.3 Safari/537.36",
79                 "Content-Type":'application/x-www-form-urlencoded',"Referer":url_chongdingxiang_ticket} #將headers來源地址更改成url_chongdingxiang_ticket
80                 url_get_token='http://xxxx/Auth/login' #登陸接口
81                 requests_get_token=session.post(url=url_get_token,headers=headers3,data=ticket_data)
82                 reponse6=requests_get_token.json()
83                 crm_system_token=reponse6['data']['token']
84                 print('login---susscess---')
85                 print('當前登錄手機號爲:%s,token爲:\n%s'%(username,crm_system_token))
86                 return crm_system_token
87             except BaseException as error:
88                 print('登陸錯誤,token獲取失敗,\n錯誤信息:%s'%(error))
89         else:
90             print(response_login_message)
91 
92 
93 if __name__=="__main__":
94     tk=Crm_token()
95     tk.get_token()
相關文章
相關標籤/搜索