Chapter 2: Access The Command Line PDF

Summary

This document is an instructional guide on accessing the command line in a Linux environment. It covers introducing the bash shell, explaining the concepts of commands, options, and arguments, and describing how a regular user or superuser interacts with a terminal. It also discusses the concept of virtual consoles and logging into a remote or local system.

Full Transcript

Chapter 2. Access the Command Line Access the Command Line Objectives Log in to a Linux system and run simple commands with the shell. Introduction to the Bash Shell A command line is a text-based interface that is used to input instructions to a computer system. The Linux command line...

Chapter 2. Access the Command Line Access the Command Line Objectives Log in to a Linux system and run simple commands with the shell. Introduction to the Bash Shell A command line is a text-based interface that is used to input instructions to a computer system. The Linux command line is provided by a program called the shell. Many shell program variants have been developed over the years. Every user can use a different shell, but Red Hat recommends using the default shell for system administration. The default user shell in Red Hat Enterprise Linux (RHEL) is the GNU Bourne-Again Shell (bash). The bash shell is an improved version of the original Bourne Shell (sh) on UNIX systems. The shell displays a string when it is waiting for user input, called the shell prompt. When a regular user starts a shell, the prompt includes an ending dollar ($) character: [user@host ~]$ A hash (#) character replaces the dollar ($) character when the shell is running as the superuser, root. This character indicates that it is a superuser shell, which helps to avoid mistakes that can affect the whole system. [root@host ~]# Using bash to execute commands can be powerful. The bash shell provides a scripting language that can support task automation. The shell has capabilities that can enable or simplify operations that are hard to accomplish at scale with graphical tools. NOTE The bash shell is conceptually similar to the Microsoft Windows cmd.exe command- line interpreter. However, bash has a sophisticated scripting language, and is more similar to Windows PowerShell. On macOS, the bash shell was the default shell before macOS 10.15 Catalina. Starting from macOS 10.15 Catalina, Apple changed the default shell to the zsh shell, an alternative shell that is also available in RHEL. Shell Basics Commands that are entered at the shell prompt have three basic parts: Command to run. Options to adjust the behavior of the command. Arguments, which are typically targets of the command. The command is the name of the program to run. It might be followed by one or more options, which adjust the behavior of the command or what it does. Options normally start with one or two dashes (-a or --all, for example) to distinguish them from arguments. Commands might also be followed by one or more arguments, which often indicate a target that the command should operate on. For example, in the usermod -L user01 string, usermod is the command, -L is the option, and user01 is the argument. This command locks the password of the user01 user account. Log in to a Local System A terminal is a text-based interface to enter commands into and print output from a computer system. To run the shell, you must log in to the computer on a terminal. A hardware keyboard and display for input and output might be directly connected to the computer. This is the physical console from the Linux machine. The physical console supports multiple virtual consoles, which can run on separate terminals. Each virtual console supports an independent login session. You can switch between the virtual consoles by pressing Ctrl+Alt and a function key (F1 through F6) at the same time. Most of these virtual consoles run a terminal that provides a text login prompt. If you enter your username and password correctly, then you log in and get a shell prompt. The computer might provide a graphical login prompt on one of the virtual consoles. You can use the graphical login prompt to log in to a graphical environment. The graphical environment also runs on a virtual console. To get a shell prompt, you must start a terminal program in the graphical environment. The shell prompt is provided in an application window of your graphical terminal program. NOTE Many system administrators choose not to run a graphical environment on their servers, because users do not log in to servers as a desktop workspace. A server's workload can more effectively use the significant resources that a graphical environment uses. In Red Hat Enterprise Linux 9, if the graphical environment is available, then the login screen runs on the first virtual console, which is called tty1. Five additional text login prompts are available on virtual consoles two (tty2) through six (tty6). The graphical environment starts on the first virtual console that a login session is not currently using. Normally, your graphical session replaces the login prompt on the second virtual console (tty2). However, if an active text login session (not just a login prompt) is using that console, then the next free virtual console is used instead. The graphical login screen continues to run on the first virtual console (tty1). If you are already logged in to a graphical session, and switch to another user in the graphical environment without logging out, then another graphical environment is started for that user on the next available virtual console. When you log out of a graphical environment, it exits the virtual console, and the physical console automatically switches back to the graphical login screen on the first virtual console. NOTE In Red Hat Enterprise Linux 6 and 7, the graphical login screen runs on the first virtual console, but when you log in, your initial graphical environment replaces the login screen on the first virtual console instead of starting on a new virtual console. In Red Hat Enterprise Linux 8, the behavior is the same as in Red Hat Enterprise Linux 9. A headless server does not have a keyboard and display that are permanently connected to it. A data center might be filled with many racks of headless servers, and not providing each with a keyboard and display saves space and expense. For administrators to log in, a login prompt for a headless server might be provided by its serial console, which runs on a serial port that is connected to a networked console server for remote access. The serial console is normally used to access the server if the server network card becomes misconfigured and logging to the server over the conventional network connection becomes impossible. Most of the time, however, headless servers are accessed by other means over the network, for example by using Virtual Network Computing (VNC) for running a graphical interface on the target machine. Log in to a Remote System Linux users and administrators often need to get shell access to a remote system by connecting to it over the network. In a modern computing environment, many headless servers are virtual machines or are running as public or private cloud instances. These systems are not physical and do not have real hardware consoles. They might not even provide access to their (simulated) physical console or serial console. In Linux, the most common way to get a shell prompt on a remote system is to use Secure Shell (SSH). Most Linux systems (including Red Hat Enterprise Linux) and macOS provide the OpenSSH command-line program ssh for this purpose. In this example, a user with a shell prompt on the host machine uses ssh to log in to the remote Linux system remotehost as the user remoteuser: [user@host ~]$ ssh remoteuser@remotehost remoteuser@remotehost's password: password [remoteuser@remotehost ~]$ The ssh command encrypts the connection to secure the communication against eavesdropping or hijacking of the passwords and content. Some systems, such as new cloud instances, for tighter security do not allow users to use a password to log in with ssh. An alternative way to authenticate to a remote machine without entering a password is through public key authentication. With this authentication method, users have a special identity file with a private key, which is equivalent to a password, and which they keep secret. Their account on the server is configured with a matching public key, which does not have to be secret. When logging in, users can configure ssh to provide the private key. If their matching public key is installed in that account on that remote server, then it logs in the user without asking for a password. In the next example, a user with a shell prompt on the host machine logs in to remotehost as remoteuser with ssh, by using the public key authentication method. The ssh command -i option is used to specify the user's private key file, which is mylab.pem. The matching public key is already set up as an authorized key in the remoteuser account. [user@host ~]$ ssh -i mylab.pem remoteuser@remotehost [remoteuser@remotehost ~]$ For the connection to work, only the user who owns the file can have access to read the private key file. In the preceding example, where the private key is in the mylab.pem file, you can use the chmod 600 mylab.pem command to ensure that only the owner can read the file. How to set file permissions is discussed in more detail in a later chapter. Users might also have configured private keys that are tried automatically, but that discussion is beyond the scope of this section. The References at the end of this section contain links to more information about this topic. NOTE When you first log in to a new machine, you are prompted with a warning from ssh that it cannot establish the authenticity of the host: [user@host ~]$ ssh -i mylab.pem remoteuser@remotehost The authenticity of host 'remotehost (192.0.2.42)' can't be established. ECDSA key fingerprint is 47:bf:82:cd:fa:68:06:ee:d8:83:03:1a:bb:29:14:a3. Are you sure you want to continue connecting (yes/no)? yes [remoteuser@remotehost ~]$ Each time that you connect to a remote host with ssh, the remote host sends its host key to authenticate itself and to help to set up encrypted communication. The ssh command compares the host key against a list of saved host keys to ensure that it is not changed. If the host key changed, then it might indicate that someone is trying to pretend to be that host to hijack the connection, which is also known as an interceptor attack. In SSH, host keys protect against interceptor attacks; these host keys are unique for each server; and they need to be changed periodically and whenever a compromise is suspected. You get this warning when your local machine does not have a saved host key for the remote host. If you enter yes, then the host key that the remote host sent is accepted and saved for future reference. The login process continues, and you should not see this message again when connecting to this host. If you enter no, then the host key is rejected and the connection is closed. If the local machine does have a saved host key and it does not match the one that the remote host sent, then the connection is closed automatically with a warning. Log Out from a Remote System When you are finished with the shell and want to quit, you can choose one of several ways to end the session. You can enter the exit command to terminate the current shell session. Alternatively, finish a session by pressing Ctrl+D. The following example shows a user who logs out of an SSH session: [remoteuser@remotehost ~]$ exit logout Connection to remotehost closed. [user@host ~]$ Execute Commands with the Bash Shell Objectives Save time when running commands from a shell prompt with Bash shortcuts. Basic Command Syntax The GNU Bourne-Again Shell (bash) is a program that interprets commands that the user types. Each string that is typed into the shell can have up to three parts: the command, options (which usually begin with a hyphen - or double hyphen - - characters), and arguments. Each word that is typed into the shell is separated from other words with spaces. Commands are the names of programs that are installed on the system. Each command has its options and arguments. When you are ready to execute a command, press the Enter key. Type each command on a separate line. The command output is displayed before the following shell prompt appears. [user@host ~]$ whoami user [user@host ~]$ To type more than one command on a single line, use the semicolon (;) as a command separator. A semicolon is a member of a class of characters called metacharacters that have a special interpretation for bash. In this case, the output of both commands is displayed before the following shell prompt appears. The following example shows how to combine two commands (command1 and command2) on the command line. [user@host ~]$ command1 ; command2 command1 output command2 output [user@host ~]$ Write Simple Commands The date command displays the current date and time. The superuser or a privileged user can also use the date command to set the system clock. Use the plus sign (+) as an argument to specify a format string for the date command. [user@host ~]$ date Sun Feb 27 08:32:42 PM EST 2022 [user@host ~]$ date +%R 20:33 [user@host ~]$ date +%x 02/27/2022 The passwd command with no options changes the current user's password. To change the password, first specify the original password for the account. By default, the passwd command is configured to require a strong password, to consist of lowercase letters, uppercase letters, numbers, and symbols, and not to be based on a dictionary word. A superuser or privileged user can use the passwd command to change another user's password. [user@host ~]$ passwd Changing password for user user. Current password: old_password New password: new_password Retype new password: new_password passwd: all authentication tokens updated successfully. Linux does not require file name extensions to classify files by type. The file command scans the compiled header of a file for a 2-digit magic number and displays its type. Text files are recognized because they are not compiled. [user@host ~]$ file /etc/passwd /etc/passwd: ASCII text [user@host ~]$ file /bin/passwd /bin/passwd: setuid ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamica lly linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=a467cb9c8fa7306d41 b96a820b0178f3a9c66055, for GNU/Linux 3.2.0, stripped [user@host ~]$ file /home /home: directory View the Contents of Files The cat command is often used in Linux. Use this command to create single or multiple files, view the contents of files, concatenate the contents from various files, and redirect contents of the file to a terminal or to files. The following example shows how to view the contents of the /etc/passwd file: [user@host ~]$ cat /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin...output omitted... To display the contents of multiple files, add the file names to the cat command as arguments: [user@host ~]$ cat file1 file2 Hello World!! Introduction to Linux commands. Some files are long and might need more space to be displayed than the terminal provides. The cat command does not display the contents of a file as pages. The less command displays one page of a file at a time and you can scroll at your leisure. Use the less command to page forward and backward through longer files than can fit on one terminal window. Use the UpArrow key and the DownArrow key to scroll up and down. Press q to exit the command. The head and tail commands display the beginning and the end of a file, respectively. By default, these commands display 10 lines of the file, but they both have a -n option to specify a different number of lines. [user@host ~]$ head /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin [user@host ~]$ tail -n 3 /etc/passwd gdm:x:42:42::/var/lib/gdm:/sbin/nologin gnome-initial-setup:x:980:978::/run/gnome-initial-setup/:/sbin/nologin dnsmasq:x:979:977:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin The wc command counts lines, words, and characters in a file. Use the -l, -w, or - c options to display only the given number of lines, words, or characters, respectively. [user@host ~]$ wc /etc/passwd 41 98 2338 /etc/passwd [user@host ~]$ wc -l /etc/passwd ; wc -l /etc/group 41 /etc/passwd 63 /etc/group [user@host ~]$ wc -c /etc/group /etc/hosts 883 /etc/group 114 /etc/hosts 997 total Understand Tab Completion With tab completion, users can quickly complete commands or file names after typing enough at the prompt to make it unique. If the typed characters are not unique, then pressing the Tab key twice displays all commands that begin with the typed characters. [user@host ~]$ pasTab+Tab passwd paste pasuspender [user@host ~]$ passTab [user@host ~]$ passwd Changing password for user user. Current password: Press Tab twice. Press Tab once. Tab completion helps to complete file names when typing them as arguments to commands. Press Tab to complete as much of the file name as possible. Pressing Tab a second time causes the shell to list all files that the current pattern matches. Type additional characters until the name is unique, and then use tab completion to complete the command. [user@host ~]$ ls /etc/pasTab [user@host ~]$ ls /etc/passwdTab passwd passwd- Press Tab once. Press Tab once. Use the useradd command to create users on the system. The useradd command has many options that might be hard to remember. By using tab completion, you can complete the option name with minimal typing. [root@host ~]# useradd --Tab+Tab --badnames --gid --no-log-init --shell --base-dir --groups --non-unique --skel --btrfs-subvolume-home --help --no-user-group --system --comment --home-dir --password --uid --create-home --inactive --prefix --user-group --defaults --key --root --expiredate --no-create-home --selinux-user Press Tab twice. Write a Long Command on Multiple Lines Commands with many options and arguments can quickly become long and are automatically wrapped by the command window when the cursor reaches the right margin. Instead, type a long command by using more than one line for easier reading. To write one command in more than one line, use a backslash character (\), which is referred to as the escape character. The backslash character ignores the meaning of the following character. Previously, you learned that to complete a command entry, you press the Enter key, the newline character. By escaping the newline character, the shell moves to a new command line without executing the command. This way, the shell acknowledges the request by displaying a continuation prompt on an empty new line, which is known as the secondary prompt, and uses the greater-than character (>) by default. Commands can continue over many lines. One issue with the secondary prompt's use of the greater-than character (>) is that new learners might mistakenly insert it as part of the typed command. Then, the shell interprets a typed greater-than character as output redirection, which the user did not intend. Output redirection is discussed in an upcoming chapter. This course book does not show secondary prompts in screen outputs, to avoid confusion. A user still sees the secondary prompt in their shell window, but the course material intentionally displays only the characters to be typed, as demonstrated in the following example. [user@host ~]$ head -n 3 \ /usr/share/dict/words \ /usr/share/dict/linux.words ==> /usr/share/dict/words /usr/share/dict/linux.words

Use Quizgecko on...
Browser
Browser