0

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.

I currently have the following commands:

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

but when run, they do not change the file at all, or provide any output in php.

How do I make this work?

Prix
  • 19,417
  • 15
  • 73
  • 132
Greg Schoppe
  • 576
  • 1
  • 7
  • 22

2 Answers2

3

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
anishsane
  • 20,270
  • 5
  • 40
  • 73
rici
  • 234,347
  • 28
  • 237
  • 341
  • I understand how this would give me username, but the file has to be two lines, username on one, password on the other... how would i do this, without being able to append? – Greg Schoppe Jul 01 '13 at 12:23
  • @GregSchoppe: `{echo foo; echo bar; } | dd of=/path/to/file `. Or just put the entire string, including a newline character, between quotes: `echo "foobar"`, which should be easy if you're generting the command line with php. If you really need to append and you're using GNU dd: `dd of=/path/to/file conv=notrunc oflag=append`. – rici Jul 01 '13 at 14:42
1

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)
anishsane
  • 20,270
  • 5
  • 40
  • 73
  • I should have added this as comment to other option, but I had already typed half of this answer. So posted here itself. – anishsane Jul 01 '13 at 05:17