通过Python调用OpenStack 的RESTful API

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

实际上是加入了novaclient 的库

root@ubuntu:~# ll /usr/lib/python2.7/dist-packages/novaclient/
auth_plugin.py       base.pyc             crypto.py            exceptions.pyc       __init__.py          service_catalog.py   shell.pyc            utils.pyc            
auth_plugin.pyc      client.py            crypto.pyc           extension.py         __init__.pyc         service_catalog.pyc  tests/               v1_1/                
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 即可,下面贴出一些例子

一,通过认证

def curl_keystone():
    url = 'http://192.168.12.1:35357/v2.0/tokens'
    values = {"auth":{"passwordCredentials":{"username":"admin","password":"password"},"tenantName":"admin"}}
    params = json.dumps(values)
    headers = {"Content-type":"application/json","Accept": "application/json"}
    req = urllib2.Request(url, params, headers)
    response = urllib2.urlopen(req)
    data = response.read()
    ddata=json.loads(data)
    token = ddata['access']['token']['id']
    return token

二,查询 IP

def curl_nova_addr(id):
    """
       :param id: vm id
       :Restore vm ip address.
    """
    xtoken = curl_keystone()
    url = 'http://192.168.12.1:8774/v2/2996e46c2519415d8de2b141d6c607ba/servers/'+id
    headers = {"Content-type":"application/json","Accept": "application/json"}
    req = urllib2.Request(url)
    req.add_header('X-Auth-Token',xtoken)
    response = urllib2.urlopen(req)
    data = response.read()
    ddata=json.loads(data)
    net = ddata['server']['addresses']['sharednet1']
    addr = net[0]['addr']
    return addr

三,通过name 查询id

def curl_nova_id(name):
    """
       :param name: Something to name the server.
       :Restore vm id.
    """
    ID=""
    xtoken = curl_keystone()
    url = 'http://192.168.12.1:8774/v2/2996e46c2519415d8de2b141d6c607ba/servers'
    headers = {"Content-type":"application/json","Accept": "application/json"}
    req = urllib2.Request(url)
    req.add_header('X-Auth-Token',xtoken)
    response = urllib2.urlopen(req)
    data = response.read()
    ddata=json.loads(data)
    list=ddata['servers']
    print len(list)
    print list
    for i in list:
       if(i['name'] == name):
           ID= i['id']
    return ID

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

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

你可能感兴趣的:(api,api,openstack,Restful,urllib2)