本文主要是介绍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请求 修改页面参数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!