PHP to Powershell using shell_exec
If I run:
$output = shell_exec('powershell "get-service "dhcp""');
I get perfect output of the service dhcp showing running but if I run:
$output = shell_exec('powershell "get-user "testing""');
I get nothing.
I don't see any difference in what Im doing here - and why get-service would work but get-user would not. If I run it in cmd it works perfectly. Any ideas?
I believe the issues might be that apache is running the command and does not have permissions. Could th开发者_JAVA百科is be the case? Does apache run as a different user? If so it doesn't have access to do this.
Try redirecting the error output to the standard output to see if you can see an error.
$output = shell_exec('powershell "get-user "testing" 2>&1"');
This snippet taken from http://www.aboutdebian.com/nettools.txt
//Normally, the shell_exec function does not report STDERR messages.
//The "2>&1" option tells the system
//to pipe STDERR to STDOUT so if there is an error, we can see it.
$fp = shell_exec("$command 2>&1");
exec() and shell_exec() are not very verbose by nature. exec() allows you to set a third variable and get the execution status, but failures are mostly assigned "1" and you have no way of knowing if it was a permissions error, if the binary is not executable etc.
Enter a project that allows PHP to obtain and interact dynamically with a real Powershell. Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
$shellObj = \MTS\Factories::getDevices()->getLocalHost()->getShell('powershell');
$strCmd1 = 'get-user "testing"';
$return1 = $shellObj->exeCmd($strCmd1);
The return will give you the command return OR error from powershell, just as if you sat at the console. Furthermore, you can issue any command you like against the $shellObj, the environment is maintained throughout the life of the PHP script. So instead of bundling commands in a script file, just issue them one by one using the exeCmd() method, that way you can also handle the return and any exceptions.
精彩评论