vmware远程 rest 接口调用、认证、java示例代码

文章介绍了如何使用Postman、Linux命令行curl以及Java代码调用VMware官方接口进行认证,包括v6.5-V7.0U1版本的/rest/com/vmware/cis/session接口,还展示了使用ApacheHttpClient进行SSL配置和处理认证过程的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考地址

vmware 官方接口文档地址

认证

postman

通过使用 postman 调用认证接口 /rest/com/vmware/cis/session (针对于V6.5-V7.0U1版本)
在这里插入图片描述

linux 命令行调用

curl -kv -X POST -H "Authorization: Basic YWRtaW5pc3RyYXRvck==" https://172.2.1.111/rest/com/vmware/cis/session

-v 显示调用详细信息
-k 忽略认证

java代码

package http;

import com.dstz.bpm.common.constant.I2DrmConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @Author: Lisy
 * @Date: 2023/11/29/13:49
 * @Description:
 */
public class HttpClientUtil {

    private HttpClientUtil() {}

    /**
     * Vmware认证接口
     * @param url vmware ip
     * @param username 用户名
     * @param password 密码
     * @param version rest 版本 v6.5-v7.0U1   7.0U2
     * @return vmware session_id {"value":"eadcfbdab1f37d574c06e9cdcb7e8348"}
     */
    public static String authVmware(String url, String username, String password, String version) {
        try (CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(getRequestConfig(10000))
                // 忽略SSL
                .setSSLSocketFactory(getSslConnectionSocketFactory())
                .build()) {
            String sendUrl;
            switch (version) {
                case "v6.5-v7.0U1":
                    sendUrl = generateSendUrl("/rest/com/vmware/cis/session", url);
                    break;
                case "7.0U2":
                    sendUrl = generateSendUrl("/api/session", url);
                    break;
                default:
                    throw new RuntimeException("未知vmware rest 版本");
            }

            HttpPost httpPost = new HttpPost(sendUrl);
            String authString = username + ":" + password;
            String value = "Basic " + Base64.getEncoder().encodeToString(authString.getBytes());
            httpPost.addHeader("Authorization", value);
            // 处理结果
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost, HttpClientContext.create())) {
                HttpEntity httpEntity = httpResponse.getEntity();
                return EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            if (e instanceof org.apache.http.conn.ConnectTimeoutException) {
                throw new RuntimeException("连接超时请检查地址是否正确:" + e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 设置超时时间
     * @param timeout 超时时间
     * @return RequestConfig 超时时间
     */
    private static RequestConfig getRequestConfig(Integer timeout) {
        return RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(timeout)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(timeout)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(timeout)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();
    }

    private static SSLConnectionSocketFactory getSslConnectionSocketFactory() {
        SSLConnectionSocketFactory scsf;
        try {
            scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
        return scsf;
    }

    /**
     * 处理跟路径与附属路径有关 '/' 的处理
     * @param secondUrl  第二路径 /getall
     * @param rootUrl 跟路径 www.example.com
     * @return 根路径与第二路径拼接参数 www.example.com/getall
     */
    private static String generateSendUrl(String secondUrl, String rootUrl) {
        int length = rootUrl.length() - 1;
        // 去除根路径末尾的 /
        if (rootUrl.lastIndexOf("/") == length) {
            rootUrl = rootUrl.substring(0, rootUrl.length() - 1);
        }
        // 判断第二路径头部分是否以 / 开头,并完成拼接
        String substring = secondUrl.substring(0, 1);
        if ("/".equals(substring)) {
            rootUrl += secondUrl;
        } else {
            rootUrl += "/" + secondUrl;
        }
        return rootUrl;
    }
}

测试类

package http;

import org.junit.Test;

public class VmwareTest {

    @Test
    public void test() {
        String url = "https://172.1.1.11";
        String session = HttpClientUtil.authVmware(url, "username", "password", "v6.5-v7.0U1");
        System.out.println("session = " + session);
    }
}

// output
session = {"value":"da37fc3b354f0b7cd7f616fde87a0ba5"}

获取所有虚拟机

https://{host}/rest/vcenter/vm
在请求header中加入认证返回的session,即可获取
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值