I need to be able to modify my openvpn auth file via a php script. I have made my http user a no-pass sudoer, as this machine is only available within my home network.
When you run
sudo command > file
Only the command is run as sudo, not redirection.
As you pointed out, sudo sh -c "command > file"
would work. But unless, you really want to run the command
as sudo, you should not do it. You can run only redirection part as sudo.
The answer by rici covers 2 methods to do it. Here is another method:
command | sudo tee filename >/dev/null #to overwrite (command > file)
command | sudo tee -a filename >/dev/null # to append (command >> file)
Instead of running an entire shell process as root, which is arguably unsafe, you can run the copy as root:
(with bash):
sudo cp <(echo "$username") /etc/openvpn/auth.txt
(should work with any shell):
echo "$username" | sudo dd of=/etc/openvpn/auth.txt