Python3通过cookie登录
import json,urllib.request,urllib.parse,http.cookiejar url_base = 'https://spam.forti.com/api/v1' url_admin = 'AdminLogin' data = {'name' : 'admin', 'password' : 'password' } headers = {'Content-Type':'application/json','User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} postdata = bytes(json.dumps(data),'utf8') #post json格式数据 print(postdata) request = urllib.request.Request(url_base + '/' + url_admin,postdata,headers) #将cookie内容保存到文件 cookie_file = 'E:\\test\\spam_cookie.txt' cookie=http.cookiejar.MozillaCookieJar(cookie_file) handler=urllib.request.HTTPCookieProcessor(cookie) opener=urllib.request.build_opener(handler) #登录获取cookie url_login = 'https://spam.yxqiche.com/api/v1/AdminLogin' result=opener.open(request) #保存cookie内容到txt文件 cookie.save(ignore_discard=True,ignore_expires=True) #访问其他url获取数据 url_sys = 'https://spam.forti.com/api/v1/SysStatusSysinfo/' res = opener.open(url_sys) reponse = res.read() content = json.loads(reponse.decode('utf8')) print(content)
#如果提示ssl certificate_verify_failed,则为opener添加额外的handler,不检查ssl证书
#将cookie内容保存到文件 cookie_file = '/data1/scripts/spam_cookie.txt' cookie=http.cookiejar.MozillaCookieJar(cookie_file) #如果提示ssl certificate_verify_failed,则为opener添加额外的handler,不检查ssl证书 context = ssl._create_unverified_context() https_handler = urllib.request.HTTPSHandler(context=context) handler=urllib.request.HTTPCookieProcessor(cookie) opener=urllib.request.build_opener(handler,https_handler)
参考:https://www.cnblogs.com/piwefei/p/11188071.html
https://www.cnblogs.com/lincappu/p/12762771.html
https://cloud.tencent.com/developer/article/1742483
https://blog.csdn.net/weixin_39867662/article/details/111427417