urllib2 调用salt restapi

1获取token

#_*_coding:utf8_*_
import urllib2
import json

def get_token():
    url='http://10.20.32.86:8000/login'
    #http头这个就不介绍了
    headers ={"Content-type":"application/json","Accept": "application/json"}
    #参数
    params=json.dumps(
              {"eauth":"pam","username":"salt","password":"salt"})
    #这里并不是真的开始访问而是将信息组合起来
    req = urllib2.Request(url,params,headers)
    #这才是正真打开web页面
    respones = urllib2.urlopen(req)
    result=json.loads(respones.read())
    #获取salt token
    token=result['return'][0]['token']
    return token

2,设置http头携带token就可以了。

有了这个值就可以做任何事情了

调用salt模块

url='http://10.20.32.86:8000'
#X-Auth-Token: 这个头就是验证头,值就是刚才获取的token,这样就有权访问api了
headers ={"Content-type":"application/json","Accept": "application/json","X-Auth-Token":get_token()}

#fun 就是模块的名字和方法名字。
#kwarg 传递给方法的参数
#剩下的地方就是固定的了
body=json.dumps({
    "client": "local",
    "fun": "cinders.create_volumes",
    "tgt": "master-minion",
    "kwarg": {
      "provider_name": "test_opss",
      "driver_name":"nova",
      "size":1,
      "name":None,
      "description":None,
      "source_volid":None,
      "volume_type":None,
      "availability_zone":"nova",
      "imageRef":None,
      "source_replica":None,
      "consistencygroup_id":None,
      "multiattach":False,
      "snapshot_id":None
    }
})
req = urllib2.Request(url,body,headers)
respones = urllib2.urlopen(req)
result=json.loads(respones.read())
print result

 

posted @ 2016-11-01 17:06  MKY-门可意  阅读(627)  评论(0编辑  收藏  举报