简体   繁体   English

为什么php命令`exec(“service apache2 restart”);`不能在ubuntu上工作?

[英]why php command `exec(“service apache2 restart”);` does't work on ubuntu?

I need to execute some commands on my web server with php configured with apache. 我需要在我的Web服务器上执行一些命令,并使用apache配置php。

exec("service apache2 restart", $output);
print_r($output);

output: 输出:

Array (
    [0] =>  * Restarting web server apache2
    [1] => Action 'start' failed.
    [2] => The Apache error log may have more information.
    [3] =>    ...fail! 
)

My guess is it's because of permissions of php on my ubuntu! 我的猜测是因为我的ubuntu上的php权限! What do you suggest? 你有什么建议?

You need to run : 你需要运行:

visudo

check that you have a line like 检查你有一条线

Host_Alias LOCAL=192.168.0.1 

with your own local IP at the top of the file, then add a line 在文件顶部使用您自己的本地IP,然后添加一行

www-data       LOCAL=NOPASSWD:/usr/bin/service

And last in your PHP file : 最后在你的PHP文件中:

exec("/usr/bin/sudo /usr/bin/service apache2 restart");

(You are trying to restart apache by web, maybe you don't know webmin interface ? I think there's betters solutions than this sudo way. It's not a good thing to authorize www-data to stop, start (...) all the services. Better explain why you'd like to restart apache ;) ) (你试图通过网络重启apache,也许你不知道webmin界面?我认为有比这个sudo方式更好的解决方案。授权www-data停止,启动(...)所有的都不是一件好事服务。更好地解释你为什么要重启apache;))

Services (in the sense of system services, like Apache httpd) can only be manipulated (started, stoppped, restarted) by the root user (UID 0). 服务(在系统服务方面,如Apache httpd)只能由root用户(UID 0)操纵(启动,停止,重新启动)。

Either you run the PHP script in root's context ( bad idea) or you use something like sudo to run the commands as super user. 要么在root的上下文中运行PHP脚本( 糟糕的主意),要么使用像sudo这样的命令以超级用户身份运行命令。 This said, there are very serious security implications when running programs with super user privileges, especially if you don't sanitize your inputs properly! 这就是说,运行具有超级用户权限的程序时会产生非常严重的安全隐患,特别是如果您没有正确清理输入!

Did you look at the Apache error log like it says? 您是否看过Apache错误日志? What's in there? 那里有什么?

Almost certainly your PHP script is running without sufficient permissions to restart Apache. 几乎可以肯定,您的PHP脚本运行时没有足够的权限来重启Apache。 Which is probably for the best. 这可能是最好的。 If you really really need this to work, consider making a setuid root script to invoke from PHP (note that this should not be used in production, and will probably create a security hole). 如果你真的需要这个工作,可以考虑从PHP调用setuid root脚本(请注意,这不应该在生产中使用,并且可能会创建一个安全漏洞)。

You could also write a little service which runs as root and accepts commands to restart Apache from your PHP script. 您还可以编写一个以root身份运行的小服务,并接受从PHP脚本重启Apache的命令。 That'd be a more "proper" way of doing this, though the task at hand seems itself improper, so I'm not sure you should continue down this path. 这是一种更“正确”的做法,虽然手头的任务看起来本身就是不合适的,所以我不确定你应该继续这条道路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM