在Linux中使用PHP / Shell脚本从浏览器重新启动MySql Server

在Linux中使用PHP / Shell脚本从浏览器重新启动MySql Server

问题描述:

I want to restart mysql service on click of the button using php.

I have developed application using php till now I tried below things and facing the problem

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  var_dump(exec("sh rst.sh"));
  exit;
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

What I am getting is:

string(55) "Restarting mysql (via systemctl): mysql.service failed!" 

rest.sh:

#!/bin/bash
/etc/init.d/mysql restart

while executing above file from the commnad line it asks for the password.

any help will be appreciated.

Thanks

我想在使用php点击按钮时重启mysql服务。 p>

我已经开发了使用php的应用程序,直到现在我尝试了下面的东西并面对问题 p>

 &lt;?php 
if($ _GET ['run']){
# 如果设置了?run = true,则此代码将运行。
 var_dump(exec(“sh rst.sh”)); 
 exit; 
} 
?&gt; 
 
&lt;! - 此链接将 将?run = true添加到您的网址,myfilename.php?run = true  - &gt; 
&lt; a href =“?run = true”&gt;点击我!&lt; / a&gt; 
  code>   pre> 
 
 

我得到的是: p>

  string(55)“重启mysql(通过systemctl):mysql.service失败!”  
 代码>  PRE> 
 
 

rest.sh: p>

 #/斌/庆典\ N /等/ init.d /的 mysql restart 
  code>  pre> 
 
 

从commnad行执行上述文件时,它会要求输入密码。 p>

任何帮助都将不胜感激。 p>

谢谢 p> div>

Granting the user that runs PHP/web server permissions to restart any service is generally a bed idea from security perspective not even taking about permission to manage all system daemons or full sudo.


Once you have been warned, you have to make sure the user that is running the PHP script has the permission to run the restart command. As already stated, the issue has likely little to do with PHP. There are several ways from you to proceed here:

  • You can grant the PHP user the sudo permission to run the desired command and nothing else (how to do that is covered elsewhere) and invoke the command directly from PHP: sudo systemctl restart mysql.

  • Keep the rst.sh file, get it owned by root, writeable by noone else but root and set SUID bit on that file. This way you can invoke the script without sudo but the script will be run as root thanks to the SUID bit.

#1 feels safer and simpler.

You could also try with system():

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  var_dump(system("sh rst.sh"));
  exit;
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Though your problem is coming from the script you are running (rst.sh). Check the commands in script, you probably need to a systemctl call with sudo.

In php try using this command

exec("/etc/init.d/mysql restart");

or push this command to rst.sh

be ensure have chmod +x on file rst.sh