通过Python调用OpenStack 的RESTful API

版权声明: 专注于"GIS+"前沿技术的研究与交流,将云计算技术、大数据技术、容器技术、物联网与GIS进行深度融合,探讨"GIS+"技术和行业解决方案;文章允许转载,但必须以链接方式注明源地址,否则追究法律责任! https://blog.csdn.net/chinagissoft/article/details/50403718

使用openstack api 可用python sdk ,需要部署相应组件的命令客户端,例如请求nova,需要python-novaclient 

实际上是加入了novaclient 的库

 

 
  1. root@ubuntu:~# ll /usr/lib/python2.7/dist-packages/novaclient/

  2. auth_plugin.py base.pyc crypto.py exceptions.pyc __init__.py service_catalog.py shell.pyc utils.pyc

  3. auth_plugin.pyc client.py crypto.pyc extension.py __init__.pyc service_catalog.pyc tests/ v1_1/

  4. base.py client.pyc exceptions.py extension.pyc openstack/ shell.py utils.py v3/


如果请求glance,neutron 组件,同样需部署其组件的命令行客户端

 

为了避免部署,可以通过调用restful api 来实现, 了解     openstack restful api 

python 调用restful api 其实用了urllib2 来实现,这个库一般的系统都会自带,import urllib2 即可,下面贴出一些例子

一,通过认证

 

 
  1. def curl_keystone():

  2.     url = 'http://192.168.12.1:35357/v2.0/tokens'

  3.     values = {"auth":{"passwordCredentials":{"username":"admin","password":"password"},"tenantName":"admin"}}

  4.     params = json.dumps(values)

  5.     headers = {"Content-type":"application/json","Accept": "application/json"}

  6.     req = urllib2.Request(url, params, headers)

  7.     response = urllib2.urlopen(req)

  8.     data = response.read()

  9.     ddata=json.loads(data)

  10.     token = ddata['access']['token']['id']

  11.     return token


二,查询 IP

 

 

 
  1. def curl_nova_addr(id):

  2. """

  3. :param id: vm id

  4. :Restore vm ip address.

  5. """

  6. xtoken = curl_keystone()

  7. url = 'http://192.168.12.1:8774/v2/2996e46c2519415d8de2b141d6c607ba/servers/'+id

  8. headers = {"Content-type":"application/json","Accept": "application/json"}

  9. req = urllib2.Request(url)

  10. req.add_header('X-Auth-Token',xtoken)

  11. response = urllib2.urlopen(req)

  12. data = response.read()

  13. ddata=json.loads(data)

  14. net = ddata['server']['addresses']['sharednet1']

  15. addr = net[0]['addr']

  16. return addr


三,通过name 查询id

 

 

 
  1. def curl_nova_id(name):

  2. """

  3. :param name: Something to name the server.

  4. :Restore vm id.

  5. """

  6. ID=""

  7. xtoken = curl_keystone()

  8. url = 'http://192.168.12.1:8774/v2/2996e46c2519415d8de2b141d6c607ba/servers'

  9. headers = {"Content-type":"application/json","Accept": "application/json"}

  10. req = urllib2.Request(url)

  11. req.add_header('X-Auth-Token',xtoken)

  12. response = urllib2.urlopen(req)

  13. data = response.read()

  14. ddata=json.loads(data)

  15. list=ddata['servers']

  16. print len(list)

  17. print list

  18. for i in list:

  19. if(i['name'] == name):

  20. ID= i['id']

  21. return ID

 

知道了如何通过urllib2 发送请求的方式,就可以轻松调用openstack 了

更多 restful api 的使用,请参考  http://developer.openstack.org/api-ref-compute-v2.1.html  ,包括了各个组件的 restful api  详解

你可能感兴趣的:(通过Python调用OpenStack 的RESTful API)