其它
OpenAPI

OpenAPI概述

行云管家的OpenAPI(以下简称OpenAPI或API),在SaaS和私有部署版上均可使用。API提供的方法和调用方式都是一致的,区别是client使用的AK和endpoint不同。

1) SaaS环境的endpoint是:https://openapi.cloudbility.com,有需要通过OpenAPI集成行云管家功能的,可以联系在线客服获取所需的AK。

2) 私有部署版本的endpoint,可以在管理控制台的菜单:系统设置->OpenAPI中查看,点击“启用API”之后会生成所需的AK。

API以http RESTful的方式提供,API调用的认证方式有两种:

1) 使用AK生成签名;

2) 使用Token。

API有一个可以在线调试的页面,即不用写一行代码,也可以完成大部分的API调用。SAAS环境的API的文档页面在https://openapi.cloudbility.com/doc/index.html,也是API调试页面。

私有部署版可以通过管理控制台的菜单:系统设置->OpenAPI 查看。在线调试,只能使用Token的方式进行认证。

API的调用的payload参数和返回结果,都是基于JSON的,涉及到日期的字段,都是采用格式:"yyyy-MM-dd'T'HH:mm:ss'Z'",采用UTC时区。

API在线调试

本章节以一个私有部署版实例进行介绍:http://188.188.77.136

从管理控制台获取到AK和endpoint如下:

获取授权的Token

在调试页面,打开API方法:other api ->GET/oauth,输入AK和超时时间,点击“试一下”;

调试页面会显示API接口的输入参数列表和输出参数的模型,如果输入的是http payload json,也会显示模型。模型参数会描述每个字段的数据类型和意义。

调试程序会打印请求的详情,用curl命令展示,也会把响应结果显示出来。可以看到,示例中获取的token是:adr51k55S2K7IMNF2Jhe6Q

点击右上角的“Authorize”把token填入 API key的 value字段,点击“Authorize”:

从此之后,当前页面发送的请求就都会带上Token进行认证。刷新页面或者Token超时后会失效。

获取自动登录的授权URL

获取一个以特定用户身份登录系统,并打开特定页面的授权URL:other api -> get /oauthLogin。下面示例中,获取以用户(id=1)身份进入团队(id=1),并且打开首页菜单的授权链接。

用浏览器打开链接:http://188.188.77.136/api/openapiOAuth?token=Dh8gtA-mTOeZ4Mug8-PUIQ可以看到用户已自动登录并打开首页了。

使用 Openapi Java SDK调用API

下面代码演示使用Java SDK获取自动登录的授权URL:

import com.cloudbility.openapi.OpenapiClient;
import com.cloudbility.openapi.OpenapiException;
import com.cloudbility.openapi.client.OpenapiConfig;
import com.cloudbility.openapi.request.OAuthLoginRequest;
import com.cloudbility.openapi.response.OAuthUrlResult;
import com.cloudbility.openapi.vo.RedirectPage;

/**
 * 获取自动登录的URL(OAuth login url)
 */
public class GetAutoLoginAuthUrlDemo {

   public static final String accessKeyId = "hpOGe8Gw6VOpMhy8";
   public static final String accessKeySecret = "Xa3qjkSC-Cvcv2I2hXzd8myqXHLlierG";
   public static final String endpoint = "http://188.188.77.136/api/openapi";

   public static void main(String[] args) {
      //client对象可以复用,可以并发使用
      OpenapiClient client = createOpenapiClient(accessKeyId, accessKeySecret, endpoint);
      OAuthLoginRequest request = new OAuthLoginRequest();
      request.setExpireSeconds(300);//链接300秒有效
      request.setOneoff(true);//链接一次有效
      request.setUserId(1);//登录用户id=1
      request.setTeamId(1);//登录后进入团队id=1
      request.setPage(RedirectPage.Home);//登录后打开首页菜单
      try {
         OAuthUrlResult result = client.otherApi().getOAuthLogin(request);
         System.out.println(result.getUrl());
         //输出:http://188.188.77.136/api/openapiOAuth?token=kUfssyjZTbO3hPilVq_qZg
      } catch (OpenapiException e) {
         e.printStackTrace();
      }
   }
   private static OpenapiClient createOpenapiClient(String accessKeyId, String accessKeySecret, String endpoint) {
      OpenapiConfig config = new OpenapiConfig();
      config.setAccessKeyId(accessKeyId);
      config.setAccessKeySecret(accessKeySecret);
      config.setEndpoint(endpoint);
      return new OpenapiClient(config);
   }
}

