运行shell命令并将输出发送到文件


Run shell command and send output to file?

我需要能够通过php脚本修改我的openvpn身份验证文件。我已经让我的http用户成为一个无通行证的sudoer,因为这台机器只能在我的家庭网络中使用。

我目前有以下命令:

echo shell_exec("sudo echo '".$username."' > /etc/openvpn/auth.txt");
echo shell_exec("sudo echo '".$password."' >> /etc/openvpn/auth.txt");

但是在运行时,它们根本不会更改文件,也不会在php中提供任何输出。

我该如何做到这一点?

您可以以root身份运行副本:

(带bash):

sudo cp <(echo "$username") /etc/openvpn/auth.txt

(应适用于任何外壳):

echo "$username" | sudo dd of=/etc/openvpn/auth.txt

运行时

sudo command > file

只有命令作为sudo运行,而不是重定向。

正如您所指出的,sudo sh -c "command > file"会起作用。但除非你真的想以sudo的身份运行command,否则你不应该这样做。你只能以sudo身份运行重定向部分。rici的答案涵盖了2种方法。这里是另一种方法:

command | sudo tee filename >/dev/null #to overwrite (command > file)
command | sudo tee -a filename >/dev/null # to append (command >> file)