首页 / 服务中心 / 常见问题

php 执行exec() 操作linux 命令

时间:2021-05-26 17:45:49 点击:

1、添加用户www到sudoers里面

//修改/etc/sudoers的内容 ## Allow root to run any commands anywhere  
//ps -aux | grep php-fpm 可以查看php-fpm进程所对应的用户,BT里可以设置www目录归属用户
root ALL=(ALL) ALL www ALL=(ALL) ALL //新添加这一行 %www ALL=(ALL) NOPASSWD: ALL //设置xxxx组下面的用户使用sudo不需要输入密码

2、修改php.ini中的disable_functions

exec删除

3、重启服务

service nginx {start|stop|status|restart|reload|configtest}  service php-fpm {start|stop|restart|reload|status}

 4、返回状态

exec($str, $array, $state); //执行命令
var_dump($state);  第三个参数是返回状态   0成功   1失败

 

5、测试代码

$return_array = array();
print_r($_ENV);
putenv('PATH=/usr/sbin/');
$return_array = array();
$result = exec("ifconfig -a", $return_array,$return);
echo $return;
echo 'result:'.print_r($result,true).'';
print_r($return_array);
exec的第三个参数可以查看返回的错误信息,命令有可能不存在,需要设置path环境变量,注意chroot之后路径会有变化,见下面的解释
exec函数第三个参数是执行命令的状态,返回127是说明, 你执行命令的路径不对, 或没有权限等等

下面是127错误文档解释

"Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).
Remember, you'll also get this error if your file does not have executable permission."

"If you have chrooted apache and php, you will also want to put /bin/sh into the chrooted environment. Otherwise, the exec() or passthru() will not function properly, and will produce error code 127, file not found."
#no chroot php script dir
include fastcgi.conf;
#chroot php script dir
#include fcginew.conf;
#fastcgi_param  SCRIPT_FILENAME   /testyytdev.crm123.cn$fastcgi_script_name;

 PS:BTApi 里有ExecShell的API接口