在 PHP 中使用调用自定义 powershell API 的正确方法



我有一个自定义的PowerShell API,允许我们通过API执行一些Hyper-v功能。

创建 VM 的调用如下所示:

http://wk-api-001.hypermice.net:8888/?command=Create-VPS%20-VmHost%20%22wk-devhyp-001.hypermice.net%22%20-Memsize%204GB%20-VMname%20%22test100%22%20-cpucount%204%20-Imagecode%201

我现在需要从PHP中调用它,这对我来说是一种非常陌生的语言,并且真的很挣扎。到目前为止,我有这个:

$headers = array();
$headers[] = "Content-Type: application/json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://wk-api-001.hypermice.net:8888/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "?command=create-vps%20-vmhost%20%22wkdevhyp-001.hypermice.net%22%20-vmname%20%22WHMCSTest01%22%20-Memsize%204gb%20-cpucount%204%20-Imagecode%201" );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_USERPWD, "frank:M0nk3ydust!!!");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
print $result;

当我执行此代码时,我到达了终点,但它没有传递我在CURLOPT_POSTFIELDS上定义的实际命令。

我的感觉是这不是定义它的正确地方,或者它们没有正确定义,但我对 CURL 的了解不足以解决它。

任何帮助将不胜感激。

使用GET 发出 HTTP 请求的最简单方法(我怀疑这就是您实际需要的(是使用流包装器,例如:

$output = file_get_contents('http://wk-api-001.hypermice.net:8888/?command=Create-VPS%20-VmHost%20%22wk-devhyp-001.hypermice.net%22%20-Memsize%204GB%20-VMname%20%22test100%22%20-cpucount%204%20-Imagecode%201');

如果您需要为 HTTP 身份验证提供凭据,HTTP 包装器似乎支持通用 Internet 方案语法的该部分:

//<user>:<password>@<host>:<port>/<url-path>

因此,您可以将它们注入到 URL 中:

http://frank:M0nk3ydust!!!@wk-api-001.hypermice.net:8888/…

唯一需要注意的是,每当用户名和密码包含 URL 中具有特殊含义的字符时,您都需要对用户名和密码进行 URL 编码。

$headers = array();
$headers[] = "Content-Type: application/json";
$URLCommand = "http://wk-api-001.hypermice.net:8888/?command=start-job%20-ScriptBlock%20%7BCreate-VPS%20-VmHost%20%22wk-devhyp-001%22%20-Memsize%204gb%20-VMname%20%22Frankisace%22%20-cpucount%204%20-Imagecode%201%7D";       
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URLCommand);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_USERPWD, "frank:M0nk3ydust!!!");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

所以我使用 POST,当我真的不需要时,我可以像这样在实际 URI 中定义命令。我不确定这是否是最好的方法,但这确实有效

最新更新