我正在尝试从使用PHP7的VMware vCenter v6.5获取VM信息。我收到来自curl_getinfo的错误代码400。
我从这篇文章中复制了代码:VCenter ReST API authentication
我已经在命令行中尝试过了,并且能够获得一个会话ID,所以我知道服务器正在按它应该的方式发送信息,只是没有发送到PHP网页。
以下命令的参考:https://communities.vmware.com/thread/556377
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'vmware-use-header-authn: test' --header 'vmware-api-session-id: null' -u 'administrator@vsphere.local' 'https://vcenter.mydomain.local/rest/com/vmware/cis/session'
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'https://vcenter.mydomain.local/rest/com/vmware/cis/session');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, 'administrator@vsphere.local:Passw0rd');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
$headers = array(
'Content-Type: application/json',
'Accept: application/json',
'vmware-use-header-authn: test',
'vmware-api-session-id: null',
'Expect:'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$out = json_decode(curl_exec($ch));
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
$info = curl_getinfo($ch);
echo "<p>CURL URL: " . $info['url'];
echo "<p><font color=green>CURL Dump: <br>";
echo '<pre>';
var_dump($info);
echo "</pre>\n";
echo "<p>OUT:<br>";
var_dump($out);
if ($out === false) {
echo 'Curl Error: ' . curl_error($ch);
exit;
}
$sid = $out->value;
echo "<br>SID: " . $sid;
curl_close($ch);
?>
我希望$out->value
的输出是一个会话ID,而我得到的是NULL
。感谢您的帮助,谢谢!
发布于 2019-01-17 02:20:44
我最好的猜测是,VCenter会阻止没有用户代理头的请求,curl-cli会自动添加这样的头,但libcurl /php的libcurl包装器不会。试一试
curl_setopt($ch,CURLOPT_USERAGENT, 'php/' . PHP_VERSION . ' libcurl/' . (curl_version()['version']));
然后你会得到像这样的东西
User-Agent: php/7.1.16 libcurl/7.59.0
这是真实的:)
发布于 2021-01-18 21:56:46
http 400错误是由以下标头引起的:
curl_setopt($ch, CURLOPT_POST, true);
用这个替换它解决了这个问题:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
发布于 2019-11-21 01:13:24
使用curl,你可以这样连接:
curl -X POST \
https://<your_vcenter>/rest/com/vmware/cis/session \
-H 'Accept: application/json' \
-H 'Authorization: Basic <encoded_password...see *1)' \
-H 'Content-Type: application/json' \
-H 'vmware-use-header-authn: SomerandomValue'
*1 => https://en.wikipedia.org/wiki/Basic_access_authentication**
然后你会得到一个响应:
{
"value": "vmware-api-session-id"
}
使用此id,您可以执行以下操作:
curl -X GET \
https://<your_vcenter>/rest/vcenter/host \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-H 'vmware-api-session-id: vmware-api-session-id' \
-d '{
"filter": {
}
}'
并获取
{
"value": [
{
"host": "host-1",
"name": "esx01.your.domain",
"connection_state": "CONNECTED",
"power_state": "POWERED_ON"
},
{
"host": "host-2",
"name": "esx02.your.domain",
"connection_state": "CONNECTED",
"power_state": "POWERED_ON"
}
]
}
https://stackoverflow.com/questions/54221861
复制相似问题