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 client

MBBToken = ''
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 MBBToken
    global MBBSessionID
    global servernonce
    global salt
    global iterations
    global ClientProof
    global ServerProof
    global serversignature
    global rsapubkeysignature
    global rsan
    global rsae
    
    print(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 False

    node_text_temp = {}
    if not kwargs:
        pass
    else:
        xmldoc = ET.parse(restful_file)
        for key in kwargs:
            node = xmldoc.find('./%s' % key.replace('_', '/'))
            node_text_temp[key] = node.text
            node.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:
        pass
    else:
#---     恢复原来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 = tokenBack
    print(MBBToken)
    print('****************POST_info刷新token************************') 
    conn.close()
    time.sleep(0.5)
    if allurl.find('/device/control') != -1:
        PRINTI('重启操作,无需退出登录')
        logoutBack = True
    elif allurl.find('/api/user/password_scram') != -1:
        PRINTI('修改初始密码操作,无需退出登录')
        logoutBack = True
    else:
        logoutBack = Logout(host)
    if data_info.find(r'<response>OK</response>') < 0 and expect == True:
        return False
    elif data_info.find(r'<response>OK</response>') >= 0 and expect == False:
        return False
    else:
        return logoutBack

def Login(host, password):
    PRINTI("****************************Start Login()***************************************")
# ## GET_TOKEN Session Start
    _GetTokenSession(host)
# ## GET_TOKEN Session End
    time.sleep(0.5)
# ## 挑战登录 Start
    _ChallengeLogin(host)
# ## 挑战登录 End
    time.sleep(0.5)
# ## 认证登录 Start
    _AuthenticationLogin(host, password)
    time.sleep(0.5)
# ## 认证登录 End
    PRINTI("****************************End Login()***************************************")
    
def _GetTokenSession(host):
    global MBBToken
    global MBBSessionID
    global servernonce
    global salt
    global iterations
    global ClientProof
    global ServerProof
    global serversignature
    global rsapubkeysignature
    global rsan
    global rsae
    
    header = {
            "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 MBBToken
    global MBBSessionID
    global servernonce
    global salt
    global iterations
    global ClientProof
    global ServerProof
    global serversignature
    global rsapubkeysignature
    global rsan
    global rsae
    
    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,
    }
    
    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 False
    conn.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 = tokenBack
    print(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").text
    salt = data_info_xml.find("salt").text
    iterations = data_info_xml.find('iterations').text
    print('************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 MBBToken
    global MBBSessionID
    global servernonce
    global salt
    global iterations
    global ClientProof
    global ServerProof
    global serversignature
    global rsapubkeysignature
    global rsan
    global rsae
    
    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,
    }
    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 False
    xmldoc = ET.parse(restful_file)
    node = xmldoc.find('./finalnonce')
    node.text = servernonce
    node = xmldoc.find('./clientproof')
    node.text = ClientProof
    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="/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 = tokenBack
    print(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").text
    rsapubkeysignature = data_info_xml.find("rsapubkeysignature").text
    rsan = data_info_xml.find('rsan').text
    rsae = data_info_xml.find('rsae').text
    print('************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页面的参数,然后下发,达到修改参数的功能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值