python接口自动化: CAS系统验证,自动完成登录并获取token,遇到302请求重定向设置(requests模块 allow_redirects=False)即可

import requests
import re

 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()

 

posted @ 2019-03-10 21:31  wan了个蛋  阅读(3711)  评论(1编辑  收藏  举报