2.20 Running Commands as the Superuser
Before going any further, you should learn how to run commands as the superuser. You may be tempted to start a root shell, but doing so has many disadvantages:
- You have no record of system-altering commands.
- You have no record of the users who performed system-altering commands.
- You don’t have access to your normal shell environment.
- You have to enter the root password (if you have one).
2.20.1 sudo
Most distributions use a package called sudo to allow administrators to run commands as root when they are logged in as themselves. For example, in Chapter 7, you’ll learn about using vipw to edit the /etc/passwd file. You could do it like this:
$ sudo vipw
When you run this command, sudo logs this action with the syslog service under the local2 facility. You’ll also learn more about system logs in Chapter 7.
2.20.2 /etc/sudoers
Of course, the system doesn’t let just any user run commands as the superuser; you must configure the privileged users in your /etc/sudoers file. The sudo package has many options (that you’ll probably never use), which makes the syntax in /etc/sudoers somewhat complicated. For example, this file gives user1 and user2 the power to run any command as root without having to enter a password:
User_Alias ADMINS = user1, user2
ADMINS ALL = NOPASSWD: ALL
root ALL=(ALL) ALL
The first line defines an ADMINS user alias with the two users, and the second line grants the privileges. The ALL = NOPASSWD: ALL part means that the users in the ADMINS alias can use sudo to execute commands as root. The second ALL means “any command.” The first ALL means “any host.” (If you have more than one machine, you can set different kinds of access for each machine or group of machines, but we won’t cover that feature.)
The root ALL=(ALL) ALL simply means that the superuser may also use sudo to run any command on any host. The extra (ALL) means that the superuser may also run commands as any other user. You can extend this privilege to the ADMINS users by adding (ALL) to the second /etc/sudoers line, as shown here:
ADMINS ALL = (ALL) NOPASSWD: ALL
Use the visudo command to edit /etc/sudoers. This command checks for file syntax errors after you save the file.
2.20.3 sudo Logs
Although we’ll go into logs in more detail later in the book, you can find the sudo logs on most systems with this command:
$ journalctl SYSLOG_IDENTIFIER=sudo
On older systems, you’ll need to look for a logfile in /var/log, such as /var/log/auth.log.
That’s it for sudo for now. If you need to use its more advanced features, see the sudoers(5) and sudo(8) manual pages. (The actual mechanics of user switching are covered in Chapter 7.)