Restful python 下发http请求 修改页面参数

2023-12-12 15:59

本文主要是介绍Restful python 下发http请求 修改页面参数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.通过下发restful api修改xml文件,从而改变页面属性
xml格式:

<?xml version='1.0' encoding='utf-8'?>
<request>
<a>1</a>
</request>

2.编写restful接口

from http import clientMBBToken = ''
MBBSessionID = ''
servernonce = ''
salt = ''
iterations = ''
ClientProof = ''
ServerProof = ''
serversignature = ''
rsapubkeysignature = ''
rsan = ''
rsae = ''#myapi:请求格式 /a/b/c 根据url链接确定
#host:url的一部分
#expect:预期下发是否成功
def POST_info(self, myapi, host, expect=True, **kwargs):global MBBTokenglobal MBBSessionIDglobal servernonceglobal saltglobal iterationsglobal ClientProofglobal ServerProofglobal serversignatureglobal rsapubkeysignatureglobal rsanglobal rsaeprint(myapi)#登陆页面Login(host)conn = client.HTTPConnection(host)header = { "Content-Type": "application/json;charset=UTF-8","Connection": "keep-alive","Accept": "application/json, text/javascript, */*; q=0.01","Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4","X-Requested-With": "XMLHttpRequest","Accept-Encoding": "gzip, deflate, peerdist","User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36","__requestverificationtoken": MBBToken,"Cookie": MBBSessionID,}#读取xml文件restful_file = getResourcePath(myapi + '.xml', isdir=False)   PRINTI(logWrap(restful_file))if restful_file == None:PRINTE(logWrap('%s 文件不存在,请检查' % restful_file))return Falsenode_text_temp = {}if not kwargs:passelse:xmldoc = ET.parse(restful_file)for key in kwargs:node = xmldoc.find('./%s' % key.replace('_', '/'))node_text_temp[key] = node.textnode.text = kwargs[key]xmldoc.write(restful_file, encoding="utf-8", xml_declaration=True)with open(restful_file) as file_object:bodydata = file_object.read()PRINTI(bodydata)   conn.set_debuglevel(1)conn.request(method="POST", url=allurl, body=bodydata, headers=header)responseBack = conn.getresponse()data = responseBack.read()data_info = data.decode("utf-8")print(data_info)if not kwargs:passelse:
#---     恢复原来xml内容xmldoc = ET.parse(restful_file)for key in kwargs:node = xmldoc.find('./%s' % key.replace('_', '/'))node.text = node_text_temp[key]xmldoc.write(restful_file, encoding="utf-8", xml_declaration=True)
#---     恢复原来xml内容tokenBack = responseBack.getheader('__RequestVerificationToken')print('\n****************POST_info刷新token************************')MBBToken = tokenBackprint(MBBToken)print('****************POST_info刷新token************************') conn.close()time.sleep(0.5)if allurl.find('/device/control') != -1:PRINTI('重启操作,无需退出登录')logoutBack = Trueelif allurl.find('/api/user/password_scram') != -1:PRINTI('修改初始密码操作,无需退出登录')logoutBack = Trueelse:logoutBack = Logout(host)if data_info.find(r'<response>OK</response>') < 0 and expect == True:return Falseelif data_info.find(r'<response>OK</response>') >= 0 and expect == False:return Falseelse:return logoutBackdef Login(host, password):PRINTI("****************************Start Login()***************************************")
# ## GET_TOKEN Session Start_GetTokenSession(host)
# ## GET_TOKEN Session Endtime.sleep(0.5)
# ## 挑战登录 Start_ChallengeLogin(host)
# ## 挑战登录 Endtime.sleep(0.5)
# ## 认证登录 Start_AuthenticationLogin(host, password)time.sleep(0.5)
# ## 认证登录 EndPRINTI("****************************End Login()***************************************")def _GetTokenSession(host):global MBBTokenglobal MBBSessionIDglobal servernonceglobal saltglobal iterationsglobal ClientProofglobal ServerProofglobal serversignatureglobal rsapubkeysignatureglobal rsanglobal rsaeheader = {"Content-Type": "application/json;charset=UTF-8","Accept": "application/json, text/javascript, */*; q=0.01","Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4","X-Requested-With": "XMLHttpRequest","Accept-Encoding": "gzip, deflate, peerdist","__requestverificationtoken": MBBToken,"Cookie": MBBSessionID,}conn = client.HTTPConnection(host)conn.set_debuglevel(1) #CONST.CONSTANT.TOKEN_URL是常量,根据你自己的情况改动conn.request(method="GET", url=CONST.CONSTANT.TOKEN_URL, headers=header)responseBack = conn.getresponse()data = responseBack.read()data_info = data.decode("utf-8")
#     print('************data_info*****************')
#     print(data_info)
#     print('************data_info*****************')cookieBack = responseBack.getheader('Set-Cookie')print(data_info.split('\n')[3].strip())MBBToken = data_info.split('\n')[3].strip().split('content="')[1][:-2]print('**************MBBToken*******************')print(MBBToken)print('**************MBBToken*******************')print(cookieBack.strip())MBBSessionID = cookieBack.strip()print('************MBBSessionID*****************')print(MBBSessionID)print('************MBBSessionID*****************')conn.close() <?xml version="1.0" encoding="UTF-8"?>
<request><username>admin</username><firstnonce>ca29b2a8c5c198e87aeb6503f6b1a18a8f0ab7a020b1cef2e6f3f8c3c49f1df1</firstnonce><mode>1</mode>
</request>def _ChallengeLogin(host): global MBBTokenglobal MBBSessionIDglobal servernonceglobal saltglobal iterationsglobal ClientProofglobal ServerProofglobal serversignatureglobal rsapubkeysignatureglobal rsanglobal rsaeheader = { "Content-Type": "application/json;charset=UTF-8","Connection": "keep-alive","Accept": "application/json, text/javascript, */*; q=0.01","Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4","X-Requested-With": "XMLHttpRequest","Accept-Encoding": "gzip, deflate, peerdist","User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36","__requestverificationtoken": MBBToken,"Cookie": MBBSessionID,}conn = client.HTTPConnection(host)restful_file = getResourcePath('challenge_login.xml', isdir=False)   PRINTI(logWrap(restful_file))if restful_file != None:with open(restful_file) as file_object:bodydata = file_object.read()PRINTI(bodydata)else:PRINTE(logWrap('%s 文件不存在,请检查' % restful_file))return Falseconn.set_debuglevel(1)conn.request(method="POST", url="/api/user/challenge_login", body=bodydata, headers=header)responseBack = conn.getresponse()data = responseBack.read()data_info = data.decode("utf-8")tokenBack = responseBack.getheader('__RequestVerificationToken')print('\n****************_ChallengeLogin刷新token************************')MBBToken = tokenBackprint(MBBToken)print('****************_ChallengeLogin刷新token************************')conn.close()print('\n挑战登录返回:\n%s' % data_info)data_info_xml = ET.fromstring(data_info)servernonce = data_info_xml.find("servernonce").textsalt = data_info_xml.find("salt").textiterations = data_info_xml.find('iterations').textprint('************servernonce*****************')print(servernonce)print('************servernonce*****************')print('***************salt*******************')print(salt)print('***************salt*******************')print('************iterations*****************')print(iterations)print('************iterations*****************')<?xml version='1.0' encoding='utf-8'?>
<request><clientproof>1c01a49f85cc39afa5f94fbd7e3d096dcbb3217e28fb5e2730f935d6bd838353</clientproof><finalnonce>ca29b2a8c5c198e87aeb6503f6b1a18a8f0ab7a020b1cef2e6f3f8c3c49f1df1dv0OPhk7VraA4ZUbYeYrIpk2hElS0Ive</finalnonce>
</request>def _AuthenticationLogin(host, password):global MBBTokenglobal MBBSessionIDglobal servernonceglobal saltglobal iterationsglobal ClientProofglobal ServerProofglobal serversignatureglobal rsapubkeysignatureglobal rsanglobal rsaeheader = { "Content-Type": "application/json;charset=UTF-8","Connection": "keep-alive","Accept": "application/json, text/javascript, */*; q=0.01","Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4","X-Requested-With": "XMLHttpRequest","Accept-Encoding": "gzip, deflate, peerdist","User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36","__requestverificationtoken": MBBToken,"Cookie": MBBSessionID,}conn = client.HTTPConnection(host)
#   jar包中返回的顺序和格式  return mClientProof + ":" + mServerProof;
#   getAllAlgorithmValue(String firstNonce, String serverNonce, String password登录密码, String salt,int iterations)# firstnonce 为 challenge_login.xml中的值firstnonce = "ca29b2a8c5c198e87aeb6503f6b1a18a8f0ab7a020b1cef2e6f3f8c3c49f1df1" 
#     password = VAR.Project.Config["var_xian"]["loginpassword"]PRINTI(logWrap(password))jarpath = os.path.join(VAR.Project.Path, r"aw/Restful/scramlib.jar")print(jarpath)command = "java -jar %s %s %s %s %s %d" % (jarpath, firstnonce, servernonce, password, salt, int(iterations))p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)outdata, errdata = p.communicate()result = "%s%s" % (outdata.decode("gb2312"), errdata.decode("gb2312"))print(result.strip())if p.returncode != 0:PRINTI(logWrap("exit code:%s, executing: %s" % (p.returncode, command)))p.terminate()ClientProof, ServerProof = result.strip().split(':')print('************ClientProof*****************')print(ClientProof)print('************ClientProof*****************')print('************ServerProof*****************')print(ServerProof)print('************ServerProof*****************')restful_file = getResourcePath('authentication_login.xml', isdir=False)   PRINTI(logWrap(restful_file))if restful_file == None:PRINTE(logWrap('%s 文件不存在,请检查' % restful_file))return Falsexmldoc = ET.parse(restful_file)node = xmldoc.find('./finalnonce')node.text = servernoncenode = xmldoc.find('./clientproof')node.text = ClientProofxmldoc.write(restful_file, encoding="utf-8", xml_declaration=True)with open(restful_file) as file_object:bodydata = file_object.read()PRINTI(bodydata)conn.set_debuglevel(1)    conn.request(method="POST", url="/api/user/authentication_login", body=bodydata, headers=header)responseBack = conn.getresponse()data = responseBack.read()data_info = data.decode("utf-8")tokenBack = responseBack.getheader('__RequestVerificationTokenone')print('\n****************_AuthenticationLogin刷新token************************')MBBToken = tokenBackprint(MBBToken)print('****************_AuthenticationLogin刷新token************************')cookieBack = responseBack.getheader('Set-Cookie')print('\n****************_AuthenticationLogin刷新SessionID************************')MBBSessionID = cookieBack.split(';')[0]print(MBBSessionID)print('****************_AuthenticationLogin刷新SessionID************************')conn.close()print('\n认证登录返回:\n%s' % data_info)data_info_xml = ET.fromstring(data_info)serversignature = data_info_xml.find("serversignature").textrsapubkeysignature = data_info_xml.find("rsapubkeysignature").textrsan = data_info_xml.find('rsan').textrsae = data_info_xml.find('rsae').textprint('************serversignature*****************')print(serversignature)print('************serversignature*****************')print('************rsapubkeysignature*****************')print(rsapubkeysignature)print('************rsapubkeysignature*****************')print('************rsan*****************')print(rsan)print('************rsan*****************')print('************rsae*****************')print(rsae)print('************rsae*****************')

3.下发报文
Restful.POST_info(self, ‘xml名称’, xml属性1=“20”, xml属性2=“1”)

备注:代码背景是修改产品WEB页面的参数,然后下发,达到修改参数的功能

这篇关于Restful python 下发http请求 修改页面参数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/485158

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON: