Php Execute Shell Command and pipe the password

你。 提交于 2019-12-11 16:26:29

问题


I am attempting to run a command as root from a php page, is there any way to run shell_exec(su - root -c 'apt-get update') (for example) and pass the password to the shell? Or is there another way to run a root command from php and pass the password to the command.

I would prefer not to do the follow:

edit the /etc/sudoers file;
install the ssh2 php extension;

回答1:


You could create a setuid wrapper for the command you want to run, and execute that wrapper instead:

echo '#!/bin/bash' > /path/to/wrapper.sh
echo 'apt-get update' >> /path/to/wrapper.sh
chown root /path/to/wrapper.sh
chmod a+x,u+s /path/to/wrapper.sh



回答2:


Used an entirely PHP based SSH implementation called phpseclib.

This way the user doesn't have to install a php extension like ssh2, just download the files and include them in your script. Then you can pipe the password to the command, like so:

set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include('Net/SSH2.php');

 $ssh = new Net_SSH2('localhost');
 if (!$ssh->login('root', $password)) {
     exit('Login Failed');
  }

 echo $ssh->exec('whoami');

This php code will return the value "root". Any commands you run at this time will be run as root.



来源:https://stackoverflow.com/questions/10875623/php-execute-shell-command-and-pipe-the-password

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!