Easy Redirection of Sudo Output
If you're using Sudo, you've probably already discovered that the increased privileges apply only to the first command typed and don't extend to any input or output redirection. For example:
|With Sudo, a sys admin can allow certain users to run commands as root or another user while providing an audit trail of the commands and their arguments. Unfortunately, increased privileges usually apply only to the first command typed. Here's how to extend them to any input or output redirection.|
sudo iptables -L > /etc/iptables
will give you a 'Permission denied' error because the shell interprets the first command (with sudo), then pipes it into the second command (without sudo).
One solution to this is to jump straight into the root user shell with su. However, this ignores all the many very good reasons to use sudo in the first place (including logging, ticketing and a lower risk of accidentally doing something foolish because you've left a root shell lying around).
A better solution is to use sudo to run bash. Just typing
isn't great, as this would put you in much the same position as just using su. However, if you use the -c option, you can execute a single command and then return to your original shell:
sudo bash -c 'iptables -L > /etc/iptables'
Another option uses echo and a second pipe:
echo 'iptables -L > /etc/iptables' | sudo bash
This method really comes into its own if you're building up a particularly complicated command, as it allows you to confirm what you're doing in advance. Type
echo 'iptables -L > /etc/iptables'
and you'll see the command you're about to run echoed to your screen. This makes sure there aren't any unexpected escapes or similar in there. Then, recall the previous command with the up arrow, and add | sudo bash(or | sudo sh, if you prefer) to the end.
Helpfully, these are all fairly easy to edit from the previous line, for those all-too-common occasions when you forget about the redirection issue until the error reminds you.
Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of "Linux System Administration Recipes: A Problem-Solution Approach" (Apress, 2009).
IT Solutions Builder TOP IT RESOURCES TO MOVE YOUR BUSINESS FORWARD
Which topic are you interested in?
What is your company size?
What is your job title?
What is your job function?
Searching our resource database to find your matches...