Wednesday, December 19, 2012

Privileged redirection with sudo

It is sometimes useful to execute something via sudo and use shell redirection that also needs to happen via sudo. This can be accomplished in a number of ways, some better (IMO) than others. The problem:
sudo cat foo > bar
The "cat foo" portion is executed as root, the "> bar" is executed as the original user. The first option is to execute a shell as the privileged user, and then execute the commands.
sudo -s
cat foo > bar
The downside of this is that an audit trail of commands executed with privilege is lost. To maintain an audit trail, each command has to be individually executed via sudo. But if both the command and the redirect need to happen as root, it can be done in two manners:
sudo sh -c "cat foo > bar"
sudo cat foo | tee sudo bar
I prefer the first method, it will create a single entry in the audit trail and seems more elegant.

No comments:

Post a Comment