需要API Java SDK和示例代码可以联系在线客服

使用Python调用OpenAPI

以下Python代码,演示获取Token、按照IP查询主机、创建登录凭证等功能:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys
import requests
import json
import os
apiEndpoint = "http://ent.cloudbility.cn:88/api/openapi"
'''
openApi: function to access api url and post parameters
'''
def openApi(url: str, params: dict = None, headers: dict = None, method: str = "GET", contentType: str = "json", timeout: int = 10) -> dict:
    if method == "GET":
        response = requests.get(apiEndpoint + url, params=params, headers=headers, timeout=timeout)
    elif method == "POST":
        if not headers:
            headers = dict()
        if contentType == "json":
            headers["Content-Type"] = "application/json"
            params = json.dumps(params) if params else None
        response = requests.post(apiEndpoint + url, data=params, headers=headers, timeout=timeout)
    elif method == "DELETE":
        response = requests.delete(apiEndpoint + url, data=params, headers=headers, timeout=timeout)
    else:
        return None
    if not response:
        return None
    if not 200 <= response.status_code <= 299:
        return None
    return json.loads(response.text)
def getToken(accessKeyId, accessKeySecret, expireSeconds=300):
    tokenJson = openApi(
        "/oauth",
        params={
            "accessKeyId": accessKeyId,
            "accessKeySecret": accessKeySecret,
            "expireSeconds": expireSeconds
        },
    )
    return tokenJson["token"]
def getHostByIP(token, ip, teamId=1):
    hostJson = openApi(
        "/host/findByIp",
        params={"teamId": teamId, "ip": ip},
        headers={"Authorization": token}
    )
    return hostJson
def createCredential(token, ip, user, password, **kwargs):
    hosts = getHostByIP(token, ip, kwargs.get("TeamId", "1"))
    if not hosts or "hosts" not in hosts:
        return None
    hostId = hosts["hosts"][0]["hostId"]
    if not hostId:
        return None
    credential = openApi(
        "/credential",
        params={
            "account": user,
            "authType": kwargs.get("AuthType", "PASSWORD"),
            "desktopType": kwargs.get("DesktopType", "SSH"),
            "hosts": [
                {
                    "hostId": hostId,
                }
            ],
            "name": "host_%s_cre_%s" %(hostId, os.getpid()),
            "password": password,
            "teamId": kwargs.get("TeamId", "1"),
        },
        headers={"Authorization": token},
        method="POST"
    )
    return credential["id"]
def main(args, **kwargs):
    ip = args[0]
    user = args[1]
    password = args[2]
    accessKeyId = kwargs.get("id")
    accessKeySecret = kwargs.get("secret")
    if not accessKeyId or not accessKeySecret:
        print("AccessKeyId and AccessKeySecret are not present.\n")
        return -1
    token = getToken(accessKeyId, accessKeySecret)
    if not token:
        print("Invalid AccessKeyId and AccessKeySecret.\n")
        return -1
    credentialId = createCredential(token, ip, user, password, **kwargs)
    if credentialId:
        print("Create credential for %s successed. Credential Id is %s.\n" % (ip, credentialId))
    else:
        print("Create credential for %s failed.\n" % (ip))
if __name__ == "__main__":
    print("Create credential for a host in team(default 1). Before this operation, please do:\n")
    print("1: Import the host to cloudbility\n")
    print("2: Get the AccessKey Id & Secret from administration console\n")
    print(
        "Usage: openapi_demo.py ip username password id= secret= [teamId= AuthType= DesktopType=]\n")
    if len(sys.argv) != 6:
        sys.exit(-1)
    sys.exit(main(sys.argv[1:4], **dict(arg.split('=') for arg in sys.argv[4:])))