Run shell command and send output to file?

前端 未结 2 946
北荒
北荒 2021-01-27 23:37

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.

相关标签:
2条回答
  • 2021-01-27 23:52

    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)
    
    0 讨论(0)
  • 2021-01-28 00:08

    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
    
    0 讨论(0)
提交回复
热议问题