PHP 使用 exec() 执行 linux 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19834444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:07:35  来源:igfitidea点击:

PHP execute linux command using exec()

phpexec

提问by Beeelze

So, i'm on my ubuntu server and want to execute the following command:

所以,我在我的 ubuntu 服务器上,想要执行以下命令:

su -c /path/to/command -s /bin/bash -l otheruser

When i type this command in the linux command line, it perfectly asks for the password for the otheruser and executes the command.

当我在 linux 命令行中键入此命令时,它完美地要求输入其他用户的密码并执行该命令。

However, when i do it like this

但是,当我这样做时

exec("su -c /path/to/command -s /bin/bash -l otheruser");

it doesn't do anything. I haven't of course specified a password for it yet, but it doesn't really return anything that could help me solve this problem. I have set the permissions to that command to 777 for testing purposes.

它什么也不做。我当然还没有为它指定密码,但它并没有真正返回任何可以帮助我解决这个问题的东西。出于测试目的,我已将该命令的权限设置为 777。

Any suggestions?

有什么建议?

回答by Latheesan

Try this:

尝试这个:

<?php

$ret = exec("su -c /path/to/command -s /bin/bash -l otheruser", $out, $err);

var_dump($ret);
var_dump($out);
var_dump($err);

?>

More Info: http://us3.php.net/manual/en/function.exec.php

更多信息:http: //us3.php.net/manual/en/function.exec.php

Also, if you are expecting the exec command to ask you for the password for the other user (as it did in the linux command line) - it won't work, exec command isn't interactive. You'll need to pass the password on the command, inline.

此外,如果您希望 exec 命令询问您其他用户的密码(就像在 linux 命令行中所做的那样) - 它不起作用,exec 命令不是交互式的。您需要在命令中内联传递密码。