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

前端 未结 15 1458
情深已故
情深已故 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:07

    This is based on the answer involving tee. To make things easier I wrote a small script (I call it suwrite) and put it in /usr/local/bin/ with +x permission:

    #! /bin/sh
    if [ $# = 0 ] ; then
        echo "USAGE: <command writing to stdout> | suwrite [-a] <output file 1> ..." >&2
        exit 1
    fi
    for arg in "$@" ; do
        if [ ${arg#/dev/} != ${arg} ] ; then
            echo "Found dangerous argument ‘$arg’. Will exit."
            exit 2
        fi
    done
    sudo tee "$@" > /dev/null
    

    As shown in the USAGE in the code, all you have to do is to pipe the output to this script followed by the desired superuser-accessible filename and it will automatically prompt you for your password if needed (since it includes sudo).

    echo test | suwrite /root/test.txt
    

    Note that since this is a simple wrapper for tee, it will also accept tee's -a option to append, and also supports writing to multiple files at the same time.

    echo test2 | suwrite -a /root/test.txt
    echo test-multi | suwrite /root/test-a.txt /root/test-b.txt
    

    It also has some simplistic protection against writing to /dev/ devices which was a concern mentioned in one of the comments on this page.

    0 讨论(0)
  • 2020-11-22 08:09

    Someone here has just suggested sudoing tee:

    sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
    

    This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an "echo to a file" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.

    0 讨论(0)
  • 2020-11-22 08:09

    Make sudo run a shell, like this:

    sudo sh -c "echo foo > ~root/out"
    
    0 讨论(0)
提交回复
热议问题