Python request模块 携带cookie

# _*_coding:utf-8 _*_
import time
import requests
import json
import sys
import random
import string
import datetime


def login_device(user_name, passwd, url_addr, property_group):
    seesion = requests.session()
    headers = {'content-type': 'application/json;charset=UTF-8','User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0'}
    body = {
         "password": passwd,
         "username": user_name}
    body = json.dumps(body)
    lonin_url = 'https://%s/shterm/api/authenticate' %(url_addr)
    res = seesion.post(lonin_url, body, headers=headers, verify=False)
    #print res
    if res.status_code != 200:
        print 'login fliad:{}'.format(url_addr)
        sys.exit(1)
    print 'login secceed...'
    res_info = json.loads(res.text)
    token_info = res_info.get('ST_AUTH_TOKEN') # 获取cookie
    print "gert token: %s" %token_info
    if not token_info:
        print 'not get token'
        sys.exit(1)
    token_data = {'st-auth-token':token_info}
    get_url = 'https://%s/shterm/api/resGroup/?search=%s'%(url_addr, property_group)
    group_res = seesion.get(get_url, cookies=token_data, verify=False)
    if group_res.status_code != 200:
        print "no property group"
    print "获取资产组ID..."
    property_grouq_A = json.loads(group_res.text)
    if property_grouq_A.get('content'):
        print "+++++++++++++++++++++++"
        group_id = property_grouq_A.get('content')[0].get('id')
        print "资产组ID:",group_id
        print "+++++++++++++++++++++++"
    else:
        print "查询资产组ID不存在...."
        group_id = 1
    return group_id
if __name__ == '__main__':
    #property_group = 'test01'
    group_id = login_device(user_name, passwd, url_addr, property_group)
   

 

posted @ 2020-07-16 14:25  QQmini  阅读(775)  评论(0编辑  收藏  举报