本篇博文主要介绍在已经完成搭建OpenDayLight的系统上使用Python3调用RestAPI来完成下发流表的操作。
要点
1.使用了Python3的Httplib2库来完成http请求的操作。
2.调用了OpenDayLight 北向接口的RestAPI进行的流表操作,使用了HTTP PUT方法进行的流表上传操作。
3.采用了Http协议的Basic Auth的方式进行的用户认证,认证用的用户名密码需要有OpenDayLight的 Network-Admin权限。
样例代码如下(在本样例中发送的流表项的功能是更改ToS的参数,使用的流表的命名规则为flow_时间戳):
import httplib2
import time
class OdlUtil:
url =
''
def __init__(self, host, port):
self.url =
'http://' + host +
':' + str(port)
'''
流表规则下发
'''
def install_flow(self, node, ip_from, ip_to, container_name='default',username="admin", password="admin"):
http = httplib2.Http()
http.add_credentials(username, password)
headers = {
'Accept':
'application/json'}
flow_name =
'flow_' + str(int(time.time()*
1000))
body =
'{"installInHw":"true","name":"' + flow_name +
'",' \
'"node":{"id":"' + node +
'","type":"OF"},' \
'"priority":"500","etherType":"0x800",' \
'"nwSrc":"' + ip_from +
'","nwDst":"' + ip_to +
'","actions":["SET_NW_TOS=63"]}'
'''
********* Body里面所有可选的参数 ***********
<?xml version="1.0" encoding="UTF-8"?>
<flowConfig>
<tpSrc>...</tpSrc>
<protocol>...</protocol>
<vlanId>...</vlanId>
<node>
<type>...</type>
<id>...</id>
</node>
<vlanPriority>...</vlanPriority>
<idleTimeout>...</idleTimeout>
<priority>...</priority>
<ingressPort>...</ingressPort>
<tosBits>...</tosBits>
<name>...</name>
<hardTimeout>...</hardTimeout>
<dlDst>...</dlDst>
<installInHw>...</installInHw>
<etherType>...</etherType>
<actions>...</actions>
<actions>...</actions>
<!--...more "actions" elements...-->
<cookie>...</cookie>
<dlSrc>...</dlSrc>
<nwSrc>...</nwSrc>
<nwDst>...</nwDst>
<tpDst>...</tpDst>
</flowConfig>
'''
headers = {
'Content-type':
'application/json'}
print(body)
response, content = http.request(uri=self.url +
'/controller/nb/v2/flowprogrammer/' + container_name +
'/node/OF/' + str(node) +
'/staticFlow/' + flow_name, body=body, method=
'PUT',headers=headers)
print(content.decode())
调用
odl = OdlUtil(
'127.0.0.1',
'8080')
odl.install_flow(
'00:00:00:00:00:00:00:02',
'10.0.0.1',
'10.0.0.3')
返回结果:
成功的情况下返回:Success
转载请注明原文地址: https://ju.6miu.com/read-679213.html