传递管理员用户名&使用shell_exec的密码

时间:2012-12-30 21:24:36

标签: php powershell shell-exec

我有一个Powershell脚本,当我直接在Web服务器上运行时(Windows 2008R2,IIS)成功完成。我现在正试图从php页面启动脚本。脚本启动,我可以在任务管理器中看到这个过程。

当我从php页面使用shell_exec调用脚本时,它失败并显示错误

"Exception calling "FindOne" with "0" argument(s): "An operations error occurred."

我可以从任务管理器看到该脚本作为用户IUSR运行。我很确定这就是脚本失败的原因,为了成功完成它需要作为域管理员运行。

我使用以下命令调用脚本

$ username =页面上当前登录的用户(针对AD进行身份验证)
$ newPword1 =新用户密码

$query = shell_exec("powershell -command $psScriptPath '$username' '$newPword1' < NUL");

Powershell脚本:

#*=============================================================================
#* PARAMETER DECLARATION
#*=============================================================================

param([string]$username,[string]$pword)

#*=============================================================================
#* INITIALISE VARIABLES
#*=============================================================================
# Increase buffer width/height to avoid Powershell from wrapping the text before
# sending it back to PHP (this results in weird spaces).
$pshost = Get-Host
$pswindow = $pshost.ui.rawui
$newsize = $pswindow.buffersize
$newsize.height = 3000
$newsize.width = 400
$pswindow.buffersize = $newsize


#*=============================================================================
#* SCRIPT BODY
#*=============================================================================

$root = [ADSI]'LDAP://<server>/<DNtoOU>'
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectCategory=person)(sAMAccountName=$username))"
$user = $searcher.findone()

$userDN = $user.path

$user=[ADSI]$($userDN)
$user.SetPassword($pword)
$user.setinfo()
write-host "success"

是否可以传递域管理员用户名/密码来运行PowerShell,因为使用上述命令,从而允许脚本成功运行?

1 个答案:

答案 0 :(得分:1)

其中一种方法是使用PowerShellRunAs

编辑:据记载,您可以按原样使用powershell脚本或修改它以满足您的需求(例如使用密码文件)。

更详细地说,而不是:
shell_exec("powershell -command $psScriptPath …")
你可以用这个:
shell_exec("powershell -command "Start-Process powershell.exe -argumentlist '-command $psScriptPath …' -Credential 'TheDomain\TheUser'")
但是为避免密码提示,请按照文档使用PowerShellRunAs:
shell_exec("powershell -command "Start-Process powershell.exe -argumentlist '-command $psScriptPath …' -Credential (.\PowerShellRunAs.ps1 -get contoso\svc_remoterestart \\fileserver\share\file.pwd)")

或者,您可以将start-process … -credential …合并到自己的脚本中。通过这种方式,您可以像以前一样简单地保持shell_exec调用,并且只有部分脚本可以在具有不同(更高)权限的用户下运行。

如果您按原样使用该脚本,请记住首先使用-set而不是-get运行该脚本,以便设置密码文件。