首页 > 解决方案 > 无法使用 PHP 的 SSH 命令创建 Active Directory 用户

问题描述

我尝试使用 PHP 页面中的 SSH 命令创建 Active Directory 用户:

include('Net/SSH2.php');
$path = "OU=HRTest,OU=Israel,OU=Users,OU=Solaredge,DC=solaredge,DC=local";
$name = "Test User2";
$title = "Some Position";
$password = "Welcome!";
$department = "IS";
$POBox = "01/05/2020";
$Company = "SolarEdge Technologies LTD.";
$GivenName = "Test";
$DisplayName = "Test User2";
$SamAccountName = "Test.u2";
$Enabled = "$true";

$server = "MyServerName";
$username = "MyUserName";
$pwd = "MyPassword";

$command = 'powershell New-ADUser -Path "'.$path.'" -Name "'.$name.'" -Title "'.$title.'" -Department "'.$department.'" -POBox "'.$POBox.'" -AccountPassword $("'.$password.'" | ConvertTo-SecureString -AsPlainText -Force) -Company "'.$Company.'" -GivenName "'.$GivenName.'" -DisplayName "'.$DisplayName.'" -SamAccountName "'.$SamAccountName.'" -Enabled '.$Enabled;

$ssh = new Net_SSH2($server);
if (!$ssh->login($username, $pwd)) {
    exit('Login Failed');
}

echo $ssh->exec($command);

SSH 连接有效,但 PowerShell 生成此错误:

New-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Path'. Specified 
method is not supported.
At line:1 char:18
+ ... DUser -Path OU=HRTest,OU=Israel,OU=Users,OU=Solaredge,DC=solaredge,DC ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.NewADUser

编辑 - 新错误:

'ConvertTo-SecureString' is not recognized as an internal or external command,
operable program or batch file.

标签: phppowershellsshactive-directoryphpseclib

解决方案


您必须将所有可能包含特殊字符的字符串的引号传递给 PowerShell,以便它可以按预期解析您的字符串。此外,ConvertTo-SecureString像这样调用时行为很奇怪。这个答案中描述了一个解决方案。ConvertTo-SecureString我在以下行中包含了引号和解决方法:

$command = 'powershell "& {New-ADUser -Path \''.$path.'\' -Name \''.$name.'\' -Title \''.$title.'\' -Department \''.$department.'\' -POBox \''.$POBox.'\' -AccountPassword (ConvertTo-SecureString -AsPlainText \''.$password.'\' -Force) -Company \''.$Company.'\' -GivenName \''.$GivenName.'\' -DisplayName \''.$DisplayName.'\' -SamAccountName \''.$SamAccountName.'\' -Enabled '.$Enabled}";

将您的密码行更改为:

$password = "Welc0me!";

推荐阅读