How do I use sudo to redirect output to a location I don't have permission to write to?

前端 未结 15 1607
情深已故
情深已故 2020-11-22 07:23

I\'ve been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don\'t normally h

15条回答
  •  梦如初夏
    2020-11-22 08:00

    Clarifying a bit on why the tee option is preferable

    Assuming you have appropriate permission to execute the command that creates the output, if you pipe the output of your command to tee, you only need to elevate tee's privledges with sudo and direct tee to write (or append) to the file in question.

    in the example given in the question that would mean:

    ls -hal /root/ | sudo tee /root/test.out
    

    for a couple more practical examples:

    # kill off one source of annoying advertisements
    echo 127.0.0.1 ad.doubleclick.net | sudo tee -a /etc/hosts
    
    # configure eth4 to come up on boot, set IP and netmask (centos 6.4)
    echo -e "ONBOOT=\"YES\"\nIPADDR=10.42.84.168\nPREFIX=24" | sudo tee -a /etc/sysconfig/network-scripts/ifcfg-eth4
    

    In each of these examples you are taking the output of a non-privileged command and writing to a file that is usually only writable by root, which is the origin of your question.

    It is a good idea to do it this way because the command that generates the output is not executed with elevated privileges. It doesn't seem to matter here with echo but when the source command is a script that you don't completely trust, it is crucial.

    Note you can use the -a option to tee to append append (like >>) to the target file rather than overwrite it (like >).

提交回复
热议问题