Friday, June 17, 2011

4 Tricks with sudo


I think that sudo is become a wide used command with Ubuntu, where you don’t even have a root password, before that probably it was used only in some data-centers to restrict access to some commands.
sudo allows a permitted user to execute a command as the superuser or another user, as specified in the sudoers file.
In this article I will show some uses a little less common for this command, for a general description of the command you could read the page about sudo on wikipedia


1)

sudo !!
you wanted to give a command as root but you forgot to use sudo ? Don’t worry with this command you’ll use the history combined with sudo, the argument !! has the same meaning that !-1 , so this command runs your last command as root.
Obviously this could be used also as
sudo !-2
if you give another command after the one you want to run as root, but take care on which command are you running as root.
2)
sudo -i
you can use this command to have an interactive shell as root.
To have a shell with a different user use the format
sudo -u username -i
The -i (simulate initial login) option runs the shell specified in the passwd entry of the target user as a login shell. This means that login-specific resource files such as .profile or .login will be read by the shell. If a command is specified, it is passed to the shell for execution. Otherwise, an interactive shell is executed.
3) Sudo output redirection, thanks to petur.eu:
We are faced with a problem when trying to redirect with sudo, as the second part of the command is not executed with root privileges.
sudo command > outputfile
<>—-root——<>—user—<>
The solution is to use;
‘sudo tee’ instead of the ‘>’ operator,
‘sudo tee -a’ instead of the ‘>>’ operator.
sudo command | sudo tee outputfile
<>—–root—–<>——-root——<>
4)
:w !sudo tee %
This command can be used in your vi/vim to save a file you have opened and edited as a user, but you can not save with your user rights. In this way you don’t have to save the file in /tmp, become root and move the file from /tmp to the real place.

No comments:

Post a Comment