Modern Linux System Administration

A Practical Guide to Installation, Configuration, and Management

With Early Release ebooks, you get books in their earliest form—the author’s raw and unedited content as they write—so you can take advantage of these technologies long before the official release of these titles.

Ken Hess

Modern Linux System Administration

by Ken Hess

Copyright © 2022 Hess Media and Consulting, LLC. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.

- Acquisitions Editor: John Devins

- Development Editor: Jeff Bleiel

- Production Editor:

- Copyeditor:

- Proofreader:

- Indexer:

- Interior Designer: David Futato

- Cover Designer: Karen Montgomery

- Illustrator: Kate Dullea

- September 2022: First Edition

Revision History for the Early Release

- 2021-08-31: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781098109035 for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Modern Linux System Administration, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.

The views expressed in this work are those of the author, and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.

978-1-098-10903-5

[LSI]

Chapter 1. Getting Started with Linux

Linux system administration means different things to different people. Administration, for this book, means the daily actions that a Linux system administrator must take to manage and support users, maintain system health, implement best practices for security, install software, and perform housekeeping tasks. This chapter covers Linux installation, initial setup, and system exploration using simple shell commands.

You’ll spend a significant portion of your time at the command line, also known as the command line interface (CLI). Linux system administrators rarely install or use graphic user interfaces (GUIs) on their supported server systems. This chapter introduces you to the CLI and some simple commands to navigate the filesystem, to locate important files, and to familiarize yourself with the Linux CLI.

Installing Linux

One of the first things every Linux system administrator (sysadmin) learns is how to install Linux. There’s no single correct way to install Linux but there are a few guidelines and suggestions that will make your life easier in the future as your user’s needs change.

While this section won’t go into step-by-step detailed instructions on how to install Linux, the basic steps are outlined here. For the majority of junior-level sysadmins, system installation generally takes place via automated means such as Kickstart or other enterprise-level delivery system.

Preparing your system for Linux

If this is your first time to install Linux, I suggest that you install it into a virtual machine (VM) so that you don’t have to dedicate an entire piece of hardware for a learning system and so that you don’t potentially render your system inoperable by attempting to install Linux in parallel to your current system creating a multi-boot computer. (Setting up multi-booting is a more advanced concept and out of the scope of this book.)

