通过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()