System Administration - Linux PDF
Document Details

Uploaded by PraisingNurture2259
Yesmine Chalgham
Tags
Summary
This document is a guide to Linux system administration. It covers what Linux is, why it's useful, open-source software, and different types of Linux distributions, including Red Hat, Fedora, and CentOS. It also describes the command-line interface (CLI) and how to access a system remotely. The document is intended for those learning about Linux system administration, perhaps as a part of a course.
Full Transcript
System Administration : Linux Résumé Yesmine Chalgham + Cours + Chatgpt Chapter 1 Mimixa What is Linux ? A free and open-source (anyone can view, modify, and share its code )operatin...
System Administration : Linux Résumé Yesmine Chalgham + Cours + Chatgpt Chapter 1 Mimixa What is Linux ? A free and open-source (anyone can view, modify, and share its code )operating system that powers many devices and systems worldwide, known for its flexibility, security, and collaborative development. Linux is modular and can be configured as a full graphical desktop or a small appliance Why Learn Linux: It's widely used in internet infrastructure, cloud computing, supercomputers, mobile apps, and more. Learning Linux can boost your career opportunities and tech skills. -A Linux distribution is an installable operating system that is constructed from a Linux kernel and that supports user programs and libraries. What Makes Linux Great: ○ Open source: Anyone can view, modify, and share the code, leading to rapid innovation and transparency.//You can also experiment with changes and share them freely for others to use ○ Powerful CLI( command-line interface): Efficient automation and system administration. => easy access and powerful scripting. ○ Modular and flexible: Easy customization and upgrades.(easily replace or remove components) - System components can be upgraded and updated when needed. - A Linux system can be a general-purpose development workstation (configured with a full graphical user interface, development tools, programming languages, and libraries. It's ideal for software development, testing, and general computing tasks) or a purposefully minimized software appliance (stripped down to include only the essential components needed for specific tasks ; running a web server, database, or specialized application ) Open Source Software: 2 Software with publicly accessible source code, allowing for study, modification, and sharing. It promotes collaboration, transparency, and cost-effectiveness. (contraire de "proprietary" or "closed source") Open source has many benefits for the user: - Control: See what the code does and improve it. - Training: Learn from real-world code and develop more applications that are useful. - Security: Inspect sensitive code, and fix it even without the original developers' help. - Stability: Rely on code that can survive the loss of the original developer. Types of Open Source Licenses The software license terms control how the source can be combined with other code or reused. Two general classes of open source license are particularly important: ★ Copyleft (GPL, LGPL) / "share-alike" : Derivative works must also be open-source.( the code, with or without changes, must pass along the freedom for others to also copy, change, and distribute the code) ★ Permissive (MIT, BSD, Apache): Allow for commercial use and modification without sharing changes. (maximize code reusability Allows you to use the code in any way, including making it part of proprietary software. It doesn’t require you to share changes or keep it open.) * Copyleft License :GNU General Public License (GPL) / the Lesser GNU Public License (LGPL). *Permessive License : the MIT/X11 license, the Simplified BSD license, and the Apache Software License 2.0 Who Develops Open Source Software? Both professional developers, paid by organizations, and volunteers contribute to open-source projects. Linux distributions: ➔ A complete operating system built on top of the Linux kernel, providing a user-friendly experience with pre-installed software and tools. Key points about Linux distributions: 2 3 Open-source construction: Built by independent communities, not single companies. Pre-packaged convenience: Offer pre built and tested software for easy installation. Variety for choice: Cater to diverse needs with different features and focuses. Essential characteristics: Typically include a Linux kernel, user programs, installation and update tools, and support from vendors and communities. Redhat : - leading provider of open-source solutions, including Red Hat Enterprise Linux, JBoss middleware, and cloud technologies - the role of Red Hat is to help customers to connect with the open source community and their partners to effectively use open source software solutions. Fedora (community project) - Fedora is a community-driven Linux distribution known for its fast-paced innovation and cutting-edge features. Red Hat Enterprise Linux (RHEL) is commercially supported Linux distribution , leading platform for open-source computing - RHEL major releases are developed from the CentOS Stream project, which is derived from Fedora. Fedora is best for those seeking the latest technology and features. CentOS Stream serves as a bridge, allowing users to contribute to the development of RHEL while providing a more stable platform than Fedora. 3 4 RHEL is focused on providing a reliable and supported operating system for enterprise use, with guaranteed updates and long-term support RHEL for Edge (an image-based variant of RHEL with a different deployment mechanism ) - image-based:It uses a different method of deployment by creating operating system images with a tool called Image Builder. - Efficiency: IT teams can quickly build, deploy, and maintain these images, saving time over the system's lifecycle. - Customization: The images can be tailored for different edge environments. - RHEL for Edge includes: ★ Secure management: Ensures safety and control over the system. ★ Zero-touch provisioning: Automatically sets up devices without manual intervention. ★ System health visibility: Provides insights into the system's performance. ★ Quick security fixes: Allows for rapid updates and remediations through a single interface. Red Hat CoreOS (RHCOS) - It is not a stand-alone operating system, but it is built from RHEL components, and is then released, upgraded, and managed as part of the Redhat. - OpenShift Container Platform (RHOCP) for cloud-native applications. - RHCOS is fundamentally an image-based RHEL container host, which uses the Container Runtime Interface (CRI-O)-compliant container engine that is integrated in RHOCP. Red Hat Universal Base Image (UBI) - freely redistributable derivative of RHEL - It serves as a foundation for developing cloud-native and web applications within containers - similar to RHEL when run on a RedHat supported platforms such as OpenShift and RHEL hosts. 4 5 - Focus on application development /Includes base and application images (e.g., Python, Node.js) / Provides easy updates and dependency management. UBI: For building container applications. RHCOS: A container host for OpenShift. RHEL: A stable enterprise Linux operating system. RHEL for Edge: Optimized for managing edge computing environments. ___________________________________________________________ Chapter 2: Access the Command Line mimixa Command Line Interface (CLI): A text-based interface for interacting with a computer system using commands.(used to input instructions to a computer system) Shell: A program that provides the CLI, interpreting and executing commands. The default shell in Red Hat Enterprise Linux is Bash. -Every user can use a different shell, but Red Hat recommends using the default shell for system administration.; GNU Bourne-Again Shell (bash). The bash shell is an improved version of the original Bourne Shell (sh) on UNIX systems. Prompt: indicating the shell is ready for input. (It shows up before the command you type) Regular user prompt ends with $ ; [user@host ~]$ (they don’t have full control over system) superuser prompt ends with # ; [root@host ~]# Terminal: An interface that allows users to interact with the shell.( a display for output and a keyboard for input ) Command Structure: Commands that are entered at the shell prompt have three basic parts: ○ Command to run (The action you want to perform) ○ Options (adjusting behavior, start with - or - -) distinguish them from arguments. 5 6 ○ Arguments (targets of the command). Example: usermod -L user01 (locks password of user01) Logging In: ○ Locally: Physical Console: Keyboard and display for input and output directly connected to the computer. (You enter your username and password to log in/No graphical elements, only plain text..) Virtual Consoles: Multiple independent login sessions, accessed using Ctrl+Alt+Function keys (F1-F6). Graphical Environment: Provides a graphical login prompt, requires a terminal program to access the shell.(Often accessed after logging in through the physical console but provides a more visual experience, with icons, windows, and menus.) ○ Remotely:used to access and manage a computer from a different location Secure Shell (SSH): Encrypted connection for secure remote access. ( to connect securely to a different computer from your laptop even if you’re far away) ➔ Command: ssh username@remotehost (username is your account name on the remote computer//remotehost is the address or IP of the computer you’re trying to access)(baad yotlob alik mdps) Public Key Authentication: Passwordless login using private (kept on your local computer) and a public key (stored on the remote server) ➔ Command: ssh -i private_key_file username@remotehost ➔ -i private_key_file specifies the private key file to use. the remote server checks your private key against its public key, allowing access without needing a password. ➔ By avoiding passwords, this method reduces the risk of attacks based on stolen or guessed passwords. Logging Out: ○ exit command ○ Ctrl+D Commands Summary: usermod -L user01: Locks the password of user01 ssh username@remotehost: Logs in to a remote host using SSH ssh -i private_key_file username@remotehost: Logs in using public key authentication chmod 600 private_key_file: Sets permissions on a private key file exit: Logs out of the current shell session 6 7 Command Syntax: ○ Command, options (- or --), arguments separated by spaces ○ Press Enter to execute ○ Use semicolon (;) to separate multiple commands on one line Examples of Simple Commands the current username you’re logged in as : [user@host ~]$ whoami Finish: [student@workstation ~]$ lab finish cli-desktop (change to the student user home directory and use the lab command to complete this exercise. This step is important to ensure that resources from previous exercises do not impact upcoming exercises) lab: This is the command used for the specific lab exercises you're working on. finish: This tells the lab command to mark the exercise as complete. cli-desktop: This is the name of the exercise you are finishing.t ○ date: Prints the full date and time in a default format Output: Sun Feb 27 08:32:42 PM EST 2022 ○ date +%R: Displays time in 24-hour format Output: 15:32 ○ date +%x: Displays date in MM/DD/YYYY format Output: 12/26/2023 (+) as an argument to specify a format string for the date command. Passwd: ○ passwd: Changes a user's password Output: Interactive prompt for current and new password File: ○ file /etc/passwd: Identifies file type Output: /etc/passwd: ASCII text (“/etc/passwd” is a text file). ○ file /bin/passwd: Identifies file type Output: /bin/passwd: setuid ELF 64-bit LSB shared object, x86-64…(Shows it’s an ELF 64-bit executable file, which is a type of program in Linux.) ○ file /home: Identifies file type 7 8 Output: /home: directory ( ( This output shows that /home is a directory, not a regular file.) Viewing File Contents: cat: - view the contents of files, concatenate the contents from various files, and redirect contents of the file to a terminal or to files. ○ cat /etc/passwd: Displays entire contents of “/etc/passwd”(1) Output: Contents of the /etc/passwd file ○ cat file1 file2: Displays contents of multiple files Output: Contents of file1 followed by contents of file2. less: ○ less /etc/passwd: Displays one page at a time. Output: First page of /etc/passwd, Use the UpArrow key and the DownArrow key to scroll up and down. Press q to exit the command. - cat displays everything in one go.(which can be overwhelming for large files since it doesn’t pause) - less lets you view it page-by-page, offering more control for reading long files head: ○ head /etc/passwd: Displays first 10 lines.(by default) Output: First 10 lines of /etc/passwd -n option to specify a different number of lines. tail: ○ tail -n 3 /etc/passwd: Displays last 3 lines. Output: Last 3 lines of /etc/passwd wc: - counts lines, words, and characters in a file - Use -l(only the given number of lines), -w(only words), or -c(only characters) ○ wc /etc/passwd Output: 45 102 2480 /etc/passwd (lines, words, characters, filename) ○ wc -l /etc/passwd Output: 45 /etc/passwd (lines only) ○ wc -l /etc/passwd ; wc -l /etc/group Output: 45 /etc/passwd 70 /etc/group ○ wc -c /etc/group /etc/hosts Output: 966 /etc/group 516 /etc/hosts 1482 total (characters in each file and total) ○ (((((((Continuing a Long Command on Another Line ○ \ : escape character (Continues a command on the next line): Example: head -n 3 \ >/usr/share/dict/words \ (secondary prompt) >/usr/share/dict/linux.words the shell use > by default for secondary prompt(don’t type it , it appears automatically) 8 9 ○ Command History ○ history (Displays previously executed commands): history Output: (List of commands with numbers) ○ !number (Executes a command by its number): !26 Output: (Re-executes the command with number 26) ○ !string (Executes the most recent command starting with a string): !ls Output: (Re-executes the most recent command starting with "ls") ○ Editing the Command Line Ctrl + A Go to the start of the line. Ctrl + E Go to the end of the line. Ctrl + U Clear everything before the cursor. Ctrl + K Clear everything after the cursor. Ctrl + Left Arrow Move to the start of the previous word. Ctrl + Right Arrow Move to the end of the next word. Ctrl + R. Search your command history for something you typed before 9 10 Tab Completion Press Tab once to complete as much as possible. Press Tab twice to list all possible completions. ○ Examples: Completing commands: Type pas and press Tab twice(2) to see a list of commands starting with pas. Type pass and press Tab once(1) to complete to passwd. Completing file names: Type ls /etc/pas and press Tab to complete to ls /etc/passwd. Press Tab again to list files matching the pattern. Completing options: Type useradd -- and press Tab twice to see a list of available options.(--home-dir / --password..) 10 11 Chapter 3 : Manage Files from the Command Line Mimixa The File-system Hierarchy Linux uses a single, inverted tree structure to organize files and directories. The root directory (/) is at the top, with branches of directories and subdirectories extending below. The / character is used as a directory separator in file paths. Standardized subdirectories within the root directory serve specific purposes, making file organization and location efficient. The path /etc/issue guides you to a file named "issue": ○ Start at the root (/). ○ Descend into the "etc" subdirectory. ○ Find the file "issue" within that subdirectory. The following terms help to describe file-system directory contents: Static content remains unchanged until explicitly edited or reconfigured.(images, style sheets, scripts, or documentation files that don’t change automatically) Dynamic or variable content might be modified or appended by active processes (because of things happening on the computer.) for example (logs, temporary files, and data that applications might generate or update during their operation.) //a log file records events in real-time, so it’s constantly being updated. Think of it like a journal where you add new entries each day. Persistent content remains after a reboot, such as configuration settings.(This is content that stays on your computer even if you turn it off and back on. It’s like your phone’s contacts list—no matter how many times you restart your phone, the contacts are still there.) Runtime content from a process or from the system is deleted on reboot.This content is only needed temporarily while your computer is on. When you reboot, these files disappear. 11 12 Directory Purposes /boot: Stores files essential for system start up.( like the boot loader and kernel. Without these, the system can’t start.) /dev : holds special files that let the system interact with hardware like disks, USB drives, and keyboards /etc: Contains system configuration files and settings.(It’s where the system looks to find out how to configure and manage various services, like networking, user accounts, and installed applications.) /home: Holds personal directories for individual users. /root : Home directory for the administrative superuser, root. /run :Holds temporary runtime data for processes started since the last boot, like process ID and lock files.Everything here is deleted and recreated on reboot. (It combines the old /var/run and /var/lock directories.) /tmp : A temporary storage space for files that all users can write to. Files not accessed for 10 days are automatically deleted. There's also /var/tmp, another temporary directory where files are kept for up to 30 days if not accessed. /bin: Contains essential command-line programs that all users need, like basic commands (ls, cp, mv). /var: Holds variable data, such as logs, mail, and print queues. /usr: Stores most software applications and utilities(libraries). ★ /usr/bin : user commands ★ /usr/sbin : system administration command ★ /usr/local : locally customized software 12 13 Locating Files by Name Paths: specifies a file or directory’s unique file-system location. Spaces are allowed in a Linux file name but can lead to confusion when using the command line as spaces separate options and arguments.(the shell can misinterpret the command and assume that the file name is multiple arguments.) To avoid this mistake, surround such file names in quotation marks so that the shell interprets the name as a single argument. (cp "my file.txt" /destination/)/// consider using underscores _ or hyphens - to separate words. Red Hat recommends avoiding spaces at all in file names. Absolute Path: Specifies the complete location of a file, starting from the root directory (/). It always begins with a /. (long) Example: /home/user/Documents/thesis_chapter1.odf Relative Path: Specifies the location of a file relative to the current working directory. It doesn't start with a /. (short) Example: If you're currently in /home/user, the relative path to thesis_chapter1.odf would be Documents/thesis_chapter1.odf. Commands: pwd: Displays the current working directory's full path. ls: Lists the contents of a directory. Options: ➔ -l: Long listing format, showing file permissions, ownership, size, and modification time. (more info about each one of ls output ) ➔ -a: Shows all files, including hidden files (those starting with.) 13 14 ➔ ls -al : lists files in the current location, with a long format, and including hidden files ➔ -R: Lists the contents of subdirectories recursively. ○ ken taaml -R fi wst ldoc utalaalk l subdirectories ali f wst ldoc // ken taaml -R fi wst home ytalaalk dir w subdir Examples: cd: Changes the current working directory. ★ cd Documents: Enters the "Documents" subdirectory. ★ cd /etc: Goes directly to the "/etc" directory. ★ cd..: Moves up one level to the parent directory. ★ cd -: Switches back to the previous directory. ★ cd : when run without any arguments, will take you directly to your home directory, which is /home/user in this case. 14 15 touch: Creates empty files or updates timestamps. Example: touch newfile.txt # Creates an empty file named newfile.txt important ; Hidden Files: Files that start with a dot (.) are hidden and not visible with standard commands like ls unless specific options (e.g., ls -a) are used. - This behavior is not a security feature.They keep user configuration files organized and prevent clutter in home directories. - Many commands do not process hidden files by default to avoid accidental copying of personal configurations.(kima ls) File Permissions: To protect file contents from unauthorized viewing, Linux relies on file permissions, ensuring only authorized users can access or modify files. 15 16 Create Directories (mkdir) The mkdir command creates one or more directories or subdirectories -If you try to create a directory within a non-existent parent directory, the command will fail, and you'll receive an error message. -The mkdir command -p (parent) option creates any missing parent directories for the requested destination. In the following example, the mkdir command creates three ChapterN subdirectories with one command. The -p option creates the missing Thesis parent directory. * Use the mkdir command -p option with caution, because spelling mistakes can create unintended directories without generating error messages. imagine that you are trying to create a Watched subdirectory in the Videos directory, but you accidentally omitted the letter "s" in Videos in your mkdir command. [user@host ~]$ mkdir Video/Watched mkdir: cannot create directory Video/Watched: No such file or directory The mkdir command fails because the Video directory does not exist. If you had used the mkdir command with the -p option, then the Video directory would be created mcgh belaani w fi wstha watch 16 17 Copy Files and Directories (cp) The cp command copies a file (not a directory), and creates a file either in the current directory or in a different specified directory. By default, the cp command does not copy directories; it ignores them. You can use the cp command to copy multiple files to a target directory. The last argument must be the destination directory. The files will keep their original names in the new location. If a file with the same name already exists in the target directory, it will be replaced with the new one. cp -r : You can copy directories and their contents. ( In the following example, the Thesis directory and its contents are copied to the ProjectY directory. ) [user@host Documents]$ cd ProjectY [user@host ProjectY]$ cp -r../Thesis/. 17 18 (‘.’ yaani fel current directory ) Move Files and Directories (mv) 2 actions The mv command moves files to a new location or renames them without changing their contents. Moving a file to a different path is like giving it a new name in the file system. mv to rename : renames the thesis_chapter2.txt file to thesis_chapter2_reviewed.txt in the same directory. ( mv esm lkdim esm jdid ) mv to move a file to a different directory : The file thesis_chapter1.txt was moved from the current directory (Documents) to the Thesis/Chapter1 directory. You can use the mv command -v option to display a detailed output of the command operations. Summary mv source_file target_directory/ → Move file to a new directory. mv old_name new_name → Rename file in the same directory. mv source_file target_directory/new_name → Move file to a new directory and rename it. 18 19 Remove Files and Directories (rm) rm command removes files. By default, rm does not remove directories. rm -r : to remove directories and their content ( traverses each subdirectory first, and individually removes their files before removing each directory.) rm -ri option to interactively prompt for confirmation before deleting. rm -rf option : forces the removal without prompting the user for confirmation. ( aaks rm -ri) If you specify both the -i and -f options, then the -f option takes priority rmdir command to remove empty directories NB: Red Hat Enterprise Linux does not have an "undelete" command or a "trash bin" for files deleted from the command line. Trash bins only exist in desktop environments like GNOME. Make Links Between Files - you can create multiple file names that point to the same file. These file names are called links. - You can create either a hard link, or a symbolic link (sometimes called a soft link) Create Hard links - Every file starts with a single hard link, from its initial name to the data on the file system. When you create a hard link to a file, you create another name that points to that same data. - The new hard link acts exactly like the original file name. 19 20 - You can determine whether a file has multiple hard links by using the ls -l command => 1 is the link count ln command to create a hard link (another file name) that points to an existing file. - The command needs at least two arguments: a path to the existing file, and the path to the hard link that you want to create. ( ln existing_file /dir/new) ls -i : To determine whether two files are hard linked(to list each file's inode number). - If the files are on the same file system and their inode numbers are the same, then the files are hard links that point to the same data file content. 8924107 -rw-rw-r--. 2 user user 12 Mar 11 19:19 newfile.txt 8924107 -rw-rw-r--. 2 user user 12 Mar 11 19:19 /tmp/newfile-hlink2.txt NB : - Hard links to the same file share the same inode, which includes the link count, permissions, ownership, timestamps, and content. Changes made to one hard link affect all other hard links pointing to the same data, since they all reference the same storage location - Even if the original file is deleted, its contents remain accessible as long as at least one hard link exists. The data is only removed from storage when the last hard link is deleted, making the file unreferenced. Limitations of Hard Links : - ln is used only with regular files , not with directories 20 21 - Hard links require both files to be on the same file system. Different directories in the file system hierarchy may actually reside on separate storage devices. - df command to list the directories that are on different file systems. (to see different storage areas on your computer) - If two files are within directories that df shows under the same "Mounted on" section, you can link them. - If they’re in different sections (like / versus /boot), you can’t link them. ○ /home, /var, and /tmp are subdirectories of / and therefore share the same file system, /dev/mapper/system-root. ○ /boot is separate, mounted on /dev/sda1, so it’s on a different file system. Create symbolic links - ln -s option creates a symbolic link => soft link (ln -s [TARGET] [LINK_NAME]) - A symbolic link is not a regular file, but a special type of file that points to an existing file or directory. + Symbolic links can link two files on different file systems. + Symbolic links can point to a directory or special file, not just to a regular file. -> ln -s command creates a symbolic link for the” /home/user/newfile-link2.txt file”. The name for the symbolic link is “/tmp/newfile-symlink.txt”. - the /tmp/newfile-symlink.txt file is l (letter l) instead of -. This character indicates that the file is a symbolic link and not a regular file. When the original regular file is deleted, the symbolic link still points to the file but the target is gone (the content is gone). A symbolic link that points to a missing file is called a "dangling symbolic link". 21 22 NB: ○ One side-effect of the dangling symbolic link : if you create a file with the same name as the deleted file (/home/user/newfile-link2.txt), then the symbolic link is no longer "dangling" and points to the new file. ○ Hard links do not work in this way. If you delete a hard link and then use normal tools (rather than ln) to create a file with the same name, then the new file is not linked to the old file. A hard link points a name to data on a storage device.(file’s data) A symbolic link points a name to another name, which points to data on a storage device. - A symbolic link can link to a directory, acting like a shortcut. When you cd to a symbolic link that points to a directory, it takes you to that directory but shows the link’s name as the current location. Some tools track that you arrived via a symbolic link. - Using cd -P : updates your working directory with the actual path to the directory, not the symbolic link name. —----------------------------------------------------------------------- Matching File Names Using Path Name Expansion (Use pattern matching in the Bash shell to run commands on multiple files at once.) 22 23 Command-line Expansions : When you enter a command in the Bash shell, it processes that command through multiple expansions before running it. These expansions make it easier to perform complex tasks. Here are the main types of expansions: 1. Brace Expansion: Generates multiple strings of characters. Example: echo file{1,2,3} outputs file1 file2 file3. 2. Tilde Expansion: Expands to the path of a user’s home directory. Example: cd ~ takes you to your home directory. 3. Variable Expansion: Replaces text with the value of a shell variable. Example: If name="Alice", then echo Hello, $name outputs Hello, Alice. 4. Command Substitution: Replaces text with the output of a command. Example: echo Today is $(date) shows the current date. 5. Pathname Expansion (or globbing): Matches file and directory names using patterns.( use patterns like * to match multiple files at once) Example: ls *.txt lists all files ending with.txt. 1. Pattern Matching (Globbing): Matches filenames with patterns containing metacharacters. -Pathname expansion uses special characters to match file names based on patterns. Before executing a command, the shell replaces the pattern with a list of matching file names. -If no matches are found, the shell treats the pattern as a literal argument.( the shell will just use the pattern as it is, treating it like a regular word.) 23 24 mkdir glob; cd glob ➔ Creates a new directory named "glob" in the current working directory. ➔ Changes the current working directory to the newly created "glob" directory. ls [ac]* : Lists files that start with either the letter "a" or the letter "c 24 25 ->the two commands match only file names with four and five characters in length, respectively. Tilde Expansion (~) Purpose: Expands ~ to the current user's home directory. Examples: - echo ~root -> Output: /root - echo ~user -> Output: /home/user - echo ~/glob -> Output: /home/user/glob Brace Expansion {} Purpose: Brace expansion generates strings based on a defined pattern inside braces {} - You can use comma-separated lists or sequences to create multiple outputs. You can also nest brace expansions. Examples: - echo {Sunday,Monday,Tuesday,Wednesday}.log -> Output: Sunday.log Monday.log Tuesday.log Wednesday.log - echo file{1..3}.txt -> Output: file1.txt file2.txt file3.txt - mkdir../RHEL{6,7,8} -> Creates directories RHEL6, RHEL7, and RHEL8 25 26 Variable Expansion -A variable acts like a named container that stores a value in memory Purpose: Replaces variables with their stored values. Syntax: $ VARIABLENAME=value -Variable names can contain only letters (uppercase and lowercase), numbers, and underscores. Variable names are case-sensitive and cannot start with a number Command Substitution Purpose: Replaces a command with its output.(Used when you want to get data from a command.) Syntax: $(command) - While backticks (`command`) are still accepted for command substitution, it's best to avoid them due to potential visual confusion with single quotes and their inability to be nested. 26 27 Protecting Arguments from Expansion Purpose: Prevents unintended expansion of special characters. Methods: 1. Backslash (\): ○ Escapes the special meaning of the next character. Output: The value of $HOME is your home directory. (The dollar sign is printed literally.) 2. Single Quotes ('): ○ Prevent all expansion within them. ○ Anything enclosed in single quotes is treated as literal text. ○ Example : For example, if you write 'Hello $USER', it will output Hello $USER exactly as it is, without replacing $USER with the actual username 3. Double Quotes ("): ○ Allow variable and command substitution, but prevent globbing (filename expansion using wildcards like * ,? and !). ○ Example: echo "Today is $(date +%A)" Output: Today is Wednesday (assuming it's Wednesday; date command is substituted, but * wouldn't expand if present) —-------------------------------------------------------------------------------- CHAPTER 4 : Get Help in Red Hat Enterprise Linux Manual Pages (man pages): (source of documentation) Built-in form documentation for Linux commands, files, and concepts. 27 28 They provide detailed information about commands, programs, and features directly on the command line. (how to use a command or find specific options) Accessed using the man command.(like man ls) The pages are stored in subdirectories of the /usr/share/man directory. To distinguish identical topic names in different sections, man page references include the section number in parentheses after the topic (e.g., 1 for user commands, 5 for file formats, 8 for administration). the man topic command : To read specific man pages, Specify a section number to view a specific page (, man 5 passwd displays passwd(5). Navigation and Search: Efficiently searching for topics and navigating man pages is an essential administration skill. While GUI tools help configure common system resources, using the command line is often more efficient. To navigate the command line effectively, it’s crucial to find the information you need in man pages. 28 29 Navigate within a page using Spacebar, Page Up/Down, arrow keys, D/U, G/Shift+G. Search for text using /string. Repeat search with N/Shift+N. Exit with Q. Keyword Search: man -k or apropos keyword : to search for a keyword in titles and descriptions. Search full text using man -K (uppercase) (more resource-intensive). ↳ the keyword search displays a list of keyword-matching man page topics with section numbers. 29 30 Man Page Structure: - Man pages separate each topic into several parts. Most topics use the same headings and follow the same order. Typically, a topic does not feature all headings, because not all headings apply to all topics. (Just like a book has chapters and sections, a man page has different parts to explain things. But not every book will have all the chapters, just the ones that are relevant to that topic.) Common headings: ○ NAME: Subject name and brief description ○ SYNOPSIS: Command syntax summary (it shows how to write the command) ○ DESCRIPTION: Basic understanding of the topic(how it works, and the context in which it is used.) ○ OPTIONS: Command execution options(options you can use with the command) ○ EXAMPLES: Usage examples ○ FILES: Related files and directories( that the command might use or affect) ○ SEE ALSO: Related man pages ○ BUGS: Known bugs (+provide information on how to report new bugs if you encounter any.) ○ AUTHOR: Contributors Notes from exercices : - Use the man man command to determine how to prepare a man page for printing - The man -t option prepares a man page for printing, converting it to a PostScript format. man -t bash | lpr -Pps - | (Pipe): This symbol takes the output of the command on its left (man -t bash) and passes it as input to the command on its right (lpr -Pps). - lpr: This is the command to send files to the printer. -Pps: This specifies the printer named ps. - > symbol : When you run a command in the terminal, you can save its results into a file >. This is called "output redirection." 30 31 exp : To save a list of file names from your home directory into a file, you can use the ls command like this ls > /tmp/my-file-names (/tmp/my-file-names: This is the path where the output will be saved) -Use the file command to determine the file format.(when you used -t , the format will be postscript format) -man -k Search in the man pages for information about PostScript files. # man -k postscript viewer ; finds man pages that match any word; such as "postscript" or "viewer" in their descriptions. - man evince : to learn how to use the viewer in preview mode. —-------------------------------------------------------------------------------------------------------- CHAPTER 5: Create, View, and Edit Text Files Editing Text Files from the Shell Prompt Objectives: ➔ Create and edit text files from the command line using the Vim editor. Editing Files with Vim Vim is a powerful text editor commonly found on Linux and Unix-like systems. It's often used for editing configuration files and system administration tasks. It has multiple modes of operation, each with specific functions. Vim: always installed by a default on a server for editing text-based files Benefits of the Vim editor : If a system uses a text-only shell, knowing a text editor like Vim is essential for editing configuration files through terminal access, SSH, or Web Console. -Vim is commonly pre-installed on servers and follows the POSIX standard, making it compatible across Linux and many Unix-like systems. Additionally, platforms like macOS also include Vim by default, so skills learned on Linux are transferable to other environments. Starting Vim:(2 packages) 31 32 Here’s a quick guide on installing and starting with Vim on Red Hat Enterprise Linux (RHEL), where you can choose between two packages: 1. vim-minimal: vi filename A lightweight package with core features. 2. vim-enhanced: vim filename Includes advanced features, an online help system, and a tutorial. -If vim-enhanced is installed, typing vi will automatically use Vim, thanks to a shell alias for regular users. -To use the original vi command (without Vim), a regular user can type \vi to override the alias. -The alias doesn't apply to the root user or system users (UIDs below 200), ensuring system services still use the basic vi.(not vim) -To compare features, use \vi --version and vim --version. Vim Operating Modes: Command mode (default): Navigation, cut/paste, text manipulation Edit mode: the mode where you directly type text( i key) // return to Command mode, press the Esc key. Visual mode: Select text (press v, Shift+V, or Ctrl+V) ○ Single-line selection: Press the v key. 32 33 ○ Multi-line selection: Press Shift+v or V. ○ Block selection: Press Ctrl+v. Extended command mode: Save, quit, other tasks (press : ) ⇒If you are unsure which mode Vim is using, then press Esc a few times to get back into command mode. It is safe to press the Esc key in command mode repeatedly. Basic Workflow:(keystrokes) Enter insert mode (i) Type text Exit insert mode (Esc) Undo the most recent edit (u) Delete a single character(x) Save file (:w) & remains in command mode for more editing. Quit Vim (:wq or :q!) : ○ : wq = saves the file and quits Vim. ○ :q!= quits Vim, and discards all file changes since the last write. Rearranging Text: Copy and paste is called "yank" and "put": ○ Visually select text (v, Shift+V, or Ctrl+V) ○ Yank (copy) selection (y) ○ Move cursor to new location ○ Put (paste) selection (p) Visual Mode: useful to highlight and manipulate text in different lines and columns. Character mode (v): Highlight characters - Move the cursor to select the text. The word "VISUAL" will appear at the bottom of the screen. If you want to delete the word "hello" in the text: 1. Place the cursor at the beginning of "hello". 2. Press v, then move right using the arrow key to highlight the word. 3. Press d to delete the highlighted text 33 34 Line mode (Shift+V): Highlight lines - Move the cursor up or down to select whole lines. "VISUAL LINE" appears at the bottom If you want to delete the whole line containing the word "hello": 1. Place the cursor on the line. 2. Press Shift+v to highlight the entire line. 3. Press d to delete the whole line. Block mode (Ctrl+V): Highlight rectangular blocks (ideal for columns or structured data) - Use the arrow keys to expand the selection in a block shape. "VISUAL BLOCK" appears at the bottom. If you want to delete a block of text in columns (e.g., removing the first column in a list): 1. Place the cursor at the start of the column you want to select. 2. Press Ctrl+v to begin selecting in block mode. 3. Use the arrow keys to highlight the text block (e.g., a column of numbers). 4. Press d to delete the selected block. Vim Configuration Files : The /etc/vimrc and ~/.vimrc files in Vim are used to configure and customize the behavior of the editor(tab spacing, syntax highlighting, color schemes…) ○ /etc/vimrc: This file affects the behavior of Vim for all users on the system (global settings). ○ ~/.vimrc: This file is specific to the user and allows for personalized settings Scenario 1: Editing a Configuration File Imagine you're managing a web server and need to adjust a setting in its configuration file /etc/httpd/conf/httpd.conf. Here's how you can use Vim: 1. Open the file: vim /etc/httpd/conf/httpd.conf 2. Enter insert mode: Press i 3. Find the line with the setting: Use the arrow keys or search commands like /Listen 4. Modify the setting value: Change the port number or another parameter 5. Exit insert mode: Press Esc 6. Save the changes: Type :w 7. Quit Vim: Type :wq 34 35 Scenario 2: Copying Text from Log Files You're troubleshooting an issue and need to copy specific lines from multiple log files: 1. Open the first log file: vim /var/log/messages 2. Enter visual line mode: Press Shift+v 3. Select the relevant lines: Use the arrow keys to highlight them 4. Yank the selection: Press y 5. Open the second log file: vim /var/log/httpd 6. Move the cursor to the target location: Use the arrow keys 7. Paste the copied lines: Press p 8. Repeat steps 2-7 for other log files if needed Scenario 3: Rearranging Lines in a Script You're writing a shell script and need to swap the order of two lines: 1. Open the script: vim my_script.sh 2. Move the cursor to the first line to swap: Use the arrow keys 3. Enter visual character mode: Press v 4. Move the curs 5. or to the end of the line: Press right arrow key 6. Yank the line: Press y 7. Move the cursor to the target line: Use the arrow keys 8. Enter visual character mode again: Press v 9. Move the cursor to the beginning of the line: Press Home 10. Put the copied line before the current line: Press p Standard Input, Standard Output, and Standard Error In Linux, every running program (called a process) uses numbered channels called file descriptors to handle input and output. 35 36 Redirect Output to a File: 36 37 In Linux, every running program (called a process) uses numbered channels called file descriptors to handle input and output. stdin , stdout , stderr You can redirect these streams using commands: > redirects stdout to a file |>> append (add to the content) but >(replace it) 2> redirects stderr to a file.| 2>> append < redirects stdin from a file. Explanation with examples : > file: Example: echo "Hello" > output.txt Writes "Hello" into output.txt, replacing its contents if it already exists. >> file: Example: echo "World" >> output.txt Adds "World" to the end of output.txt without removing existing content. 2> file: Example: ls wrongfile 2> errors.txt if wrongfile doesn’t exist , the error message is saved in errors.txt , replacing its contents if it already exists. 2> /dev/null : Example: ls wrongfile 2> errors.txt Errors (stderr)[error message ("No such file or directory"] are redirected to /dev/null, so you don’t see them. Only normal output (if any) remains visible. > file 2>&1 or &> file : Example: ls somefile > output.txt 2>&1 - If somefile exists: Its name is written to output.txt. - If somefile doesn't exist: The error message ("No such file or directory") is also written to output.txt. If you want to add (append) output and errors to the file without overwriting: ls somefile ls somefile >> output.txt 2>&1 Order of Redirections: The order of redirections matters. For example : 37 38 - > output.log 2>&1 sends both stdout and stderr to output.log - 2>&1 > output.log sends only stdout to output.log and stderr to the terminal (Here, first, stderr is redirected to the terminal (because stdout is still going to the terminal at this point). Then, stdout is redirected to the file output.log. So normal output (stdout) goes to the file, but error messages (stderr) stay in the terminal.) For this reason, some people prefer to use the merging redirection operators: - &> output.log instead of > output.log 2>&1 - &>> output.log instead of >> output.log 2>&1 (in Bash 4 or RHEL 6 and later) - (they are not standardized and may not be supported across all environments) Command Examples and Output: Redirecting Output: date > /tmp/saved-timestamp: Saves the current date and time to the file /tmp/saved-timestamp. tail -n 100 /var/log/secure > /tmp/last-100-log-secure: Copies the last 100 lines of the file /var/log/secure to the file /tmp/last-100-log-secure. cat step1.sh step2.log step3 step4 > /tmp/all-four-steps-in-one: Combines the contents of four files into a single file named /tmp/all-four-steps-in-one. ls -a > my-file-names: Lists all files (including hidden ones) in the current directory and saves the output to the file my-file-names. Appending Output: echo "new line of information" >> /tmp/many-lines-of-information: Adds a new line of text to the end of the file /tmp/many-lines-of-information. Redirecting Error Messages: find /etc -name passwd 2> /tmp/errors: Sends any error messages from the find command to the file /tmp/errors, while displaying normal output on the terminal. find /etc -name passwd > /tmp/output 2> /tmp/errors: Saves normal output to /tmp/output and error messages to /tmp/errors. 38 39 find /etc -name passwd > /tmp/output 2> /dev/null: Saves normal output to /tmp/output and discards error messages. Redirecting Both Output and Errors: find /etc -name passwd &> /tmp/all-message-output: Combines both standard output and standard error into the file /tmp/all-message-output. find /etc -name passwd >> /tmp/all-message-output 2>&1: Appends both standard output and standard error to the file /tmp/all-message-output /tmp/all-message-output. Construct Pipelines Pipelines: Combine multiple commands, sending the output of one command as input to the next. Use the pipe symbol (|) to connect commands. Pipelines and I/O redirection both manipulate standard output and standard input. - Pipelines send the standard output from one process to the standard input of another process. - I/O Redirection sends output to a file or takes input from a file. Examples: ls -l /usr/bin | less: View a long directory listing one screen at a time. ls | wc -l: Count the number of files in a directory. 39 40 ls -t | head -n 10 > /tmp/first-ten-changed-files: Save the first 10 recently changed files to a file. Redirecting Output in Pipelines: When you combine redirection and a pipeline, the shell sets up the pipeline first, then handles redirection [user@host ~]$ ls > /tmp/saved-output | less - ls > /tmp/saved-output: Redirects the output of ls to the file /tmp/saved-output. - | less: less receives nothing because the output was already redirected to the file, so it displays nothing. The tee command overcomes this limitation. tee copies input to both standard output and files: It allows you to view output on the terminal while simultaneously saving it to one or more files. Position of tee matters: (dima tktb tee + file) ○ Middle of a pipeline: Sends output to both the next command and a file. Example: ls -l | tee /tmp/saved-output | less displays output on the terminal and saves it to a file. ○ End of a pipeline: Displays output on the terminal and saves it to a file. Example: ls -t | head -n 10 | tee /tmp/ten-last-changed-files Appending with -a: Use tee -a to append output to a file instead of overwriting it. 40 41 ○ Example: ls -l | tee -a /tmp/append-files Redirecting stderr: ○ Use 2>&1 before the pipe to redirect both stdout and stderr. ○ Example: find / -name passwd 2>&1 | less ○ you cannot use the merging redirection operators (&> and &>>). Change the Shell Environment : Shell Variables Usage : - In Bash, you can use shell variables to store values or modify the shell's behavior. - These variables are useful for simplifying commands or setting common options for commands you run. - Shell variables are stored within a specific shell session (e.g., one terminal window or login session). They only apply to the current session. - If you export a shell variable, it becomes an environment variable. These variables are automatically passed to any programs or commands run from that shell. Assign Values to Variables : [user@host ~]$ VARIABLENAME=value MY_VAR="Hello" Variable names can contain UPPERCASE or lowercase letters, digits, and the underscore character (_) [user@host ~]$ COUNT=40 [user@host ~]$ first_name=John [user@host ~]$ file1=/tmp/abc [user@host ~]$ _ID=RH123 set command to list all shell variables that are currently set.(It also lists all shell functions, which you can ignore.) 41 42 Retrieve Values with variable expansion : To retrieve the value of a variable in Bash, you use variable expansion by prefixing the variable name with a dollar sign ($) - You can also use a variable to refer to a long file name for multiple commands Use curly braces {} when a variable is followed by characters to ensure correct expansion. 42 43 Configure Bash with Shell Variables : Some shell variables are set when Bash starts. You can modify them to adjust the shell's behavior. HISTFILE: Specifies the file where the shell history is saved (default is ~/.bash_history) HISTFILESIZE: Sets the maximum number of commands to save in the history file. HISTTIMEFORMAT: Defines the time format for each command in the history. This variable does not exist by default, so you need to set it manually. The PS1 variable in Bash controls the appearance of the shell prompt. By modifying the value of PS1, you can customize how your prompt looks, such as showing the current user, hostname, or working directory. Default Prompt : PS1="bash\$ " => $ appears as the default prompt for a regular user. Customized prompt : PS1="[\u@\h \W]\$ " ○ \u: Username \h: Hostname ○ \W: Current working directory(basename) ○ $: The prompt symbol for a regular user -Red Hat recommends adding a trailing space at the end of the prompt to improve readability -When the PS1 value contains spaces, tabs, or returns, it must be enclosed in either single or double quotes. Omitting quotes can lead to unexpected results. 43 44 Configure Programs with Environment Variables : The shell environment includes information like the current directory, command-line options, and environment variables that control how programs behave. Shell variables are only used by the shell itself. Environment variables are set by the shell and can be used by both the shell and any programs you run from it. To make a shell variable accessible to programs, you export it as an environment variable. (you use the export command) OR Examples : the shell automatically sets the HOME variable to the file name of the user's home directory when it starts. You can use this variable to help programs to determine where to save files. The LANG environment variable sets the locale encoding for your system, affecting various aspects like language, character encoding, date formats, and sorting behavior. ○ en_US.UTF-8 : US ENGLISH with UTF-8 Unicode encoding. ○ fr_FR.UTF-8, then it uses French UTF-8 Unicode encoding. The PATH variable contains a list of colon-separated directories that contain programs: - When you type a command like ls, the shell looks through these directories to find the ls executable, typically located in /usr/bin/ls. 44 45 Appending a Directory to PATH: If you want to add a directory (e.g., /home/user/sbin) to the PATH for the current session, you can use the export command: => This adds /home/user/sbin to the end of the existing PATH. After that, any executables in /home/user/sbin will be accessible just like system commands. env command To list all the environment variables for a shell Set the Default Text Editor : The EDITOR environment variable specifies your default text editor for command-line programs. By default, many command-line programs use vi or vim if the EDITOR variable is not set. However, you can change this to another text editor of your choice [user@host ~]$ export EDITOR=nano to set nano as your default text editor. By convention, environment variables and shell variables that are automatically set by the shell have names with all uppercase characters. If you are setting your own variables, then you might want to use names with lowercase characters to prevent naming collisions. Set Variables Automatically : When Bash starts, it uses specific files to set up your environment. These files can be edited to automatically set variables when the shell starts The exact script that runs depends on whether the shell is - interactive (the user directly interacts with the system(terminal) ) - non-interactive(A shell that runs in the background without user input (script) - and whether it is a login (A shell that is initiated when a user logs in locally or remotely) - or non-login shell( invoked from an existing session, such as to open a terminal from the GNOME GUI) 45 46 For Interactive Shells: Login shells: Run when you log in, using /etc/profile (system-wide) and ~/.bash_profile (user-specific). These may also source /etc/bashrc and ~/.bashrc.. Non-login shells: Run when you open a terminal, using /etc/bashrc and ~/.bashrc(user-specific) Non-interactive Shells: Used for scripts. Can run files defined by the BASH_ENV variable (if set because This variable is not set by default). To set variables: ★ Use ~/.bashrc for variables across all terminal sessions. ★ Use ~/.bash_profile for variables applied once after login. ★ The best way to adjust settings that affect all user accounts is to add a file with a.sh extension that contains the changes to the /etc/profile.d directory. To create the files in the /etc/profile.d directory, log in as the root user. Bash Aliases - Bash aliases are shortcuts to other Bash commands - alias command to create aliases 46 47 Unset and Unexport Variables and Aliases - unset command : To unset and unexport a variable - export -n :To unexport a variable without unsetting it (removed from the environment but ket as shell variable ) - unalias :To unset an alias CHAPTER 6: Manage Local Users and Groups YE RABI NAJAH MIMIX What is a User? Users have usernames to identify them to human users and for ease of working. Internally, the system distinguishes user accounts by ; Username & User ID (UID): Each account has a unique identifier for system recognition. Authentication: Typically involves a password to verify identity. File Ownership & Process Control: Users own files and determine access, with their permissions regulating system processes.(which files and directories it can access, modify, or execute) Types of Users: 1. Superuser: The administrative account (root), with unrestricted system access (UID 0). 2. System Users: ○ used by processes that provide supporting services.( like web servers, database servers, or schedulers to run in the background.) ○ Limited privileges (exp , a web server should only access web files, not your personal files.) ○ non-privileged accounts to secure their files and other resources from each other and from regular users on the system.(it makes the 47 48 system safer because even if one program is hacked, the damage is limited) ○ Users do not interactively log in with a system user account( They’re meant only for programs, not humans.// they run automatically in the background.) 3. Regular Users: Standard accounts with limited privileges for everyday activities & they have limited access to the system. id: info about the currently logged-in user: [user01@host ~]$ id uid=1000(user01) gid=1000(user01) groups=1000(user01) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 - every user must belong at least to one group - a default group will be created and will have the same id as the user if we didn’t mention a specefic group - id + username :info about another user - ls -l + file: to view the owner of a file. - ls -ld + doc :command to view the owner of a directory, rather than the contents of that directory. - "process status" ps : to view process information.(shows information about the processes (programs) running on your computer) ○ The default is to show only processes in the current shell.(current terminal) ○ ps -a : to view all processes with a terminal (Processes from other users, other terminals, and yours, as long as they are terminal-based.) ○ ps -u : to view the user that is associated with a process (user-oriented format) 48 49 Processes with: R+ :The ps command itself is in the running state S or Sl: Most of the processes are in the sleeping state (S), meaning they are idle or waiting for something (e.g., user input, system events). /etc/passwd : file to store information about local users - Each line in the /etc/passwd file contains information about one user. - The file is divided into 7 colon-separated fields (by a colon : ) Consider each part of the code block, separated by a colon: 1. user01 : The username for this user. 2. x : The user's encrypted password was historically stored here; it is now a placeholder. 3. 1000 : The UID number for this user account. 4. 1000 : The GID number for this user account's primary group. Groups are discussed later in this section. 5. User One : A brief comment, description, or the real name for this user. 6. /home/user01 : The user's home directory, and the initial working directory when the login shell starts. 7. /bin/bash : The default shell program for this user that runs at login. Some accounts use the /sbin/nologin shell to disallow interactive logins with that account. =>The /etc/passwd file is an essential part of Linux. It is a text file that contains information about all the system's user accounts. Despite its name, it doesn't 49 50 store passwords anymore; instead, it holds user details. Encrypted passwords are stored in a separate file: /etc/shadow. melekher taatik kol chay etc/passwd ken l password What is a Group? - A group is a collection of users that need to share access to files and other system resources. - Groups can grant access to files to a set of users instead of to a single user. - Group ID (GID): A unique number identifying the group internally to the system. - systems use the /etc/group file to store information about local groups. Each line in the /etc/group file contains information about one group. Each group entry is divided into 4 colon-separated fields. 1-group01 : Name for this group//2- x : Obsolete group password field; it is now a placeholder//3-10000 : The GID.//4-user01,user02,user03 : A list of users that are members of this group as a supplementary group. Primary / Supplementary Groups : 1-Primary group: - Every user has exactly one primary group. This is the default group associated with the user - The primary group is stored in the /etc/passwd file as the Group ID (GID). - why ? When a user creates a file, the primary group is the default owner of that file. - When a regular user is created (e.g., user01), a User Private Group with the same name as the user (user01) is also created (The user is the sole member of this group by default) - The new user’s primary group is set to their private group. 50 51 - This group membership design simplifies the management of file permissions, to have user groups separated by default 2-Supplementary group: - Users can belong to multiple supplementary groups in addition to their primary group. - Supplementary group memberships are listed in the /etc/group file. - Supplementary groups allow users to share access to files and resources with other users who belong to those groups. - Permissions are cumulative, meaning a user can access files if any of their groups (primary or supplementary) have the necessary permissions - For example, if the (user01) user has a (user01) primary group and wheel and webadmin supplementary groups, then that user can read files that any of those three groups can read. the “user01” User has the “user01” group as their primary group (gid). The groups item lists all group memberships for this user, and the user also has the wheel and group01 groups as supplementary groups. Gain Superuser Access: a superuser(root) : has all power over the system. This user has the power to override normal privileges on the file system. you can use it to manage and administer the system. - The root user can override normal permissions, allowing it to manage system files and directories , install or remove software ,and control devices like hard drives. While normal users can control removable devices (like USBs). => only the root user can manage more critical system resources like hard drives. - However, this powerful access comes with risk. If the root account is compromised, the entire system could be damaged. Therefore, it's 51 52 recommended to log in as a normal user and only use root privileges when necessary through tools like sudo or su, ensuring system security. - The root account in Linux is similar to the Administrator account in Windows but is used more cautiously. Switch User Accounts : 1-Su : su: allows you to switch user accounts If you run the su command from : a regular user account with another user account as a parameter, then you must provide the password of the account to switch to A root user account you do not need to enter the user's password. - su: starts a non-login shell Switches user but keeps the original user's environment. - su -: starts a login shell Switches user and gives the new user's full environment. =>Usually, administrators should run su - to get a shell with the target user's normal environment settings. su -c to run a specific command as another user without switching to their shell, similar to the Windows runas command. su -c 'command' username 52 53 su -c 'ls /root' => to run ls as root: su -c 'whoami' user02 => running the whoami command as user02(This will show the username of user02 even if you're logged in as a different user.) 2-Run Commands with Sudo : sudo command is commonly used to run commands with root privileges in a more secure way.(only if they are authorized in the sudoers file) - When using sudo, you authenticate using your own password (not the root password). - It grants you temporary root access to run specific commands without fully switching to the root user. you can configure the sudo command to allow specific users to run any command as some other user, or only some commands as that user. For example, if you configure the sudo command to allow the user01 user to run the usermod command as root, then you can run the following command to lock or unlock a user account: - The system administrator has configured sudo so that user01 can run the usermod command with root privileges. This is done by 53 54 editing the /etc/sudoers file or by adding a file in /etc/sudoers.d/ with specific permissions for user01. ○ In the example, user02's account is locked because the command usermod -L user02 was run. that’s why when user01 wanted to login as user02 eventhough he has the password , it failed. If a user tries to run a command with sudo but doesn't have permission (because they are not in the sudoers file), bash will block the command and send by default an email to the root user. Another benefit of sudo is to log by default all the executed commands to /var/log/secure ( Whenever you use sudo to run a command, the system records the command in a special log file called /var/log/secure.It helps track what commands were run and who ran them) In Red Hat Enterprise Linux 7 and later versions, all members of the wheel group can use sudo to run commands as any user, including root, by using their own password. (In RHEL 6 and earlier, the wheel group has no special privileges by default) PS : The wheel group in Linux is a special user group that gives its members permission to perform administrative tasks by using the sudo command 3-Get an interactive Root Shell with Sudo sudo -i : Switches to the root account and runs the root user's default shell (usually bash), including its interactive login scripts. 54 55 sudo -s : Switches to the root account and runs the root shell without loading interactive login scripts.(keeps using the current user’s environment.) 4-Configure Sudo /etc/sudoers file :is the main configuration file for managing the sudo permissions. visudo command : to edit the file safely. It prevents errors and ensures no two people edit it simultaneously. - For example, the following line from the /etc/sudoers file enables sudo access for wheel group members: %wheel ALL=(ALL:ALL) ALL The %wheel string is the user or group that the rule applies to. The % symbol before the wheel word specifies a group. ALL=(ALL:ALL) command specifies that - First ALL: Applies to all hosts in this file - Second ALL: Users in the wheel group can run commands as any user. - Third ALL: Users can run commands as any group. The last ALL command specifies that users in the wheel group can run any command. /etc/sudoers.d Directory : Any files inside this directory are automatically included in the sudo configuration. (extension of the main sudo configuration file (/etc/sudoers) - In the /etc/sudoers.d/ directory, each file can define specific sudo access for users or groups. - You can enable or disable sudo access by copying a file into the directory or removing it from the directory. To enable full sudo access for the user01 user, you can create the /etc/sudoers.d/user01 file with the following content: user01 ALL=(ALL) ALL 55 56 To enable full sudo access for the group01 group, you can create the /etc/sudoers.d/group01 file with the following content: %group01 ALL=(ALL) ALL To allow users in the games group to run the id command as the operator user, you would create a file named /etc/sudoers.d/games with the following content: %games ALL=(operator) /bin/id You can also set up sudo to allow a user to run commands as another user without entering their password, by using the NOPASSWD: ALL command: ansible ALL=(ALL) NOPASSWD: ALL RQ: chalta 4 PATH is a list of directories where your computer looks for programs or commands to run - If you run echo $PATH, it will show directories where programs like ls, cat, and others are located. - If you want to run ls, the system checks the directories in PATH to find the ls command. If you run su -> you immediately get the root environment, including its PATH. If you run sudo su -> sudo first elevates you to root without giving you root’s full environment. then temporarily changing the PATH. It does this for security reasons, to make sure you're not running any potentially dangerous commands from unsafe locations.) 56 57 Switch to the root user in a non-login shell and explore the new shell environment.(sudo su) 57 58 Switch to the root user in a login shell and explore the new shell environment (sudo su -) Differences :(thabat fehom) Non login shell : [root@servera student]# VS login shell : [root@servera ~]# Non login shell : pwd : /home/student VS login shell : pwd : /root PATH 58 59 sudo cat /etc/sudoers.d/username : verify if user 1 can run any command => The command failed because normal users don’t have permission to read system log files such as /var/log/messages,You used sudo to run the tail command, which allows you to execute commands with superuser (root) privileges 59 60 Manage Local User Accounts : 1-Create users from the command line useradd username : This command creates a new user with the name username - Creates a home directory for the user (e.g., /home/username). - Creates a private group with the same name as the user (e.g., username group). - Does not set a password for the user, meaning the user cannot log in until a password is set. 60 61 useradd --help: This shows the available options for the useradd command, which let you override default settings (like the user’s home directory, shell, etc.) usermod: This command is used to modify an existing user. You can use many of the same options with usermod that you used with useradd. /etc/login.defs file sets some default options for user accounts, like the range of valid user IDs (UIDs) and password aging rules. These settings only apply to newly created users, not existing ones.(A change to this file does not affect existing users.) In Red Hat Enterprise Linux 9, the useradd command assigns new users the first free UID that is greater than or equal to 1000, unless you explicitly specify a UID by using the -u option.. 2- Modify Existing Users from the Command Line 61 62 more in details : -c : usermod -c "Operator One" operator1 ( Update the operator1 to include the “Operator One “comment) comments ali mawjoudin f ekel case 5 ki taaml /etc/passwd -G: This option allows you to specify a list of groups to which you want to add a user.(supplementary) -a: When used with -G, this option ensures that the user is added to the specified groups without being removed from any groups they were already a member of (john aslou fi staff group wenti theb tzidou l admin group donc ywali fi 2 groupes taaml -aG / ken taaml -G khaw , john ytnaha mn staff w ywali f admin khaw) -d : If you want to create a user with a custom home directory, use this option. useradd -d /home/johndoe johndoe This creates the user johndoe with the home directory set to /home/johndoe -g : useradd -g developers johndoe (This creates the user johndoe and assigns them to the primary group developers.) -L: usermod -L johndoe (This locks the johndoe account, preventing it from being used to log in.) (# -U) -m : usermod -m -d /new/home/directory johndoe (To move the user's home directory from the default location to a custom path) -s : useradd -s /bin/bash johndoe (To set the login shell to /bin/bash for the user:) 3- Delete Users from the Command line : userdel username : removes the username user from /etc/passwd but leaves the user's home directory intact. userdel -r username removes the user from /etc/passwd + deletes the user's home directory. 62 63 if you remove a user 1 without -r option , an unassigned UID now owns the user's files. If you create a user and that user is assigned the deleted user's UID , then the new account owns those files, which is a security risk find / -nouser -o -nogroup : to find all unowned files and directories 4-Set passwords from the command line : passwd username :used to set or update a password for a user account -A regular user must choose a password at least eight characters long. Do not use a dictionary word, the username, or the previous password. 5- UID ranges : UID 0 : The superuser (root) account UID. UID 1-200 : System account UIDs that are statically assigned to system processes (e.g., daemon, bin, syslog). UID 201-999 : UIDs that are assigned to system processes that do not own files on this system. Software that requires an unprivileged UID is dynamically assigned a UID from this available pool. 63 64 UID 1000+ : The UID range to assign to regular, unprivileged users. Note : RHEL 6 and earlier versions use UIDs in the range 1-499 for system users and UIDs higher than 500 for regular users. - You can change the useradd and groupadd default ranges in the /etc/login.defs file. Manage Local Group Accounts : 1-Create Groups from the command line : groupadd command is used to create groups added to the /etc/group file. When no options are specified, the group is assigned the next available Group ID (GID) within the range defined by GID_MIN and GID_MAX in the /etc/login.defs file. (, the command assigns a GID value that is greater than any other existing GIDs, even if a lower value becomes available.) groupadd -g : specifies a GID for the group to use -Because of the automatic creation of user private groups (GID 1000+), some administrators set aside a separate range of GIDs for creating supplementary groups for other purposes.(to avoid overlap with user private groups) - However, this extra management is unnecessary, because a user's UID and primary GID do not need to be the same number.(it is set the same by default but you can change it , it is not a requirement ) groupadd -r :creates system groups. As with normal groups, system groups use a GID from the range of listed valid system GIDs in the /etc/login.defs file. The SYS_GID_MIN and SYS_GID_MAX configuration items in the /etc/login.defs file define the range of system GIDs. 64 65 2-Modify Existing Groups from the command line : groupmod :changes the properties of an existing group groupmod -n : specifies a new name for the group. groupmod -g : specifies a new GID. 3-Delete Groups from the command line : groupdel : removes groups. Note You cannot remove a group if it is the primary group of an existing user. Similar to using the userdel command, ensure first that you locate files that the group owns. (If you try to delete a group, and that group owns files or directories on the system, those files will no longer have a valid group owner after the group is deleted. This can lead to potential security risks or organizational problems). 4-Change group membership from the command line : usermod -g : change a user's primary group. 65 66 usermod -aG : add a user to a supplementary group. usermod -a option enables the append mode => Without the -a option, the command removes the user from any of their current supplementary groups that are not included in the -G option's list. 5-Compare Primary and Supplementary Group Membership : user's primary group : - is viewed on the user's account in the /etc/passwd file. - A user can belong to only one primary group at a time. user's supplementary groups : - the additional groups that are configured for the user - viewed on the user's entry in the /etc/group file. - A user can belong to as many supplementary groups - used to assign extra file access permissions for the user. Whether a group is the primary group or a supplementary group, there is no difference in file access permissions. If a user is part of a group that has access to certain files, the user can access those files. The key difference between a primary group and supplementary groups comes into play when the user creates a file: When a user creates a new file, the primary group is assigned as the group owner of that file by default while supplementary groups help with permissions but don’t affect new file ownership. 6- Temporarily change your primary group : - Only a user's primary group is used for new file creation attributes - However, you can temporarily switch your primary group to a supplementary group that you already belong to. newgrp : to switch your primary group, in this shell session 66 67 - You can switch between any primary or supplementary group that you belong to, but only one group at a time can be primary. - Your primary group returns to the default if you log out and log in again In this example, the group01 group temporarily becomes this user's primary group. Manage User Passwords : 1-Shadow Passwords and Password Policy : - Originally, encrypted passwords were stored in the world-readable /etc/passwd file. These passwords were considered adequate until dictionary attacks on encrypted passwords became common. - The cryptographically hashed passwords were moved to the /etc/shadow file, which only the root user can read. 67 68 - Like the /etc/passwd file, each user has an entry in the /etc/shadow file. - It has 9 colon-separated fields 1. user03 : username account. 2. $6$CSsXsd3rwghsdfarf : The cryptographically hashed password of the user. 3. 17933 : The days from the epoch when the password was last changed, where the epoch is 1970-01-01 in the UTC time zone. 4. 0 : The minimum days since the last password change before the user can change it again. 5. 99999 : The maximum days without a password change before the password expires. An empty field means that the password never expires (99999 is a very long time , it means that the password doesn’t need to be changed) 6. 7 : The number of days ahead to warn the user that their password will expire.( the user will be warned 7 days before their password expires.) 7. 2 : The number of days without activity, starting with the day that the password expired, before the account is automatically locked.(baad me it get expired b nharin ywali locked w you can’t login) 8. 18113 : The day when the account expires in days since the epoch. An empty field means that the account never expires. 9. The last field is typically empty and is reserved for future use 2-Format of an Cryptographically Hashed Password : - The cryptographically hashed pa