A good place to start with virtualization, if you don’t already have it installed, is to download and install the latest version of VirtualBox (https://www.virtualbox.org/). VirtualBox is an application that allows your current computer to act as a virtual machine host system where you may install virtual guests, such as Linux into what amounts to a separate functioning computer system. Virtualbox runs on many different host operating systems (OSs) and supports a variety of guest operating systems including Linux. The host OS and guest OS can be different from one another. Your computer (host OS) can be a Windows, Mac, or Linux-based system but have guest Linux systems installed on it as VirtualBox VMs.

Downloading and installing Linux

Next, you’ll need to select a Linux distribution (distro) to install so that you can practice issuing commands, changing configurations, rebooting, installing software, creating users, and so on. I suggest that you should select a Linux distro based on the one that your current employer uses. If your company doesn’t use Linux yet or you’re not employed in a system administrator role, then select from one of the popular distributions described below:

Debian

Debian is a top-level distribution from which many other distributions are derived. Debian is community-supported, open source, and free.

OpenSUSE

OpenSUSE is a community-supported, top-level distribution that has many faithful followers worldwide. Its commercial version SUSE Linux Enterprise has widespread adoption.

Red Hat Enterprise Linux

Red Hat is a commercially-supported Linux that enjoys worldwide enterprise adoption and is now owned by IBM.

Ubuntu

Ubuntu is a very popular, Debian-derived community and commercially-supported distribution. Ubuntu also offers ready-made VirtualBox (and other) virtual machines to help you get a quick start.

The downloaded ISO file is a bootable Linux image. You don’t have to do anything to it if you use it to create a virtual machine. A virtual machine will boot from the ISO image and begin the installation process. After you’ve configured your virtual machine in VirtualBox, select Settings from the Oracle VM VirtualBox Manager, as shown in Figure 1-1.

Figure 1-1. The Oracle VirtualBox Manager application and a configured virtual machine.

Then, select Storage, as shown in Figure 1-2.

Figure 1-2. Virtual machine settings with Storage settings selected.

Select the empty optical disk drive under the IDE Controller in the Storage Devices pane and then select the optical disk icon in the Attributes pane to browse for your ISO image file. See Figure 1-3.

Figure 1-3. Select the ISO image from the list.

Once you’ve selected your ISO image, click OK to proceed. Now, when you start your VM, it will boot from this ISO image to begin installation onto your VM’s virtual disk.

When your system boots, you can accept the default settings. If you have some experience installing Linux, then you can change the default settings to suit your needs. Create yourself a user account when prompted to do so. If your distribution prompts you to give the root account a password, do so. You must remember this password because without it you’ll have to reinstall your Linux VM or try to recover it. Installing Linux can take several minutes and a reboot is required at the end of the installation process.

Getting to know your new Linux system

After installation, the first you need to do is to login using the username and password that you created during installation. Upon login, you’re placed into your home directory inside a shell or operating environment. Your home directory is a subdirectory of the /home directory. The Linux filesystem is a hierarchical filesystem, similar to Microsoft Windows. At the very top level, there is the root directory, which is represented by the / symbol. Windows uses a drive letter, such a C: for the root directory. On Windows, you can have many drive letters that all have their own root levels, such as C:, D:, E:, and so on. In Linux, there is only one root directory, /. All other directories are subdirectories of the root directory. Figure 1-4 is an illustration of the Linux root directory and its subdirectories.

Figure 1-4. The Linux Hierarchical Filesystem showing the root directory (/) and all of its subdirectories.

Note that there are only directories under the / (root) filesystem and no individual files. All files are kept in directories. You’ll explore many of these subdirectories throughout the rest of the book. The following table gives you a brief overview of the files and information contained in each directory.

Directory

Description

/

The root filesystem only contains other directories but no individual files.

/bin

The binaries directory contains executable files. Points to /usr/bin.

/dev

The device directory contains device files to address peripherals.

/etc

Contains system configuration files for users and services.

/home

User’s home directories.

/lib

System libraries files. Points to /usr/lib.

/media

Directory for mounting media such as USB drives or DVD disks.

/mnt

The mount directory for mounting remote filesystems.

/opt

Directory in which third-party software is installed.

/proc

A virtual filesystem that tracks system processes.

/root

The root user’s home directory.

/run

Variable and volatile run-time data.

/sbin

System binary (executable) files.

/srv

Might contain data from system services.

/sys

Contains kernel information.

/tmp

Temporary file directory for session information and temporary file storage.

/usr

Programs and libraries for users and user-related programs.

/var

Variable files such as logs, spools, and queues.

System files are protected from user modification. Only the root (administrative) user can modify system configuration files and settings. Users generally only have write access to their own home directories, the /tmp directory, and shared directories specifically created and modified by the administrator.

In the next section, you learn how to interact with your new Linux system at the command line.

Learning the command line interface

The command line interface or CLI is how most system administrators interact with their Linux systems because server systems don’t typically have a graphic interface. In Microsoft Windows terminology, a CLI only system, such as a Linux server, would be equivalent to a Windows Server Core system where you only have access to command line utilities.

As the name suggests, you interact with the Linux system using commands that you enter with a keyboard or standard input (stdin). The source from standard input can also be file redirection, programs, and other sources, but in the context for this book, stdin refers to keyboard input unless otherwise noted. Many commands are informational and display data about the system or system activities to the screen or standard output (stdout). Sometimes you’ll receive an error from the system that’s also known as standard error or stderr. You’ll see the shorthand and the long versions of these references used interchangeably throughout this text and in other Linux-related documentation that you’ll find elsewhere.

You must learn a few commands to successfully interact with the filesystem. And by learn, I mean know them without looking them up online. There’s only a handful of commands like this and there are few options that you should also commit to memory so that your interaction with the system becomes natural and efficient. And don’t worry about harming the system with any command that I cover. I’ll warn you when a command should be used with care or caution.

There are a few things you need to know before jumping into issuing commands. The first is that Linux doesn’t use file extensions. This means that the file, filename.exe has no more meaning to Linux than does the file, Financial_Report.txt or Resume.doc. They are all files and might or might or not be executable or text files. In Linux, you can name a file anything you want to.

The second thing to know about Linux is that filenames are case-sensitive. In other words, the two files, filename.txt and filename.TXT are two different files. I will prove this later in the chapter. For now, take my word for it. The third thing to know is that a file’s permission determines whether you can execute the file, edit the file, or even look at the file’s contents. Fourth, all Linux locations are stated from the / (root) directory. For example, if you mention the password file in Linux, it’s always shown as /etc/passwd. This is known as the absolute path and is the standard convention for speaking of or referring to files on the system.

Fifth, Linux assumes you know what you want to do and that you’ve spelled everything correctly when you issue a command, so be careful because some actions are irreversible.

Finally, Linux, like Unix, or more generally *nix systems are not “chatty” like the Windows® operating systems are. Linux systems, for example, don’t prompt you with an “Are you sure?” message when you remove (delete) files. The Linux system assumes that you want to execute the command that you issued and that you correctly spelled all parts of the command. Spelling counts at the Linux command line.

Commands for filesystem navigation

Navigating the Linux filesystem means exploring the various system directories, learning to return to your home directory, and listing directory contents in different ways. If you’re a Windows user and you’ve worked at the command prompt (CMD window) on that platform, then the Linux command line will be familiar to you.

The following short list of commands will acquaint you with the Linux filesystem, files, and the contents of your home directory.

pwd

The pwd or print working directory command displays where you are on the filesystem. If you issue the pwd command now, followed by the ENTER key, the command responds with /home/<your login name>. Always assume that you press the ENTER key after each command so that you can receive a response.

$ pwd

/home/student1

The $ is your shell prompt that shows you’re logged into the system as a user. You’ll use this command more later in the chapter.

cd

The cd, change directory, or current directory command places you into a new directory, returns you to your home directory, moves you to a higher level, or to a subdirectory. The cd command is analogous to the Windows cd command.

$ cd /etc

$ pwd

/etc

Simply entering cd returns you to your home directory regardless of where you are on the filesystem. From the example above.

$ pwd

/etc

$ cd

$ pwd

/home/student1

When you cd to a directory, use its absolute path.

$ cd /usr/bin

You can cd to a subdirectory without the absolute path if you’re currently in the parent directory.

$ cd

$ pwd

/home/student1

$ cd /usr

$ cd bin

$ pwd

/usr/bin

The cd command is one that you’ll use every day that you connect to a Linux system.

ls

The ls or list command displays a list of files and directories of the location you specify. If you don’t specify a location, ls displays the list of files and directories in your current directory.

$ cd

$ pwd

$ /home/student1

$ ls

You have no visible files on the system yet because you haven’t created any and none exist by default. However, you can list files from other directories by specifying the absolute path to the directory list you wish to see.

$ ls /usr/bin

a2x               getcifsacl                   p11-kit                   snmpping

a2x.py            getconf                      pack200                   snmpps

ac                getent                       package-cleanup           snmpset

There are too many files to list here in the /usr/bin directory, so I’ve truncated it to these few.

There are actually files in your home directory but they’re hidden because of the way they’re named. Files that begin with a period (.) are hidden from a regular ls command. To see these files, you must use a command option to allow you to see all files.

$ ls -a

.  ..  .bash_history  .bash_logout  .bash_profile  .bashrc  .gnupg  .zshrc

Your listing might vary slightly from this one but understand that all directories and files whose names begin with a (.) are hidden from standard file lists. You can cd into hidden directories or list files within them.

$ ls .gnupg

private-keys-v1.d  pubring.kbx

The ls command is one you’ll certainly use every time you login to your Linux system and is certainly one that you want to commit to memory. I will use the ls command throughout this book and introduce you to many more options for it along the way. Now that you’ve learned the basics of filesystem navigation, it’s time to cover rebooting and shutting down your system.

Starting, rebooting, and shutting down a Linux system

The most basic tasks facing any Linux sysadmin is that of starting, restarting, and shutting down a system. If you have experience with computers, you know that powering off a system without issuing a shutdown command is bad. It’s bad because doing so can, for example, corrupt open files, it can leave open files open, it disrupts running services, and it can cause problems with database transaction logs--possibly resulting in data loss.

Proper knowledge of how to start, restart, and shutdown a system is of great value to sysadmins.

Starting a system

For physical systems, you press the power button and release to start a system. This begins the power-on self tests (POST) and boot process. Watching the console during boot is important because the system notifies you and logs any issues on the way up. Your goal is to watch the screen for any errors or anomalies along the way. The worst message of all is a “kernel panic” which will be covered later in the book. Hopefully all is well with your system and the process ends with a login prompt.

The startup process is quite short but can identify systemic problems such as memory, disk, filesystem, and network issues. I’ll cover troubleshooting in a later chapter, but be aware now that you should watch the boot process carefully noting any problems for later investigation.

Restarting a system

Restarting or rebooting a system is a standard sysadmin practice. Although you might read or hear the contrary, there’s nothing wrong with rebooting your system. In fact, it’s recommended that you do so on a regular basis for all of the reasons stated under the previous section. Restarting a system clears memory, refreshes connections, and ensures that the system is healthy. A good reboot can cure certain nagging problems, such as an application that drains your system’s memory, but only temporarily.

Any issues that are resolved with a reboot should be investigated more thoroughly after the system is up and stable. Restarting a system gives you an opportunity to do some troubleshooting before application problems, logging problems, or network problems place the system back into a state when it requires another reboot.

Shutting down a system

Shutting down means issuing a command that gently and appropriately closes all programs and eventually powers off the system. This gentle shutdown also has the effect of warning users that the system is going down, so that everyone can save their work and logoff.

System shutdown should be reserved for hardware maintenance, relocation, or decommissioning. Some enterprise policies require that systems go through a full shutdown once a year to identify any hardware issues that might not manifest themselves except through a complete system failure. Technicians and sysadmins usually take this opportunity to perform hardware maintenance or hardware checks at the same time.

Summary

This first chapter gets you up and running with a live Linux system, covers some Linux basics, explores a few essential commands, and instructs you on the how and why of system startup, rebooting, and shutdown. In Chapter 2, you learn more about using the command line interface using commands to create, remove, and modify files. You also learn about Linux permissions, how to set them, how to interpret them, and how to set a global default permission for users.

Chapter 2. Diving Deeper into the Command Line Interface

For system administrators (sysadmins), the command line interface (CLI) is home. Typing at the keyboard is standard fare for sysadmins. You’ll need to become comfortable with the command line, its idiosyncrasies, and its shortcuts--yes, there are command line shortcuts. There’s a lot for you to learn about Linux at the command line. There are dozens of commands each with dozens of options. Sure, you’ll only use a handful of commands and a limited number of options for each command but you need to know how to find the options you need and how to use them when you need to.

The true power of the CLI is in its ease of use. The CLI was the first interface that users and programmers had with which to address their operating environments. The fact that the CLI is still in use some 50 years later is a testament to its power and its usefulness to the sysadmin and user alike. In this chapter, you learn to work at the command line as a regular user and as the root user. You also learn to set and modify file permissions, and the effects that those permissions have on files.

Working as a regular user

There are two user types on a Linux system: regular users and the root user. Regular users each receive their own home directory and a somewhat limited use of the system. Users have unlimited power in their own home directories to create, modify, remove, and manipulate files but have almost no power outside of that single location. Many system commands are available to regular users while other commands are restricted to those who either have been granted limited root user access through the sudo command or through direct access to the root user account.

The general, and most security conscious, rule is that you should always work as a regular user unless some task requires administrative (root user) access, which is covered in the next section.

Working as the root user

The administrator or root user is the all-powerful account on any Linux system. The root user can create, edit, move, or remove any file on the system. The root user can reboot, change runlevels, and shutdown the system. There are three methods of becoming the root user.

- Login as the root user

- Use the su (substitute user) command

- Use the sudo command

Login as root

You can directly login as the root user on a system either via SSH across the network, or interactively at the console. It’s not recommended to SSH to a system and login as root. The primary reason is that if you allow across-the-network root access to a system, then it’s possible that malicious actors can attempt to brute force a root login. You don’t want this to happen. Later in the book, I’ll show you how to prevent SSH root logins. Some Linux distributions prevent SSH root logins by default, while others leave it up to the administrators to decide.

You shouldn’t directly login as root at the console either because doing so prevents system logging from recording who has logged in and become root. Recording who uses the root user account is important because when something goes wrong, you want to know which administrator performed the actions. This record-keeping’s purpose is not to lay blame but is necessary to meet some regulatory requirements and to correct actions of a system administrator who needs a teachable moment or some advanced training. The next two options we discuss are better, safer ways to become the root user.

su to root

One of the appropriate methods of becoming the root user is to use the su (substitute user) command. The caveat with using su is that the user must know the root user password. If administrative users know the root password, then it’s difficult to prevent those same administrators from directly logging in as root. Using the su command to become root is acceptable but only if the root password changes after each use. In larger enterprises, security groups maintain root passwords and system administrators are allowed to check out the root password on a temporary basis to perform maintenance.

The root user may su to any other user account on the system without knowing the user’s password. This power gives administrators the capability to login as any user for troubleshooting purposes because it’s often difficult for users to accurately describe problems they’re experiencing. It also prevents a user from having to reveal their password to an administrator, which should force the user to change their password.

To su to another account is a simple procedure. Issue the su command and the user account you wish to su to. For this example, I use the full prompt rather than just the $ to demonstrate the user change.

[bjones@server1] $ su root

Password:

#

The # prompt informs you that you are now logged in as the root user. The user prompt is $ and the root is # to distinguish a standard user’s prompt from the root user’s prompt. Any command you issue now is done so with root privilege, which means that you must be careful because there are no restrictions on the account.

The better method of using su is to do so using the su - command because the - means that you also want to take on the root user’s full environment rather than just the account privilege. The display is much too long to show here but if you issue the env command, you’ll see the original user’s environment variables rather than root’s.

# env

Use the exit command to return to the original user account.

# exit

[bjones@server1] $

And now issue the su command with the - option. You don’t have to specify root in this command because the default is root.

[bjones@server1] $ su -

Password:

# env

The root user’s environment variables are now displayed. Using the su - command is the equivalent of logging into the console as the root user.

Actually, any user may su to any other user account but to do so requires one to know a user’s password.

[bjones@server1] $ su cdavis

Password:

[cdavis@server1] $

Use the sudo command

The best method to obtain root access is to use the “substitute user do” or “execute a command as another user” (sudo) command. The sudo command allows an appropriately configured user account to issue individual commands as the root user. The sudo command must precede each command issued. On first use, the sudo command requires that the sudoer (A user account configured for sudo use) supply their own password. Knowledge of the root password isn’t required.

$ sudo env

[sudo] password for bjones:

bjones is not in the sudoers file.  This incident will be reported.

[bjones@server1 ~]$

The warning that the user is not in the sudoers file means that the user account, bjones, is not configured in the /etc/sudoers file. In the next section, I demonstrate how to setup a user to be a sudoer.

NOTE

The sudo command, the /etc/sudoers file, and the sudoer user label are interesting because they have their own unique pronunciations. The accepted pronunciation for sudo is ‘soodoo’ and sudoer is ‘soodooer.’ Some sysadmins pronounce them as ‘soodoe’ and ‘soodoe-ers’ and no one takes issue with either pronunciation.

Creating a sudoer

You must have root user access to edit the /etc/sudoers file and you must use the visudo utility, whose only purpose is to edit the /etc/sudoers file. You can’t successfully edit it directly with vi, emacs, or any other text editor. To edit the /etc/sudoers file, issue the visudo command as root with no options.

# visudo

The /etc/sudoers file is a simple text file that describes users, groups, and commands allowed to work with root privileges. You can create a sudoer with very restrictive permissions (i.e., to run a single command as root) or permissive: Run any command as root without entering a password to do so. I prefer to configure a mixture of the two by creating sudoers who can run any command as root but must supply their password to do so.

There are hundreds of possible configuration scenarios for the /etc/sudoers file and for sudoers. It’s out of the scope of this book to explore more than what’s given here as examples. In this first example, I demonstrate how I set up my own user account to use sudo.

## Allow root to run any commands anywhere

root    ALL=(ALL)       ALL

khess   ALL=(ALL)       ALL

I copy the root user’s setting and insert my user account in its place. The setting takes effect immediately. It’s not recommended to set up a user account to use sudo without issuing a password. Using a password when issuing a command is an attempt to make it more difficult to make mistakes while wielding root privilege. The same can be said of the sudo command itself. The theory is that if an administrator has to issue the sudo command that they will make fewer mistakes as root because it requires the user to think specifically about their command action and its results.

Setting and modifying permissions

In this section you learn how to read, set, and modify file permissions. You must learn file permissions so that you can appropriately set and modify access to files and directories. Knowing file permissions also helps with troubleshooting when users can’t access a file or directory.

File permissions are simple but central to Linux security. Their simplicity can make them susceptible to neglect and misconfiguration. Frustrated sysadmins sometimes open permissions up to solve a problem but never return to the issue or reset the permissions to their proper settings.

Read, write, and execute

The three Linux file permissions or modes are read (r), write (w), and execute (x).

Read

View a file or list directory contents.

Write

Create and modify a file or copy, move, and create files in a directory.

Execute

Execute/run a file or cd into a directory.

As mentioned in Chapter 1, filenames have nothing to do with file actions. File actions and capabilities are all permission-based.

Using the rwx designations in permissions is known as symbolic mode. The symbolic mode is one of two methods of identifying permissions. The other is the numeric mode which assigns values to each of the rwx permission modes.

Numerical permission values

Each of the permission modes has its own assigned numerical value. This shortcut method makes setting permissions easier for sysadmins.

The read permission has a value of 4, write has a value of two, and execute has a value of 1. Permission values can range from 0 to 7. A zero permission value means no permission.

- Read - 4

- Write - 2

- Execute -1

- None - 0

In the next section, you find out how these permissions work together with group permissions to create a simple, but complete file security system.

Group permissions

There are four file group permissions: user, group, others, and all. The all group includes user, group, and others. It is a shorthand method of globally assigning permissions to a file or directory. Each group has a shorthand designation as well.

- User - u

- Group - g

- Other - o

- All - a

Users and sysadmins may set permissions on files for each group individually or for all groups at once. Each Linux file and directory is assigned read, write, and execute permissions for each group. The next section brings all of the permissions settings together .

Bringing permissions settings all together

The examples in this section will use the file, file.txt. If you want to follow along with the example, issue the following command to set up your file:

$ touch file.txt

This command creates an empty file named file.txt for you. Next, issue the ls command with the -l (long) option to see file permissions.

$ ls -l

-rw-rw-r--. 1 khess khess 0 Jun 19 17:35 file.txt

Figure 2-1 illustrates the positions and their designations (in red). The first position is for special file types such as directories that will have a d in that position. Regular files have a - to show that they’re not directories or other special files. The next nine positions are user, group, and other permissions locations. The first “triad” or three positions are for the user, the second for group, and the final three are for other users.

Figure 2-1. Special character position and user, group, and other permission locations

Figure 2-2 shows you the numerical permissions for each listing and then an explicit label for the user (u), group (g), and other (o) triads.

Figure 2-2. Numerical permission values and user, group, and other (ugo) designations.

As you can see from Figure 2-2 above, numerical permissions are additive for each triad to create a permission profile for a file. For example, a file with -rw-rw-r-- permissions has a numeric permission value of 664. The read permission has a value of 4 added to the value of the write permission, which is 2, equals six. All three possible permissions, rwx, yield a value of seven.

If a file has a permission equal to 750, the rwx representation is -rwxr-x---. This means that others outside of the designated user and group have no permissions for the file.

NOTE

The other group is often referred to as world. For example, if permissions for a file are -rw-rw-r--, this file is referred to as world readable rather than as other readable. Permissions for the other group are especially sensitive because allowing write or execute permissions to files and directories to others can be a security risk.

In the next section, you learn how to set and change file permissions using multiple methods.

Changing file permissions

Setting and changing file permissions or modes is a common system administrator task. Each file on the filesystem has its own individual permissions that either allows or denies access to users, groups, and others. To change file permissions, you use the chmod (Change mode) command. You can set or modify permissions with the chmod command in multiple ways. You don’t have to be consistent. You can use chmod with numeric, rwx, or ugo designations, but not both together in the same command. I demonstrate several possibilities and practical examples in the following sections.

NOTE

Some sysadmins find the symbolic (rwx and ugo) method easier to grasp than the numeric (0, 1, 2, 4) method. You can use either or both methods because they are equivalent to one another.

Symbolic mode

Changing permissions using the symbolic mode method is quite simple. Referring back to the original file.txt file that you created in a previous example, view the original permissions with the ls -l command.

$ ls -l

-rw-rw-r--. 1 khess khess 0 Jun 19 17:35 file.txt

The current file permissions aren’t adequate. You need to restrict anyone else but yourself from even reading this file. How do you do it? You remove the read permission from others. Removing is equivalent to subtraction because you are subtracting a permission from the current ones given to the file. So, to remove read permission from the file, you subtract read from others using the chmod command.

$ chmod o-r file.txt

$ ls -l

-rw-rw----. 1 khess khess 0 Jun 19 17:35 file.txt

You have removed read permission from the file for others. Now, no one but you can read (or write to) this file. When you create a shell script and attempt to execute it with ./file.sh and nothing happens, you should check the file’s permissions to see if you’ve added the execute permission to it.

NOTE

To execute an executable file or script that is not in your path, you must provide the absolute path to the file. If the file is in your current directory, you must tell the shell that it is in your current directory and that you’d like to execute it. Use ./script_name.sh to inform the shell that the file is executable and in your current directory. Here, script_name.sh is the name of the file you wish to execute.

$ touch file.sh

$ echo “echo Hello” > file.sh

$ ./file.sh

-bash: ./file.sh: Permission denied

Permission denied? But, I just created the file in my home directory. Checking permissions reveals the problem.

$ ls -l

-rw-rw-r--. 1 khess khess  11 Jun 29 19:58 file.sh

The file, file.sh, although named with a .sh extension, you recall that extensions have no effect in Linux and realize that file.sh isn’t executable because it doesn’t have the execute permission and therefore you receive the “Permission denied” message. To fix the problem, add the execute permission for yourself.

$ chmod u+x file.sh

$ ls -l

-rwxrw-r--. 1 khess khess 11 Jun 29 19:58 file.sh

Now, file.sh is executable.

$ ./file.sh

Hello

You can add or subtract multiple permissions from a file and even add and subtract permissions within the same command. Here are some examples of each action. The first command removes (deletes) (rm file.txt) the file from any previous example.

To add multiple permissions to a file:

$ rm file.txt

$ touch file.txt

$ ls -l

-rw-rw-r--. 1 khess khess   0 Jun 29 20:13 file.txt

$ chmod ug+x,o+w file.txt

-rwxrwxrw-. 1 khess khess 0 Jun 29 20:13 file.txt

To subtract multiple permissions from a file:

$ ls -l

-rwxrwxrw-. 1 khess khess 0 Jun 29 20:13 file.txt

$ chmod a-x,o-rw file.txt

$ ls -l

-rw-rw----. 1 khess khess 0 Jun 29 20:13 file.txt

Now add execute permission for all groups and remove read permission for others:

$ rm file.txt

$ touch file.txt

$ ls -l

-rw-rw-r--. 1 khess khess   0 Jun 29 20:13 file.txt

$ chmod a+x,o-r file.txt

$ ls -l

-rwxrwx--x. 1 khess khess 0 Jun 29 20:23 file.txt

WARNING

Be careful that you explicitly define which group you want to add or subtract permissions. The reason is that simply supplying a +x or -r defaults to all.

If you don’t specify to which groups you wish to add permissions or subtract permissions from, the default behavior is for the system to assume the intended group is all. This can be dangerous from a security perspective. Never grant a particular permission to all groups unless that is what you intended to do. The execute permission is granted to all groups because you didn’t explicitly define which group should receive it.

$ rm file.txt

$ touch file.txt

$ ls -l

-rw-rw-r--. 1 khess khess   0 Jun 29 20:34 file.txt

$ chmod +x file.txt

$ ls -l

-rwxrwxr-x. 1 khess khess 0 Jun 29 20:35 file.txt

The execute permission was granted to all groups because you didn’t explicitly define which group should receive it.

Numeric mode

For the purposes of clarity and comparison, the examples in this section are duplicates of the examples in the previous section. But here, we use the numeric mode (rather than the symbolic mode) of changing permissions. Create a new file and check its permissions.

$ rm file.txt

$ touch file.txt

$ ls -l

-rw-rw-r--. 1 khess khess   0 Jun 29 21:12 file.txt

Remove the read permission from the other group using the numeric method. First, calculate the current permission value of the file and then what you want the new value to be. Currently, the file’s permission value is 664. The desired value is 660.

$ chmod 660 file.txt

$ ls -l

-rw-rw----. 1 khess khess 0 Jun 29 20:12 file.txt

Using the numeric method, there’s no adding or subtracting of permissions. You simply reassign a value to the file. In a previous example, you added the execute permission to all and subtracted the read permission from others.

$ rm file.txt

$ touch file.txt

$ ls -l

-rw-rw-r--. 1 khess khess   0 Jun 29 20:13 file.txt

$ chmod a+x,o-r file.txt

$ ls -l

-rwxrwx--x. 1 khess khess 0 Jun 29 20:23 file.txt

The numeric equivalent is to reassign the value of the original file (664) to the new one (771).

$ rm file.txt

$ touch file.txt

$ ls -l

-rw-rw-r--. 1 khess khess   0 Jun 29 20:13 file.txt

$ chmod 771 file.txt

$ ls -l

-rwxrwx--x. 1 khess khess 0 Jun 29 20:23 file.txt

Either method of changing permissions is perfectly acceptable. There’s no stigma with using one over the other. Like most sysadmins, I use both methods interchangeably. It depends more on context and how quickly I want to do something. The process of changing permissions will become automatic to you with some practice and a few mistakes along the way.

Default permissions explained: umask

You might have noticed that when you create a new file, it’s created with specific permissions: 664 or -rw-rw-r--. For the root user the default permissions for a new file are 644 or -rw-r--r--. You might now wonder how this happens. There is a global setting called a umask or user file-creation mask that masks or filters certain permissions from being given to files by default. The execute permission is never given by default so it’s not explicitly masked by the umask setting. To find out what your system umask is, use the umask command.

$ umask

0002

You might now wonder why the umask reports four digits and we’ve only worked with three so far. The first (leftmost) digit is for special permissions such as setuid, setgid, and sticky, which I’ll cover in a later chapter. For now, focus on the other three digits: 002. These three digits correspond to rwx. When you create a new file, certain permissions are filtered out. In the case of the 002 umask, the write (w) permission is filtered out, so that new files are created as -rw-rw-r--. The 2 is for write. When a new file is created, the write permission is masked from the other group and therefore isn’t given to the new file.

For the root user, the umask is 0022. The write (w) permission is masked from both group and other. The reason for a umask is security. When a regular user creates a file, you don’t want everyone else to be able to write to it. You must explicitly grant this permission. For the root user, the umask prevents the root group and others from writing to files by default. This security feature prevents daemons or programs that might run as root from writing to certain sensitive files such as the /etc/passwd file. Everyone may read the file but only the root user may write to it.

You can change your own umask value by issuing the umask command and a new value. This temporarily changes the umask during your current login session.

$ umask 006

$ touch test.txt

$ ls -l test.txt

-rw-rw----. 1 khess khess 0 Jun 29 22:16 test.txt

To make this change permanent, do the following to append the new umask to the end of the .bashrc file:

$ echo umask 006 >> .bashrc

$ source .bashrc

$ umask

0006

Now, every time you login your umask will be set to 006 or 0006, which yields a more secure -rw-rw---- new default file permission.

Summary

In this chapter, you gained more experience working at the command line, you learned some new commands, and perhaps more importantly, you learned to read, set, and change file permissions. In Chapter 3, you learn some file editing basics and how to modify the user’s default environment.

About the Author

Kenneth Hess has been a Linux system administrator for more than 25 years and a technology writer and journalist for the past 20 years. Ken has written hundreds of articles covering desktop Linux, virtualization, databases, and the general topic of system administration.

1. 1. Getting Started with Linux

1. Installing Linux

1. Preparing your system for Linux

2. Downloading and installing Linux

3. Getting to know your new Linux system

2. Learning the command line interface

1. Commands for filesystem navigation

3. Starting, rebooting, and shutting down a Linux system

1. Starting a system

2. Restarting a system

3. Shutting down a system

4. Summary

2. 2. Diving Deeper into the Command Line Interface

1. Working as a regular user

2. Working as the root user

1. Login as root

2. su to root

3. Use the sudo command

4. Creating a sudoer

3. Setting and modifying permissions

1. Read, write, and execute

2. Numerical permission values

3. Group permissions

4. Bringing permissions settings all together

4. Changing file permissions

1. Symbolic mode

2. Numeric mode

3. Default permissions explained: umask

5. Summary

Table of Contents

1. Getting Started with Linux

Installing Linux

Preparing your system for Linux

Downloading and installing Linux

Getting to know your new Linux system

Learning the command line interface

Commands for filesystem navigation

Starting, rebooting, and shutting down a Linux system

Starting a system

Restarting a system

Shutting down a system

Summary

2. Diving Deeper into the Command Line Interface

Working as a regular user

Working as the root user

Login as root

su to root

Use the sudo command

Creating a sudoer

Setting and modifying permissions

Read, write, and execute

Numerical permission values

Group permissions

Bringing permissions settings all together

Changing file permissions

Symbolic mode

Numeric mode

Default permissions explained: umask

Summary