最近小二哥要在PHP上执行shell命令,例如:
<?php
exec('/sbin/service sshd restart');
?>
然后发现没有执行权限。
通过二进制包装器(binary wrapper)来实现
1)新建一个希望以root权限运行的sh脚本
# cat > php_shell.sh <
2)更改此文件的权限,确保root用户可以读写
# chown root php_shell.sh# chmod u=rwx,go=xr php_shell.sh
3) 构建二进制包装器来运行我们的脚本
# cat > wrapper.c <#include #include int main (int argc, char *argv[]) { setuid (0); /* WARNING: Only use an absolute path to the script to execute, * a malicious user might fool the binary and execute * arbitary commands if not. * */ system ("/bin/sh /path/to/php_shell.sh"); return 0; }CONTENT
4) 编译并设置合适的权限(使其可以root权限运行)
# gcc wrapper.c -o php_root# chown root php_root# chmod u=rwx,go=xr,+s php_root
php_root
现在可以root权限运行在php_root.sh
中定义的命令了
假如这些命令不需要被经常修改,为了安全,我推荐直接在wrapper.c
中写这些命令,直接使用system ("your shell command here");
来定义你希望执行的命令
参考文章:
https://stackoverflow.com/questions/8532304/execute-root-commands-via-php