
正文
python-自动登录禅道
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
from bs4 import BeautifulSoup
import hashlib
import requests
import re
from tool.request_data_change_to_StrEncode import request_data_change_to_str
import os
import jsonclass zentao_login(object):
global file_login_info
file_login_info = './login_info.txt'#登录网页存放至本地,用于提取verifyRand def __init__(self):
self.data_to_str=request_data_change_to_str()
self.session = requests.session()
self.host = 'http://xxxx'
self.header={"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"} def md5_key(self,str):#md5加密
m = hashlib.md5()
b = str.encode(encoding='utf-8')
m.update(b)
return m.hexdigest() def login(self,user='admin',pw='sss',file=file_login_info):#登录
url=self.host+'/zentao/user-login.html'
content = self.session.get(url,headers = self.header)
with open(file,'w',encoding='utf-8') as file:#将网页保存到本地
file.write(content.text)
verifyRandstr=self.read_verifyRandstr()#获取登录字符串
password=self.md5_key(self.md5_key(pw)+verifyRandstr)#md5加密密码
login_url=self.host+'/zentao/user-login.html'
data=self.data_to_str.requestDataToStr_firefoxAndChrome('''account: admin
password: %s
passwordStrength: 1
referer: /zentao/
verifyRand: %s
keepLogin: 1'''%(password,verifyRandstr))
request_login=self.session.post(url=login_url,data=data,headers=self.header,allow_redirects=True)#登录
if "self.location='/zentao/" in request_login.text:
#判断登录是否成功,成功后将cookie写入文件
cookies = requests.utils.dict_from_cookiejar(request_login.cookies) #拿到所有的cookie
temp_str = ''#定义cookie字符串
# 获取sessionid,如果不保存至header,用requests直接请求会出错
session_str = 'zentaosid=' + request_login.cookies.values()[-1]
for key,value in cookies.items():
if (key=='zp' or key=='za' or key=='keepLogin'):
str='{}={};'.format(key,value)#拼接cookie,key/value
temp_str+=str#将拼接完成的cookie,添加至最终的cookie字符串
self.header['Cookie']=temp_str+session_str#将处理完成的cookie添加至请求header
with open('./zentao_header.txt','w',encoding='utf-8') as zentao_header:#将header写入至文件
zentao_header.write(repr(self.header))
elif "alert('登录失败,请检查您的用户名或密码是否填写正确。')" in request_login.text:
# 判断由于密码错误引起的登陆失败
raise Exception('密码错误,登录失败,请重试')
else:
# 判断由于其他情况引起的登录失败
raise Exception(request_login.text) def read_verifyRandstr(self,file=file_login_info):#匹配verifyRand
with open(file,'r',encoding='utf-8') as file_read:
login_html_info=file_read.read()
soup=BeautifulSoup(login_html_info,'lxml')
button=soup.find_all('input',attrs={'type': re.compile("hidden"),'id': re.compile("verifyRand")})[0]['value']
return button def load_header(self,user='admin',pw='test2019zentao',file='./zentao_header.txt'):
#测试cookie是否有效,有效的话就直接使用,无效就触发重新登录
'''这里遇到了一个问题,如果header里没有保存sessionid,那么用requests直接请求会出错,这时候需要用session请求才行,
如果header里保存了sessionid,那么用requests请求即可,当然用session请求也不会有问题,
所以最终还是把session保存进了header,与token认证还真不一样'''
try:#处理zentao_header.txt不存在的情况
with open(file,'r',encoding='utf-8') as header_info:
header=eval(header_info.read())
url_bug = self.host + '/zentao/bug-browse.json'
re_bug = requests.get(url=url_bug, headers=header)
if "self.location='/zentao/user-login-" in re_bug.text:
self.login(user, pw)
return header
except FileNotFoundError as error:
print(error,'执行登录')
self.login()
self.load_header()if __name__=="__main__":
zt=zentao_login()
# zt.login()
zt.load_header()






