Adding yourself to the sudoers file

27 August 2007

Adding yourself to the sudoers file

If you've gone at least some way to trying to make your server secure, you wont be running as root so you wont have access to many of the administration commands you'll need. It's easily resolved by adding yourself to the sudoers file, here's a quick guide on how to do it.

Giving a user access to sudo

Unless you've already got an account with sudo access, you're going to need to log in as root one last time to set one up. So do the following:

su -

And enter in the password for root when prompted. Next we'll edit the sudoers file using visudo:

visudo

This will open up the file in a vi session for editing. If you've not got crazy vi chops don't worry, were don't need to do anything complicated. Just page down to the bottom of the document and enter the following:

your_username_here ALL=(ALL)       ALL

Hit esc then type:

:wq

and press ENTER. The file will be saved, and you've just granted yourself access to run everything as the root user. Now type:

exit

to log out as root and back in as yourself. Now if we want to edit the sudoers file we can do the following:

sudo visudo

this time when you are prompted for a password, you only need to enter your own one. And tada, the sudoers file is open again. Now let's give some more users access, but we won't be quite so generous with what they can do.

Giving a user access to a single command

What about on a production machine where you've got a user that is a little bit trusted, but shouldn't be given total access to the system? It quite easy to setup some walled access to the commands you need to open up. In the example below, we will grant access to god for the user deploy so that we can start and stop our services through capistrano.

deploy  ALL= /usr/bin/god

Sudo command line howto

How about running a command as another user, without changing to that user? Simple:

sudo -u otheruser /usr/bin/command

Or running a command and pushing it to the background:

sudo -b /usr/bin/command

Or just finding out what commands you are allowed to run:

sudo -l

Sudo config (more detailed sudoers file options)

The sudoers file offers quite a lot of control over exactly what someone can run, as well as who they can run it as, and from where. Let's just quickly run through a few of the other options you've got in the sudoers file:

Restricting who a user can run commands as

The following snippet allows the user bob to run all commands from anywhere, but only as alice or anne:

RunAs_Alias     HELPDESK = alice, anne
bob ALL=(HELPDESK) ALL

Restricting where a user can run commands from

This config allows bob to run any command as any user, but only from the defined subnet:

Host_Alias     MYNET = 10.1.2.0/255.255.255.0
bob MYNET=(ALL) ALL
I'm putting together a weekly newsletter to help developers spend more time on what they do best. You should sign up to Cloud Services Weekly  today!