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

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互