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

相关文章

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、