【python2】restconf协议对接管理设备

通过http.client访问

import http.client
import base64
import datetime
import ssl
import socket 

socket.setdefaulttimeout(90)
ssl._create_default_https_context = ssl._create_unverified_context

HOSTARM   = "192.168.0.1"
PORT      = int(10000)
USER_NAME = 'restconf'
PASSWORD  = 'restconf'


DEFAULT_HEADER = {
                           "Cache-Control" : "no-cache,no-store",
                           "Connection"    : "Keep-Alive",
                            "Accept"       : "application/yang-data+xml",
                           "Content-Type"  : "application/yang-data+xml",
                           }
#python2
USERNAME_PASS = base64.b64encode(bytes('%s:%s' % (USER_NAME, PASSWORD))).decode()

#_RESTRICTED_SERVER_CIPHERS = 'DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:AES128-SHA256:DHE-RSA-AES128-SHA256:AES256-SHA256'
_RESTRICTED_SERVER_CIPHERS = "ALL"

def fix_header():
    headers = DEFAULT_HEADER.copy()
    headers['Authorization'] = 'Basic ' + USERNAME_PASS
    return headers

def send_request(method, url, body=""):
    context = ssl._create_default_https_context()
    context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
    httpClient = http.client.HTTPSConnection(HOSTARM, PORT, timeout=30, context=context)
    headers = fix_header()
    try:
        begin = datetime.datetime.now()
        httpClient.request(method, url, body, headers)
        response = httpClient.getresponse()

        resp_status = response.status
        resp_headers = response.getheaders()
        end = datetime.datetime.now()
        k = end - begin
        print("cost time:%s s" % k.total_seconds())
        print("status: " + str(resp_status) + "\nResponse Headers: " + str(resp_headers[3]))

        resp_str = response.read()
        #print(resp_str)

        httpClient.close()
        print("The Content-Length: " + str(len(resp_str)))
    except Exception as e:
        print('Restconf: send request faild.')
        print("ERROR, traceback:%s" % e)
        print(e.args)
        httpClient.close()
    return 0


def test():
    context="""<addr-object>
<elements>
<elem-id>1011</elem-id>
<address-ipv4>100.0.0.11/32</address-ipv4>
</elements>
</addr-object>
"""
    # send_request('POST', "/restconf/data/ietf-routing:routing", context)
    send_request('GET', "/restconf/data/ietf-routing:routing")
    return
if __name__ == '__main__':
    test()

通过requests访问

import requests
import re
from requests.packages import urllib3
import base64
urllib3.disable_warnings()


class restconf:
    def __init__(self,url,user,passwd):
        self.server = url
        self.user = user
        self.passwd = passwd
        self.header = {"Authorization": "Basic {}".format(base64.b64encode((user+":"+passwd).encode()).decode()),
                       "Content-Type": "application/yang-data+xml"
                      }

    def get_route(self):
        url = "{}/restconf/data/ietf-routing:routing".format(self.server)
        response = requests.get(url, headers=self.header,verify=False)
        xml = response.text
        print(url+'\n'+xml,response.status_code)

if __name__ == '__main__':
    wx = "https://1.1.1.1:10000"
    r = restconf(wx,'restconf','restconf')
    r.get_route()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值