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开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Python中图片与PDF识别文本(OCR)的全面指南

《Python中图片与PDF识别文本(OCR)的全面指南》在数据爆炸时代,80%的企业数据以非结构化形式存在,其中PDF和图像是最主要的载体,本文将深入探索Python中OCR技术如何将这些数字纸张转... 目录一、OCR技术核心原理二、python图像识别四大工具库1. Pytesseract - 经典O

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.