上周需要用python访问vcloud上的资源,但是vcloud有个登录认证过程,需要将头信息加入到请求中,经过几番搜寻,终于找到解决方案。
参考地址:http://stackoverflow.com/questions/11395224/vcloud-director-org-user-authentication-for-restapi-in-python
我用用RESTClient的访问过程是:
1)先用POST:https://your_ip/api/sessions(附加头信息有authorization(username:password),headers("Accept":"application/*+xml;version=5.1"))登录vcloud。
2)然后再通过REST API 访问vcloud上的资源(带有上述头信息),eg:GET https://your_ip/api/org/。
Python实现代码:
'''
Created on 2013-11-5
@author: sj_mei
'''
import urllib2
import base64
import cookielib
from lib.utils import MiscUtils
class VcloudRest:
def __init__(self,url,username,password):
MiscUtils.assert_true(url is not None,"No url defined")
MiscUtils.assert_true(username is not None,"No user name defined")
MiscUtils.assert_true(password is not None,"No password defined")
self._url = url
self._username = username
self._password = password
self._autheader = self.encodeAuth(username, password)
self.login(url, username, password)
def login(self,url,username,password,method='POST'):
cookiehandler = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
httpshandler = urllib2.HTTPSHandler()
opener = urllib2.build_opener(cookiehandler,httpshandler)
urllib2.install_opener(opener)
request = urllib2.Request(url)
request.add_header("Authorization", self._autheader)
request.add_header("Accept",'application/*+xml;version=5.1')
request.get_method = lambda: method
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e
if connection.code == 200:
data = connection.read()
print "Data :", data
else:
print "ERRROR", connection.code
def encodeAuth(self,username,password):
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
return authheader
def get_header(self):
headers = {'Accept':'application/*+xml;version=5.1','Authorization':self._autheader}
return headers
def get(self,url):
headers = self.get_header()
req = urllib2.Request(url,None,headers)
req.get_method = lambda: 'GET'
try:
response = urllib2.urlopen(req)
content = response.read()
print "Content: ",content
except urllib2.HTTPError,e:
print "ERROR: ",e
if __name__ == '__main__':
vRest = VcloudRest("https://your_ip/api/sessions","username@your_vcloud","password")
resource = "https://your_ip/api/org"
vRest.get(resource)