使用Python Requests实现OpenDaylight对
2017-08-22 本文已影响95人
ljyfree
之前分享的《如何用postman控制ODL查看和下发流表》毕竟是要操作postman,不方便集成到代码中。借助Python的Requests库,可以方便的完成调用ODL Restful API的PUT操作。
目标
- 通过ODL,在OVS上添加如下的一个group
# ovs-ofctl dump-groups br0 -O openflow13
OFPST_GROUP_DESC reply (OF1.3) (xid=0x2):
group_id=1,type=all,bucket=weight:0,set_field:00:00:00:00:00:05->eth_dst,set_field:192.168.100.105->ip_dst,output:5,bucket=weight:0,set_field:00:00:00:00:00:06->eth_dst,set_field:192.168.100.106->ip_dst,output:6,bucket=weight:0,set_field:00:00:00:00:00:07->eth_dst,set_field:192.168.100.107->ip_dst,output:7
准备工作
- 运行ODL的Beryllium-SR3版本
- Python 2.7
- Requests :requests==2.2.1
- 通过YangUI填写group所需信息,做PUT操作,抓取PUT的报文
- 获取对应的Json字段
- 将JSON字段存入文件,供后面调用
$ cat odl.json
{
"group": [
{
"group-type": "group-all",
"group-id": "1",
"buckets": {
"bucket": [
{
"bucket-id": "0",
"action": [
{
"order": "0",
"set-field": {
"ethernet-match": {
"ethernet-destination": {
"address": "00:00:00:00:00:05"
}
}
}
},
{
"order": "1",
"set-field": {
"ipv4-destination": "192.168.100.105/32"
}
},
{
"order": "2",
"output-action": {
"output-node-connector": "5"
}
}
]
},
{
"bucket-id": "1",
"action": [
{
"order": "0",
"set-field": {
"ethernet-match": {
"ethernet-destination": {
"address": "00:00:00:00:00:06"
}
}
}
},
{
"order": "1",
"set-field": {
"ipv4-destination": "192.168.100.106/32"
}
},
{
"order": "2",
"output-action": {
"output-node-connector": "6"
}
}
]
},
{
"bucket-id": "2",
"action": [
{
"order": "0",
"set-field": {
"ethernet-match": {
"ethernet-destination": {
"address": "00:00:00:00:00:07"
}
}
}
},
{
"order": "1",
"set-field": {
"ipv4-destination": "192.168.100.107/32"
}
},
{
"order": "2",
"output-action": {
"output-node-connector": "7"
}
}
]
}
]
}
}
]
}
代码实现
- 关键点有两个
- 'Content-Type':'application/json'
- Basic Authentication: admin/admin
- 下面是参考代码
$ cat odl_http.py
#!/usr/bin/env python
import requests
from requests.auth import HTTPBasicAuth
def http_post(url,jstr):
url= url
headers = {'Content-Type':'application/json'}
resp = requests.put(url,jstr,headers=headers,auth=HTTPBasicAuth('admin', 'admin'))
return resp
if __name__ == "__main__":
url = 'http://10.10.11.80:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:128983912192/flow-node-inventory:group/1'
with open('odl.json') as f:
jstr = f.read()
resp = http_post(url,jstr)
print resp.content
- 抓取报文如下
- 在OVS查看,期望的group添加成功
本文首发于SDNLAB http://www.sdnlab.com/19749.html