From 5302706f0e49559415a50a1e02e013eb3994c9c2 Mon Sep 17 00:00:00 2001 From: Steven Spencer Date: Fri, 17 Dec 2021 09:15:06 -0600 Subject: [PATCH] Crowdin conflicting files * Deleting these so that Crowdin can add them back in --- docs/books/admin_guide/00-toc.fr.md | 26 - docs/books/admin_guide/03-commands.fr.md | 1563 --------------------- docs/books/admin_guide/08-process.it.md | 395 ------ docs/books/admin_guide/09-backups.it.md | 833 ----------- docs/books/admin_guide/10-boot.it.md | 419 ------ docs/books/admin_guide/11-tasks.it.md | 257 ---- docs/books/admin_guide/12-network.it.md | 740 ---------- docs/books/admin_guide/13-softwares.it.md | 223 --- 8 files changed, 4456 deletions(-) delete mode 100644 docs/books/admin_guide/00-toc.fr.md delete mode 100644 docs/books/admin_guide/03-commands.fr.md delete mode 100644 docs/books/admin_guide/08-process.it.md delete mode 100644 docs/books/admin_guide/09-backups.it.md delete mode 100644 docs/books/admin_guide/10-boot.it.md delete mode 100644 docs/books/admin_guide/11-tasks.it.md delete mode 100644 docs/books/admin_guide/12-network.it.md delete mode 100644 docs/books/admin_guide/13-softwares.it.md diff --git a/docs/books/admin_guide/00-toc.fr.md b/docs/books/admin_guide/00-toc.fr.md deleted file mode 100644 index 8cf8be6eb4..0000000000 --- a/docs/books/admin_guide/00-toc.fr.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Apprendre Linux avec Rocky ---- - -# Apprendre Linux avec Rocky - -Le Guide d'administration est une collection de documents éducatifs destinés aux administrateurs systèmes. Ils peuvent être utilisés par les futurs administrateurs systèmes qui veulent se mettre à niveau, par les administrateurs systèmes actuels qui souhaitent se rafraîchir la mémoire, ou par tout utilisateur de Linux qui souhaite en savoir plus sur l'environnement, les commandes, les processus etc. de Linux. Comme tous les documents de ce type, il évoluera et sera mis à jour au fil du temps. - -Dans un premier temps, nous parlerons de Linux, des distributions, et de tout l'écosystème autour de notre système d'exploitation. - -Nous nous pencherons ensuite sur les commandes utilisateurs qui sont essentielles pour se familiariser avec Linux. Les utilisateurs les plus expérimentés pourront également consulter le chapitre consacré aux commandes "plus avancées". - -Vient ensuite le chapitre sur l'éditeur VI. Si Linux est livré avec de nombreux éditeurs, VI est l'un des plus puissants. D'autres commandes utilisent parfois des syntaxes identiques à celles de VI (on pensera notamment à `sed`). Il est donc très important de connaître VI, ou du moins de démystifier ses fonctions essentielles (comment ouvrir un fichier, enregistrer, quitter ou quitter sans enregistrer). L'utilisateur deviendra plus à l'aise avec les autres fonctions de VI au fur et à mesure qu'il utilisera l'éditeur. Une alternative serait d'utiliser nano qui est installé par défaut dans Rocky Linux. Bien qu'il ne soit pas aussi polyvalent, il est simple à utiliser, direct, et fait le travail. - -Nous pourrons ensuite entrer dans le fonctionnement profond de Linux pour découvrir comment le système gère : - -* les utilisateurs. -* les systèmes de fichiers. -* les processus. - -Ensuite, nous aborderons un sujet essentiel pour l'administrateur systèmes : Le processus de sauvegarde. De nombreuses solutions logicielles sont fournies avec Linux pour améliorer les sauvegardes (rsnapshot, lsyncd, etc..). Il est bon de connaître les composants essentiels de la sauvegarde qui se trouvent dans le système d'exploitation. Nous allons étudier deux outils : `tar` et le moins répandu `cpio` dans ce chapitre. - -La gestion du système pendant le processus de démarrage a beaucoup évolué ces dernières années depuis l'arrivée de systemd. - - -Nous terminerons en examinant la gestion des tâches, la mise en place du réseau et l'installation des logiciels. diff --git a/docs/books/admin_guide/03-commands.fr.md b/docs/books/admin_guide/03-commands.fr.md deleted file mode 100644 index 487100e818..0000000000 --- a/docs/books/admin_guide/03-commands.fr.md +++ /dev/null @@ -1,1563 +0,0 @@ ---- -title: Linux Commands -author: Antoine Le Morvan -contributors: Steven Spencer, Aditya Putta -update: 11-08-2021 ---- - -# Commands for Linux Users - -In this chapter you will learn how to work with Linux with the commands. - -**** - -**Objectives** : In this chapter, future Linux administrators will learn how to: - -:heavy_check_mark: **move** in the system tree; -:heavy_check_mark: **create** a text file, **display** its contents and **modify** it; -:heavy_check_mark: use the most useful Linux commands. - -:checkered_flag: **user commands**, **linux** - -**Connaissances : ** :star: -**Complexité : ** :star: - -**Temps de lecture : **40 minutes - -**** - -## Generalities - -Current Linux systems have graphical utilities dedicated to the work of an administrator. However, it is important to be able to use the interface in command line mode for several reasons: - -* The majority of system commands are common to all Linux distributions, which is not the case for graphical tools. -* It can happen that the system does not start correctly but that a backup command interpreter remains accessible. -* Remote administration is done on the command line with an SSH terminal. -* In order to preserve server resources, the graphical interface is either not installed or launched on demand. -* Administration is done by scripts. - -Learning these commands allows the administrator to connect to a Linux terminal, to manage its resources, its files, to identify the station, the terminal, and the connected users, etc. - -### The users - -The user of a Linux system is defined in the `/etc/passwd` file, by: - -* a **login name**, more commonly called "login", containing no spaces; -* a numeric identifier : **UID** (User Identifier); -* a group identifier : **GID** (Group Identifier); -* a **command interpreter**, a shell, which can be different from one user to another; -* a **connection directory**, the __home directory__. - -In other files by: - -* a **password**, which will be encrypted before being stored (`/etc/shadow`); -* a **command prompt**, or __prompt__ login, which will be symbolized by a `#` for administrators and a `$` for other users (`/etc/profile`). - -Depending on the security policy implemented on the system, the password will have to contain a certain number of characters and meet certain complexity requirements. - -Among the existing command interpreters, the **Bourne-Again Shell** (`/bin/bash`) is the one most frequently used. It is assigned by default to new users. For various reasons, advanced Linux users can choose alternative shells from among the Korn Shell (`ksh`), the C Shell (`csh`), etc. - -The user's login directory is by convention stored in the `/home` directory of the workstation. It will contain the user's personal data and the configuration files of his applications. By default, at login, the login directory is selected as the current directory. - -A workstation type installation (with graphical interface) starts this interface on terminal 1. Linux being multi-user, it is possible to connect several users several times, on different **physical terminals** (TTY) or **virtual terminals** (PTS). Virtual terminals are available within a graphical environment. A user switches from one physical terminal to another using Alt + Fx from the command line or using CTRL + Alt + Fx. - -### The shell - -Once the user is connected to a console, the shell displays the command **prompt**. It then behaves like an infinite loop, with each statement entered: - -* displaying the command prompt; -* reading the command ; -* syntax analysis ; -* substitution of special characters ; -* execute the command; -* display the command prompt; -* etc. - -The key sequence CTRL + C is used to interrupt a running command. - -The use of a command generally follows this sequence: - -```bash -command [option(s)] [arguments(s)] -``` - -The name of the command is **often in lower case**. - -A space separates each item. - -Short **options** begin with a dash (`-l`), while **long options** begin with two dashes (`--list`). A double dash (`--`) indicates the end of the option list. - -It is possible to group some short options together: - -```bash -$ ls -l -i -a -``` - -is equivalent to: - -```bash -$ ls -lia -``` - -There can of course be several arguments after an option: - -```bash -$ ls -lia /etc /home /var -``` - -In the literature, the term "option" is equivalent to the term "parameter," which is more commonly used in programming. The optional side of an option or argument is symbolized by enclosing it in square brackets `[` and `]`. When more than one option is possible, a vertical bar called a "pipe" separates them `[a|e|i]`. - -## General commands - -### `apropos`, `whatis` and `man` commands - -It is impossible for an administrator at any level to know all the commands and options in detail. A manual is usually available for all installed commands. - -#### `apropos` command - -The command `apropos` allows you to search by keyword within these manual pages: - -| Options | Observations | -| ------------------------------------------- | ---------------------------------------------------------- | -| `-s`, `--sections list` or `--section list` | Limited to manual sections. | -| `-a` or `--and` | Displays only the item matching all the provided keywords. | - -Example: - -```bash -$ apropos clear -clear (1) - clear the terminal screen -clear_console (1) - clear the console -clearenv (3) - clear the environment -clearerr (3) - check and reset stream status -clearerr_unlocked (3) - nonlocking stdio functions -feclearexcept (3) - floating-point rounding and exception handling -fwup_clear_status (3) - library to support management of system firmware updates -klogctl (3) - read and/or clear kernel message ring buffer; set console_loglevel -sgt-samegame (6) - Block-clearing puzzle -syslog (2) - read and/or clear kernel message ring buffer; set console_loglevel -timerclear (3) - timeval operations -XClearArea (3) - clear area or window -XClearWindow (3) - clear area or window -XSelectionClearEvent (3) - SelectionClear event structure -``` - -To find the command that will allow changing the password of an account: - -```bash -$ apropos --exact password -a change -chage (1) - change user password expiry information -passwd (1) - change user password -``` - -#### `whatis` command - -The `whatis` command displays the description of the command passed as argument: - -```bash -whatis clear -``` - -Example: - -```bash -$ whatis clear -clear (1) - clear the terminal screen -``` - -#### `man` command - -Once found by `apropos` or `whatis`, the manual is read by `man` ("Man is your friend"). This set of manuals is divided into 8 sections, grouping information by topic, the default section being 1: - -1. User Commands; -2. System Calls; -3. C library functions; -4. Peripherals and special files; -5. File formats ; -6. Games; -7. Miscellaneous; -8. System administration tools and daemons. Information about each section can be accessed by typing `man x intro`, where `x` is the section number. - -The command: - -```bash -man passwd -``` - -will tell the administrator about the passwd command, its options, etc. While a: - -```bash -$ man 5 passwd -``` - -will inform him about the files related to the command. - -Not all pages of the manual are translated from English. However, they are generally very accurate and provide all the information needed. The syntax used and the division may confuse the beginner administrator, but with practice, he will quickly find the information he is looking for. - -The navigation in the manual is done with the arrows and . The manual is exited by pressing the q key. - -### `shutdown` command - -The `shutdown` command allows you to **electrically shut down** a Linux server, either immediately or after a certain period of time. - -```bash -shutdown [-h] [-r] time [message] -``` - -The shutdown time should be specified in the format `hh:mm` for a precise time, or `+mm` for a delay in minutes. - -To force an immediate stop, the word `now` will replace the time. In this case, the optional message is not sent to other users of the system. - -Examples: - -```bash -[root]# shutdown -h 0:30 "Server shutdown at 0:30" -[root]# shutdown -r +5 -``` - -Options: - -| Options | Remarks | -| ------- | -------------------------------- | -| `-h` | Shutdown the system electrically | -| `-r` | Restarts the system | - -### `history` command - -The `history` command displays the history of commands that have been entered by the user. The commands are stored in the `.bash_history` file in the user's login directory. - -Example of a history command - -```bash -$ history -147 man ls -148 man history -``` - -| Options | Comments | -| ------- | ------------------------------------------------------------------------------------------------------------------ | -| `-w` | The `-w` option will copy the history of the current session to it. | -| `-c` | The `-c` option will delete the history of the current session (but not the contents of the `.bash_history` file). | - -* Manipulating history: - -To manipulate the history, the following commands entered from the command prompt will: - -| Keys | Function | -| ------------------ | --------------------------------------------------------- | -| !! | Recall the last command placed. | -| !n | Recall the command by its number in the list. | -| !string | Recall the most recent command beginning with the string. | -| | Recall the most recent command beginning with the string. | -| | Recall the most recent command beginning with the string. | - -### The auto-completion - -Auto-completion is also a great help. - -* It allows you to complete commands, entered paths, or file names. -* A press of the TAB key completes the entry in the case of a single solution. -* Otherwise, a second press will be required to obtain the list of possibilities. - -If a double press of the TAB key causes no reaction from the system, then there is no solution to the current completion. - -## Display and identification - -### `clear` command - -The `clear` command clears the contents of the terminal screen. In fact, to be more precise, it shifts the display so that the command prompt is at the top of the screen on the first line. - -In a terminal, the display will be permanently hidden, whereas in a graphical interface, a scrollbar will allow you to go back in the history of the virtual terminal. - -!!! Tip CTRL + L will have the same effect as the `clear` command - -### `echo` command - -The `echo` command is used to display a string of characters. - -This command is most commonly used in administration scripts to inform the user during execution. - -The `-n` option will not return to the line after displaying the text (which is the default behavior of the command). - -For various reasons, the script developer may need to use special sequences (starting with a `\` character). In this case, the `-e` option will be stipulated, allowing interpretation of the sequences. - -Among the frequently used sequences, we can mention: - -| Sequence | Result | -| -------- | --------------------- | -| `\a` | Send a sonor bip | -| `\b` | Back | -| `\n` | Adds a line break | -| `\t` | Adds a horizontal tab | -| `\v` | Adds vertical tab | - -### `date` command - -The `date` command displays the date and time. The command has the following syntax: - -```bash -date [-d AAAAMMJJ] [format] -``` - -Examples: - -```bash -$ date -Mon May 24 16:46:53 CEST 2021 -$ date -d 20210517 +%j -137 -``` - -In this last example, the `-d` option displays a given date. The `+%j` option formats this date to show only the day of the year. - -!!! Warning The format of a date can change depending on the value of the language defined in the environment variable `$LANG`. - -The date display can follow the following formats: - -| Option | Format | -| ------ | -------------------------------- | -| `+%A` | Full Name of Day | -| `+%B` | Full Name of Month | -| `+%c` | Full Date Display | -| `+%d` | Day number | -| `+%F` | Date in `YYYY-MM-DD` format | -| `+%G` | Year | -| `+%H` | Time of day | -| `+%j` | Day of the year | -| `+%m` | Month number | -| `+%M` | Minute | -| `+%R` | Time in `hh:mm` format | -| `+%s` | Seconds since January 1, 1970 | -| `+%T` | Time in `hh:mm:ss` format | -| `+%u` | Day of the week (`1` for Monday) | -| `+%V` | Week number (`+%V`) | -| `+%x` | Date in format `DD/MM/YYYY` | - -The `date` command also allows you to change the system date and time. In this case, the `-s` option will be used. - -```bash -[root]# date -s "2021-05-24 10:19" -``` - -The format to be used following the `-s` option is this: - -```bash -date -s "[AA]AA-MM-JJ hh:mm:[ss]" -``` - -### `id`, `who` and `whoami` commands - -The `id` command displays the name of the current user and its groups or those of a user, if the user's login is given as an argument. - -```bash -$ id rockstar -uid=1000(rockstar) gid=1000(rockstar) groups=1000(rockstar),10(wheel) -``` - -The `-g`, `-G`, `-n` and `-u` options display the main group GID, subgroup GIDs, names instead of numeric identifiers, and the user's UID respectively. - -The `whoami` command displays the login of the current user. - -The `who` command alone displays the names of logged in users: - -```bash -$ who -rockstar tty1 2021-05-24 10:30 -root pts/0 2021-05-24 10:31 -``` - -Since Linux is multi-user, it is likely that multiple sessions are open on the same station, either physically or over the network. It is interesting to know which users are logged in, if only to communicate with them by sending messages. - -* tty: represents a terminal. -* pts/: represents a virtual console in a graphical environment with the number after representing the instance of the virtual console (0, 1, 2...) - -The `-r` option also displays the execution level (see chapter "startup"). - -## File tree - -In Linux, the file tree is an inverted tree, called a **single hierarchical tree**, whose root is the directory `/`. - -The **current directory** is the directory where the user is located. - -The **connection directory** is the working directory associated with the user. The login directories are, by default, stored in the `/home` directory. - -When the user logs in, the current directory is the login directory. - -An **absolute path** references a file from the root by traversing the entire tree to the file level: - -* `/home/groupA/alice/file` - -The **relative path** references that same file by traversing the entire tree from the current directory: - -* `../alice/file` - -In the above example, the "`..`" refers to the parent directory of the current directory. - -A directory, even if it is empty, will necessarily contain at least **two references**: - -* `.`: reference to itself. -* `..`: reference to the parent directory of the current directory. - -A relative path can thus start with `./` or `../`. When the relative path refers to a subdirectory or file in the current directory, then the `./` is often omitted. Mentioning the first `./` in the tree will only really be required to run an executable file. - -Errors in paths can cause many problems: creating folders or files in the wrong places, unintentional deletions, etc. It is therefore strongly recommended to use auto-completion when entering paths. - -![our example tree](images/commands-pathabsolute.png) - -In the above example, we are looking to give the location of the file `myfile` from the directory of bob. - -* By an **absolute path**, the current directory does not matter. We start at the root, and work our way down to the directories `home`, `groupA`, `alice` and finally the file `myfile`: `/home/groupA/alice/myfile`. -* By a **relative path**, our starting point being the current directory `bob`, we go up one level through `..` (i.e., into the `groupA` directory), then down into the alice directory, and finally the `myfile` file: `../alice/myfile`. - -### `pwd` command - -The `pwd` (Print Working Directory) command displays the absolute path of the current directory. - -```bash -$ pwd -/home/rockstar -``` - -To move around using a relative path, you must know its position in the tree. - -Depending on the command interpreter, the command prompt may also display the name of the current directory. - -### `cd` command - -The `cd` (Change Directory) command allows you to change the current directory, in other words, to move through the tree. - -```bash -$ cd /tmp -$ pwd -/tmp -$ cd ../ -$ pwd -/ -$ cd -$ pwd -/home/rockstar -``` - -As you can see in the last example above, the command `cd` with no arguments moves the current directory to the `home directory`. - -### `ls` command - -The `ls` command displays the contents of a directory - -```bash -ls [-a] [-i] [-l] [directory1] [directory2] […] -``` - -Example: - -```bash -$ ls /home -. .. rockstar -``` - -The main options of the `ls` command are: - -| Option | Information | -| ------ | ---------------------------------------------------------------------------------------------------- | -| `-a` | Displays all files, even hidden ones. Hidden files in Linux are those beginning with `.`. | -| `-i` | Displays inode numbers. | -| `-l` | The `-l` command displays a vertical list of files with additional information formatted in columns. | - -The `ls` command, however, has a lot of options (see `man`): - -| Option | Information | -| ------ | ------------------------------------------------------------------------------------------------------------------------------------ | -| `-d` | Displays information about a directory instead of listing its contents. | -| `-g` | Displays UID and GID rather than owner names. | -| `-h` | Displays file sizes in the most appropriate format (byte, kilobyte, megabyte, gigabyte, ...). `h` stands for Human Readable. | -| `-s` | Displays the size in bytes (unless `k` option). | -| `-A` | Displays all files in the directory except `.` and `.`. | -| `-R` | Displays the contents of subdirectories recursively. | -| `-F` | Displays the type of files. Prints a `/` for a directory, `*` for executables, `@` for a symbolic link, and nothing for a text file. | -| `-X` | Sort files according to their extensions. | - -* Description of columns: - -```bash -$ ls -lia /home -78489 drwx------ 4 rockstar rockstar 4096 25 oct. 08:10 rockstar -``` - -| Value | Information | -| --------------- | ------------------------------------------------------------------------------------------------------------- | -| `78489` | Inode Number. | -| `drwx------` | File type (`d`) and rights (`rwx------`). | -| `4` | Number of subdirectories (`.` and `..` included). For a file of type physical link: number of physical links. | -| `rockstar` | For a physical link file: number of physical links. | -| `rockstar` | For a file of type physical link: number of physical links. | -| `4096` | For a physical link type file: number of physical links. | -| `25 oct. 08:10` | Last modified date. | -| `rockstar` | The name of the file (or directory). | - -!!! Note **Aliases** are frequently positioned in common distributions. - - This is the case of the alias `ll`: - - ``` - alias ll='ls -l --color=auto' - ``` - -The `ls` command has many options and here are some advanced examples of uses: - -* List the files in `/etc` in order of last modification: - -```bash -$ ls -ltr /etc -total 1332 --rw-r--r--. 1 root root 662 29 may 2021 logrotate.conf --rw-r--r--. 1 root root 272 17 may. 2021 mailcap --rw-------. 1 root root 122 12 may. 2021 securetty -... --rw-r--r--. 2 root root 85 18 may. 17:04 resolv.conf --rw-r--r--. 1 root root 44 18 may. 17:04 adjtime --rw-r--r--. 1 root root 283 18 may. 17:05 mtab -``` - -* List `/var` files larger than 1 megabyte but less than 1 gigabyte: - -```bash -$ ls -Rlh /var | grep [0-9]M -... --rw-r--r--. 1 apache apache 1,2M 10 may. 13:02 XB RiyazBdIt.ttf --rw-r--r--. 1 apache apache 1,2M 10 may. 13:02 XB RiyazBd.ttf --rw-r--r--. 1 apache apache 1,1M 10 may. 13:02 XB RiyazIt.ttf -... -``` - -* Show the rights on a folder: - -To find out the rights to a folder, in our example `/etc`, the following command would not be appropriate: - -```bash -$ ls -l /etc -total 1332 --rw-r--r--. 1 root root 44 18 nov. 17:04 adjtime --rw-r--r--. 1 root root 1512 12 janv. 2010 aliases --rw-r--r--. 1 root root 12288 17 nov. 17:41 aliases.db -drwxr-xr-x. 2 root root 4096 17 nov. 17:48 alternatives -... -``` - -since the command lists by default the contents of the folder and not the container. - -To do this, use the `-d` option: - -```bash -$ ls -ld /etc -drwxr-xr-x. 69 root root 4096 18 nov. 17:05 /etc -``` - -* List files by size: - -```bash -$ ls -lhS -``` - -* Display the modification date in "timestamp" format: - -```bash -$ ls -l --time-style="+%Y-%m-%d %m-%d %H:%M" / -total 12378 -dr-xr-xr-x. 2 root root 4096 2014-11-23 11-23 03:13 bin -dr-xr-xr-x. 5 root root 1024 2014-11-23 11-23 05:29 boot -``` - -* Add the _trailing slash_ to the end of folders: - -By default, the `ls` command does not display the last slash of a folder. In some cases, like for scripts for example, it is useful to display them: - -```bash -$ ls -dF /etc -/etc/ -``` - -* Hide some extensions: - -```bash -$ ls /etc --hide=*.conf -``` - -### `mkdir` command - -The `mkdir` command creates a directory or directory tree. - -```bash -mkdir [-p] directory [directory] [...] -``` - -Example: - -```bash -$ mkdir /home/rockstar/work -``` - -The "rockstar" directory must exist to create the "work" directory. Otherwise, the `-p` option should be used. The `-p` option creates the parent directories if they do not exist. - -!!! Danger It is not recommended to use Linux command names as directory or file names. - -### `touch` command - -The `touch` command changes the timestamp of a file or creates an empty file if the file does not exist. - -```bash -touch [-t date] file -``` - -Example: - -```bash -$ touch /home/rockstar/myfile -``` - -| Option | Information | -| --------- | -------------------------------------------------------------------------- | -| `-t date` | Changes the date of last modification of the file with the specified date. | - -Date format: `[AAAA]MMJJhhmm[ss]` - -!!! Tip The `touch` command is primarily used to create an empty file, but it can be useful for incremental or differential backups for example. Indeed, the only effect of executing a `touch` on a file will be to force it to be saved during the next backup. - -### `rmdir` command - -The `rmdir` command deletes an empty directory. - -Example: - -```bash -$ rmdir /home/rockstar/work -``` - -| Option | Information | -| ------ | ----------------------------------------------------------------------- | -| `-p` | Removes the parent directory or directories provided if they are empty. | - -!!! Tip To delete both a non-empty directory and its contents, use the `rm` command. - -### `rm` command - -The `rm` command deletes a file or directory. - -```bash -rm [-f] [-r] file [file] [...] -``` - -!!! Danger Any deletion of a file or directory is final. - -| Options | Information | -| ------- | ---------------------------------------- | -| `-f` | Do not ask for confirmation of deletion. | -| `-i` | Requires confirmation of deletion. | -| `-r` | Recursively deletes subdirectories. | - -!!! Note The `rm` command itself does not ask for confirmation when deleting files. However, with a RedHat/Rocky distribution, `rm` does ask for confirmation of deletion because the `rm` command is an `alias` of the `rm -i` command. Don't be surprised if on another distribution, like Debian for example, you don't get a confirmation request. - -Deleting a folder with the `rm` command, whether the folder is empty or not, will require the `-r` option to be added. - -The end of the options is signaled to the shell by a double dash `--`. - -In the example: - -```bash -$ >-hard-hard # To create an empty file called -hard-hard -hard-hard -[CTRL+C] To interrupt the creation of the file -$ rm -f -- -hard-hard -``` - -The hard-hard file name starts with a `-`. Without the use of the `--` the shell would have interpreted the `-d` in `-hard-hard` as an option. - -### `mv` command - -The `mv` command moves and renames a file. - -```bash -mv file [file ...] destination -``` - -Examples: - -```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 -$ mv /home/rockstar/file1 /home/rockstar/file2 /tmp -``` - -| Options | Information | -| ------- | --------------------------------------------------------------- | -| `-f` | Don't ask for confirmation if overwriting the destination file. | -| `-i` | Request confirmation if overwriting destination file (default). | - -A few concrete cases will help you understand the difficulties that can arise: - -```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 -``` - -Renames `file1` to `file2`, if `file2` already exists, it will be replaced by `file1`. - -```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 /tmp -``` - -Moves `file1` and `file2` into the `/tmp` directory. - -```bash -$ mv file1 /repexist/file2 -``` - -Moves `file1` into `repexist` and renames it `file2`. - -```bash -$ mv file1 file2 -``` - -`file1` is renamed to `file2`. - -```bash -$ mv file1 /repexist -``` - -If the destination directory exists, `file1` is moved to `/repexist`. - -```bash -$ mv file1 /wrongrep -``` - -If the destination directory does not exist, `file1` is renamed to `wrongrep` in the root directory. - -### `cp` command - -The `cp` command copies a file. - -```bash -cp file [file ...] destination -``` - -Example: - -```bash -$ cp -r /home/rockstar /tmp -``` - -| Options | Information | -| ------- | ---------------------------------------------------------------- | -| `-i` | Request confirmation if overwriting (default). | -| `-f` | Do not ask for confirmation if overwriting the destination file. | -| `-p` | Keeps the owner, permissions and timestamp of the copied file. | -| `-r` | Copies a directory with its files and subdirectories. | -| `-s` | Creates a symbolik links rather than copying | - -```bash -cp file1 /repexist/file2 -``` - -`file1` is copied to `/repexist` under the name `file2`. - -```bash -$ cp file1 file2 -``` - -`file1` is copied as `file2` to this directory. - -```bash -$ cp file1 /repexist -``` - -If the destination directory exists, `file1` is copied to `/repexist`. - -```bash -$ cp file1 /wrongrep -``` - -If the destination directory does not exist, `file1` is copied under the name `wrongrep` to the root directory. - -## Visualization - -### `file` command - -The `file` command displays the type of a file. - -```bash -file file1 [files] -``` - -Example: - -```bash -$ file /etc/passwd /etc -/etc/passwd: ASCII text -/etc: directory -``` - -### `more` command - -The `more` command displays the contents of one or more files screen by screen. - -```bash -more file1 [files] -``` - -Example: - -```bash -$ more /etc/passwd -root:x:0:0:root:/root:/bin/bash -... -``` - -Using the ENTER key, the move is line by line. Using the SPACE key, the move is page by page. `/text` allows you to search for the occurrence in the file. - -### `less` command - -The `less` command displays the contents of one or more files. The `less` command is interactive and has its own commands for use. - -```bash -less file1 [files] -``` - -The commands specific to `less` are: - -| Command | Action | -| ----------------- | ----------------------------------------------- | -| `h` | Help. | -| `Arrows` | Move up, down a line, or to the right or left.. | -| `Enter` | Move down one line. | -| `Space` | Move down one page. | -| `PgUp` and `PgDn` | Move up or down one page. | -| `Begin` and `End` | Move to the beginning or end of a file. | -| `/texte` | Search for text. | -| `q` | Quit the `less` command. | - -### `cat` command - -The `cat` command concatenates the contents of multiple files and displays the result on the standard output. - -```bash -cat file1 [files] -``` - -Example 1 - Displaying the contents of a file to the standard output: - -```bash -$ cat /etc/passwd -``` - -Example 2 - Displaying the contents of multiple files to standard output: - -```bash -$ cat /etc/passwd /etc/group -``` - -Example 3 - Displaying the contents of several files in the file `usersAndGroups.txt`: - -```bash -$ cat /etc/passwd /etc/group > usersAndGroups.txt -``` - -Example 4 - Displaying the line numbering: - -```bash -$ cat -n /etc/profile - 1 # /etc/profile: system-wide .profile file for the Bourne shell (sh(1)) - 2 # and Bourne compatible shells (bash(1), ksh(1), ash(1), ...). - 3 - 4 if [ "`id -u`" -eq 0 ]; then - 5 PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - 6 else -… -``` - -Example 5 - Shows the numbering of non-empty lines: - -```bash -$ cat -b /etc/profile - 1 # /etc/profile: system-wide .profile file for the Bourne shell (sh(1)) - 2 # and Bourne compatible shells (bash(1), ksh(1), ash(1), ...). - - 3 if [ "`id -u`" -eq 0 ]; then - 4 PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - 5 else -… -``` - -### `tac` command - -The `tac` command does almost the opposite of the `cat` command. It displays the contents of a file starting from the end (which is particularly interesting for reading logs!). - -Example: Display a log file by displaying the last line first: - -```bash -[root]# tac /var/log/messages | less -``` - -### `head` command - -The `head` command displays the beginning of a file. - -```bash -head [-n x] file -``` - -| Option | Observation | -| ------ | --------------------------------------- | -| `-n x` | Display the first `x` lines of the file | - -By default (without the `-n` option), the `head` command will display the first 10 lines of the file. - -### `tail` command - -The `tail` command displays the end of a file. - -```bash -tail [-f] [-n x] file -``` - -| Option | Observation | -| ------ | ----------------------------------------- | -| `-n x` | Displays the last `x` lines of the file | -| `-f` | Displays changes to the file in real time | - -Example: - -```bash -tail -n 3 /etc/passwd -sshd:x:74:74:Privilege-separeted sshd:/var/empty /sshd:/sbin/nologin -tcpdump::x:72:72::/:/sbin/nologin -user1:x:500:500:grp1:/home/user1:/bin/bash -``` - -With the `-f` option, the `tail` command does not give back and runs until the user interrupts it with the sequence CTRL + C. This option is very frequently used to track log files (the logs) in real time. - -Without the `-n` option, the tail command displays the last 10 lines of the file. - -### `sort` command - -The `sort` command sorts the lines of a file. - -It allows you to order the result of a command or the content of a file in a given order, numerically, alphabetically, by size (KB, MB, GB) or in reverse order. - -```bash -sort [-kx] [-n] [-u] [-o file] [-ty] file -``` - -Example: - -```bash -$ sort -k3 -t: -n /etc/passwd -root:x:0:0:root:/root:/bin/bash -adm:x:3:4:adm:/var/adm/:/sbin/nologin -``` - -| Option | Observation | -| --------- | -------------------------------------------- | -| `-kx` | Specifies the `x` column to sort on | -| `-n` | Requests a numeric sort | -| `-o file` | Saves the sort to the specified file | -| `-ty` | Specifies the field separator character `y`. | -| `-r` | Reverse the order of the result | -| `- u` | unique | - -The `sort` command sorts the file only on the screen. The file is not modified by the sorting. To save the sort, use the `-o` option or an output redirection `>`. - -By default, the numbers are sorted according to their character. Thus, "110" will be before "20", which will itself be before "3". The `-n` option must be specified so that the numeric character blocks are sorted by their value. - -The `sort` command reverses the order of the results, with the `-r` option: - -```bash -$ sort -k3 -t: -n -r /etc/passwd -root:x:0:0:root:/root:/bin/bash -adm:x:3:4:adm:/var/adm/:/sbin/nologin -``` - -In this example, the `sort` command will sort the contents of the `/etc/passwd` file this time from largest uid to smallest. - -Some advanced examples of using the `sort` command: - -* Shuffling values - -The `sort` command also allows you to shuffle values with the `-R` option: - -```bash -$ sort -R /etc/passwd -``` - -* Sorting IP addresses - -A system administrator is quickly confronted with the processing of IP addresses from the logs of his services such as SMTP, VSFTP or Apache. These addresses are typically extracted with the `cut` command. - -Here is an example with the file `dns-client.txt`: - -``` -192.168.1.10 -192.168.1.200 -5.1.150.146 -208.128.150.98 -208.128.150.99 -``` - -```bash -$ sort -nr dns-client.txt -208.128.150.99 -208.128.150.98 -192.168.1.200 -192.168.1.10 -5.1.150.146 -``` - -* Sorting file by removing duplicates - -The `sort` command knows how to remove the duplicates from the file output using `-u` as option. - -Here is an example with the file `colours.txt`: - -``` -Red -Green -Blue -Red -Pink -``` -``` -$ sort -u colours.txt -Blue -Green -Pink -Red -``` - -* Sorting file by sizes - -The `sort` command knows how to recognize file sizes, from commands like `ls` with the `-h` option. - -Here is an example with the file `size.txt`: - -``` -1,7G -18M -69K -2,4M -1,2M -4,2G -6M -124M -12,4M -4G -``` - -```bash -$ sort -hr size.txt -4,2G -4G -1,7G -124M -18M -12,4M -6M -2,4M -1,2M -69K -``` - -### `wc` command - -The `wc` command counts the number of lines, words and/or bytes in a file. - -```bash -wc [-l] [-m] [-w] file [files] -``` - -| Option | Observation | -| ------ | ------------------------------- | -| `-c` | Count the number of bytes. | -| `-m` | Count the number of characters. | -| `-l` | Counts the number of lines. | -| `-w` | Counts the number of words. | - -## Search - -### `find` command - -The `find` command searches for files or directories location. - -```bash -find directory [-name name] [-type type] [-user login] [-date date] -``` - -Since there are so many options to the `find` command, it is best to refer to the `man`. - -If the search directory is not specified, the `find` command will search from the current directory. - -| Option | Observation | -| ------------------- | -------------------------------------- | -| `-perm permissions` | Search for files by their permissions. | -| `-size size` | Search for files by size. | - -### `-exec` option of the `find` command - -It is possible to use the `-exec` option of the `find` command to execute a command on each result line: - -```bash -$ find /tmp -name *.txt -exec rm -f {} \; -``` - -The previous command searches for all files in the `/tmp` directory named `*.txt` and deletes them. - - -!!! Tip "Understand the `-exec` option" In the example above, the `find` command will construct a string representing the command to be executed. - - If the `find` command finds three files named `log1.txt`, `log2.txt`, and `log3.txt`, then the `find` command will construct the string by replacing in the string `rm -f {} \;` the braces with one of the results of the search, and do this as many times as there are results. - - This will give us: - - ``` - rm -f /tmp/log1.txt ; rm -f /tmp/log2.txt ; rm -f /tmp/log3.txt ; - ``` - - - The `;` character is a special shell character that must be protected by a `\` to prevent it from being interpreted too early by the `find` command (and not in the `-exec`). - -!!! Tip `$ find /tmp -name *.txt -delete` does the same thing. - -### `whereis` command - -The `whereis` command searches for files related to a command. - -```bash -whereis [-b] [-m] [-s] command -``` - -Example: - -```bash -$ whereis -b ls -ls: /bin/ls -``` - -| Option | Observation | -| ------ | ------------------------------- | -| `-b` | Search only the binary file. | -| `-m` | Searches only for man pages. | -| `-s` | Searches only for source files. | - -### `grep` command - -The `grep` command searches for a string in a file. - -```bash -grep [-w] [-i] [-v] "string" file -``` - -Example: - -```bash -$ grep -w "root:" /etc/passwd -root:x:0:0:root:/root:/bin/bash -``` - -| Option | Observation | -| ------ | --------------------------------------- | -| `-i` | Ignore the case of the searched string. | -| `-v` | Excludes lines containing the string. | -| `-w` | Search for the exact word. | - -The `grep` command returns the complete line containing the string you are looking for. -* The `^` special character is used to search for a string at the beginning of a line. -* The special character `$` searches for a string at the end of a line. - -```bash -$ grep -w "^root" /etc/passwd -``` - -!!! Note This command is very powerful and it is highly recommended to consult its manual. It has many derivatives. - -It is possible to search for a string in a file tree with the `-R` option. - -```bash -grep -R "Virtual" /etc/httpd -``` - -### Meta-characters (wildcards) - -Meta-characters replace one or more characters (or even an absence of characters) during a search. These meta-characters are also known as wildcards. They can be combined. The `*` character replaces a string composed of any characters. The `*` character can also represent an absence of character. - -```bash -$ find /home -name "test*" -/home/rockstar/test -/home/rockstar/test1 -/home/rockstar/test11 -/home/rockstar/tests -/home/rockstar/test362 -``` - -Meta-characters allow more complex searches by replacing all or part of a word. Simply replace the unknowns with these special characters. - -The character `?` replaces a single character, whatever it is. - -```bash -$ find /home -name "test?" -/home/rockstar/test1 -/home/rockstar/tests -``` - -The square brackets `[` are used to specify the values that a single character can take. - -```bash -$ find /home -name "test[123]*" -/home/rockstar/test1 -/home/rockstar/test11 -/home/rockstar/test362 -``` - -!!! Note Always surround words containing meta-characters with `"` to prevent them from being replaced by the names of files that meet the criteria. - -!!! Warning Do not confuse shell meta-characters with regular expression meta-characters. The `grep` command uses regular expression meta-characters. - -## Redirects and pipes - -### Standard input and output - -On UNIX and Linux systems, there are three standard streams. They allow programs, via the `stdio.h` library, to input or output information. - -These streams are called X channel or X file descriptor. - -By default: -* the keyboard is the input device for channel 0, called **stdin** ; -* the screen is the output device for channels 1 and 2, called **stdout** and **stderr**. - -![standards channels](images/input-output.png) - -**stderr** receives the error streams returned by a command. The other streams are directed to **stdout**. - -These streams point to peripheral files, but since everything is a file in UNIX/Linux, I/O streams can easily be diverted to other files. This principle is the strength of the shell. - -### Input redirection - -It is possible to redirect the input stream from another file with the character `<` or `<<`. The command will read the file instead of the keyboard: - -```bash -$ ftp -in serverftp << ftp-commands.txt -``` - -!!! Note Only commands that require keyboard input will be able to handle input redirection. - -Input redirection can also be used to simulate user interactivity. The command will read the input stream until it encounters the defined keyword after the input redirection. - -This feature is used to script interactive commands: - -```bash -$ ftp -in serverftp << END -user alice password -put file -bye -END -``` - -The keyword `END` can be replaced by any word. - -```bash -$ ftp -in serverftp << STOP -user alice password -put file -bye -STOP -``` - -The shell exits the `ftp` command when it receives a line containing only the keyword. - -!!! Warning The ending keyword, here `END` or `STOP`, must be the only word on the line and must be at the beginning of the line. - -The standard input redirection is rarely used because most commands accept a filename as an argument. - -The command `wc` could be used like this: - -```bash -$ wc -l .bash_profile -27 .bash_profile # the number of lines is followed by the file name -$ wc -l < .bash_profile -27 # returns only the number of lines -``` - -### Output redirection - -Standard output can be redirected to other files using the `>` or `>>` characters. - -The simple `>` redirection overwrites the contents of the output file: - -```bash -$ date +%F > date_file -``` - -while the double redirection `>>` adds (concatenates) to the content of the output file. - -```bash -$ date +%F >> date_file -``` - -In both cases, the file is automatically created when it does not exist. - -The standard error output can also be redirected to another file. This time it will be necessary to specify the channel number (which can be omitted for channels 0 and 1): - -```bash -$ ls -R / 2> errors_file -$ ls -R / 2>> errors_file -``` - -### Examples of redirection - -Redirection of 2 outputs to 2 files: - -```bash -$ ls -R / >> ok_file 2>> nok_file -``` - -Redirection of the 2 outputs to a single file: - -```bash -$ ls -R / >> log_file 2>&1 -``` - -Redirection of *stderr* to a "bottomless pit" (`/dev/null`): - -```bash -$ ls -R / 2>> /dev/null -``` - -When both output streams are redirected, no information is displayed on the screen. To use both the output redirection and to keep the display, you will have to use the command `tee`. - -### Pipes - -A **pipe** is a mechanism allowing you to link the standard output of a first command to the standard input of a second command. - -This communication is uni directional and is done with the `|` symbol. The pipe symbol `|` is obtained by pressing the SHIFT + | simultaneously. - -![pipe](images/pipe.png) - -All data sent by the control on the left of the pipe through the standard output channel is sent to the standard input channel of the control on the right. - -The commands particularly used after a pipe are filters. - -* Examples: - -Display only the beginning: - -```bash -$ ls -lia / | head -``` - -Display only the end: - -```bash -$ ls -lia / | tail -``` - -Sort the result: - -```bash -$ ls -lia / | sort -``` - -Count the number of words / characters: - -```bash -$ ls -lia / | wc -``` - -Search for a string in the result: - -```bash -$ ls -lia / | grep fichier -``` - -## Special points - -### `tee` command - -The `tee` command is used to redirect the standard output of a command to a file while maintaining the screen display. - -It is combined with the `|` pipe to receive as input the output of the command to be redirected: - -```bash -$ ls -lia / | tee fic -$ cat fic -``` - -The `-a` option adds to the file instead of overwriting it. - -### `alias` and `unalias` commands - -Using **alias** is a way to ask the shell to remember a particular command with its options and give it a name. - -For example: - -```bash -$ ll -``` - -will replace the command: - -```bash -$ ls -l -``` - -The `alias` command lists the aliases for the current session. Aliases are set by default on Linux distributions. Here, the aliases for a Rocky server: - -```bash -$ alias -alias l.='ls -d .* --color=auto' -alias ll='ls -l --color=auto' -alias ls='ls --color=auto' -alias vi='vim' -alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde' -``` - -The aliases are only defined temporarily, for the time of the user session. - -For permanent use, they must be created in the: - -* `.bashrc` file in the user's login directory; -* `/etc/profile.d/alias.sh` file for all users. - -!!! Warning Special care must be taken when using aliases which can be potentially dangerous! For example, an alias set up without the administrator's knowledge: - - ```bash - alias cd='rm -Rf' - ``` - -The `unalias` command allows you to delete aliases. - -To delete a single alias: - -```bash -$ unalias ll -``` - -To delete all aliases: - -```bash -$ unalias -a -``` - -To disable an alias temporarily, the combination is `\`. - -For example if we do: - -```bash -$ type ls -``` - -it might return the following: - -```bash -ls is an alias to « ls -rt » -``` - -Now that this is known, we can see the results of using the alias or disabling it one time with the `\` by executing the following: - -```bash -$ ls file* # order by time -file3.txt file2.txt file1.txt -$ \ls file* # order by name -file1.txt file2.txt file3.txt -``` - -### Aliases and useful functions - -* `grep` alias Colorize the result of the `grep` command: `alias grep='grep --color=auto'` - -* `mcd` function It is common to create a folder and then move around in it: `mcd() { mkdir -p "$1"; cd "$1"; }` - -* `cls` function Move to a folder and list its contents: `cls() { cd "$1"; ls; }` - -* `backup` function Create a backup copy of a file: `backup() { cp "$1"{,.bak}; }` - -* `extract` function Extract any type of archive: - -```bash -extract () { - if [ -f $1 ] ; then - case $1 in - *.tar.bz2) tar xjf $1 ;; - *.tar.gz) tar xzf $1 ;; - *.bz2) bunzip2 $1 ;; - *.rar) unrar e $1 ;; - *.gz) gunzip $1 ;; - *.tar) tar xf $1 ;; - *.tbz2) tar xjf $1 ;; - *.tgz) tar xzf $1 ;; - *.zip) unzip $1 ;; - *.Z) uncompress $1 ;; - *.7z) 7z x $1 ;; - *) - echo "'$1' cannot be extracted via extract()" ;; - esac - else - echo "'$1' is not a valid file" - fi -} - -``` - -* If `alias cmount` returns the following: `alias cmount="mount | column -t"` - -Then we can use cmount to show all of the system mounts in columns like this: - -`[root]# cmount` - -which would return our mounted filesystem in the following format: - -```bash -/dev/simfs on / type simfs (rw,relatime,usrquota,grpquota) -proc on /proc type proc (rw,relatime) -sysfs on /sys type sysfs (rw,relatime) -none on /dev type devtmpfs (rw,relatime,mode=755) -none on /dev/pts type devpts (rw,relatime,mode=600,ptmxmode=000) -none on /dev/shm type tmpfs (rw,relatime) -none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,relatime) - -``` - -### The character `;` - -The `;` character strings the commands. - -Les commandes s'exécuteront toutes séquentiellement dans l'ordre d'entrée une fois que l'utilisateur aura pressé ENTRÉE. - -```bash -$ ls /; cd /home; ls -lia; cd / -``` - -## Check your Knowledge - -:heavy_check_mark: What defines a user under Linux? (7 answers) - -:heavy_check_mark: What characterizes a long option for an order? - -:heavy_check_mark: Which commands allow you to search for help on a command: - -- [ ] `google` -- [ ] `chuck --norris` -- [ ] `info` -- [ ] `apropos` -- [ ] `whatis` - -:heavy_check_mark: Which command allows you to view a user's history? - -:heavy_check_mark: Which command allows you to search for text in a file? - -- [ ] `find` -- [ ] `grep` - -:heavy_check_mark: Which command allows you to search for a file? - -- [ ] `find` -- [ ] `grep` - -:heavy_check_mark: Which command redirects the error stream of a command to a new `errors.log` file: - -- [ ] `ls -R / 2> errors.log` -- [ ] `ls -R / 2>> errors.log` -- [ ] `ls -R / 2> errors.log 2>&1` diff --git a/docs/books/admin_guide/08-process.it.md b/docs/books/admin_guide/08-process.it.md deleted file mode 100644 index 8879245558..0000000000 --- a/docs/books/admin_guide/08-process.it.md +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: Gestione dei processi ---- -# Gestione dei processi - -In questo capitolo imparerai come lavorare con i processi. - ---- - -**Obiettivi** : In questo capitolo, futuri amministratori Linux impareranno come: - -:heavy_check_mark: Riconoscere il `PID` e il `PPID` di un processo; -:heavy_check_mark: Visualizzare e cercare processi; -:heavy_check_mark: Gestire i processi. - -:checkered_flag: **processi**, **linux** - -**Conoscenza**: :star: :star: -**Complessità**: :star: - -**Tempo di lettura**: 20 minuti - ---- - -## Generalità - -Un sistema operativo è costituito da processi. Questi processi sono eseguiti in un ordine specifico e sono correlati tra loro. Ci sono due categorie di processi, quelli focalizzati sull'ambiente utente e quelli focalizzati sull'ambiente hardware. - -Quando viene eseguito un programma, Il sistema creerà un processo posizionando i dati del programma e il codice in memoria e creando una **runtime stack**. Un processo è quindi un'istanza di un programma con un ambiente di processore associato (contatore ordinale, registri, etc...) e ambiente di memoria. - -Ogni processo ha: - -* un _PID_ : _**P**rocess **ID**entifier_, un identificatore di processo unico; -* un _PPID_ : _**P**arent **P**rocess **ID**entifier_, identificatore univoco del processo genitore. - -Da filiazioni successive, il processo `init` è il padre di tutti i processi. - -* Un processo è sempre creato da un processo genitore; -* Un processo genitore può avere più processi figlio. - -C'è una relazione genitore/figlio tra i processi. Un processo figlio è il risultato del processo genitore che chiama il _fork ()_ iniziale e duplicando il proprio codice crea un processo figlio. Il _PID_ del processo figlio viene restituito al processo genitore in modo che possa comunicare. Ogni processo figlio ha l'identificatore del suo processo genitore, il _PPID_. - -Il numero _PID_ rappresenta il processo al momento dell'esecuzione. Quando il processo finisce, il numero è di nuovo disponibile per un altro processo. Eseguendo lo stesso comando più volte produrrà un diverso _PID_ ogni volta. - - - -!!! Note "Nota" - I processi non devono essere confusi con i _threads_. Ogni processo ha il proprio contesto di memoria (risorse e spazio di indirizzamento), mentre il _threads_ dello stesso processo condivide lo stesso contesto. - -## Visualizzazione dei processi - -Il comando `ps` visualizza lo stato dei processi in esecuzione. - -```bash -ps [-e] [-f] [-u login] -``` - -Esempio: - -```bash -# ps -fu root -``` - -| Opzione | Descrizione | -| ---------- | ---------------------------------- | -| `-e` | Visualizza tutti i processi. | -| `-f` | Visualizza ulteriori informazioni. | -| `-u` login | Visualizza i processi dell'utente. | - -Alcune opzioni aggiuntive: - -| Opzione | Descrizione | -| --------------------- | ------------------------------------------------------- | -| `-g` | Visualizza i processi nel gruppo. | -| `-t tty` | Visualizza i processi in esecuzione dal terminale. | -| `-p PID` | Visualizza le informazioni del processo. | -| `-H` | Visualizza le informazioni in una struttura ad albero. | -| `-I` | Visualizza ulteriori informazioni. | -| `--sort COL` | Ordina il risultato secondo una colonna. | -| `--headers` | Visualizza l'intestazione su ogni pagina del terminale. | -| `--format "%a %b %c"` | Personalizza il formato di visualizzazione dell'uscita. | - -Senza un'opzione specificata, il comando `ps` visualizza solo i processi in esecuzione sul terminale corrente. - -Il risultato viene visualizzato in colonne: - -```bash -# ps -ef -UID PID PPID C STIME TTY TIME CMD -root 1 0 0 Jan01 ? 00:00/03 /sbin/init -``` - -| Colonna | Descrizione | -| ------- | ------------------------------------- | -| `UID` | Utente proprietario. | -| `PID` | Identificatore di processo. | -| `PPID` | Identificatore del processo genitore. | -| `C` | Priorità del processo. | -| `STIME` | Data e ora di esecuzione. | -| `TTY` | Terminale di esecuzione. | -| `TIME` | Durata di elaborazione. | -| `CMD` | Comando eseguito. | - -Il comportamento del controllo può essere completamente personalizzato: - -```bash -# ps -e --format "%P %p %c %n" --sort ppid --headers - PPID PID COMMAND NI - 0 1 systemd 0 - 0 2 kthreadd 0 - 1 516 systemd-journal 0 - 1 538 systemd-udevd 0 - 1 598 lvmetad 0 - 1 643 auditd -4 - 1 668 rtkit-daemon 1 - 1 670 sssd 0 -``` - -## Tipi di processi - -Il processo dell'utente: - -* è iniziato da un terminale associato a un utente; -* accede alle risorse tramite richieste o daemons. - -Il processo di sistema (_daemon_): - -* è iniziato dal sistema; -* non è associato a nessun terminale, ed è di proprietà di un utente di sistema (spesso `root`); -* è caricato al momento dell'avvio, risiede in memoria, e sta aspettando una chiamata; -* è solitamente identificato dalla lettera `d` associato al nome del processo. - -I processi di sistema sono quindi chiamati daemons (_**D**isk **A**nd **E**xecution **MON**itor_). - -## Autorizzazioni e diritti - -Quando viene eseguito un comando, le credenziali dell'utente sono passate al processo creato. - -Per impostazione predefinita., l'attuale `UID` e `GID` (del processo) sono quindi identici al **effettivo** `UID` e `GID` (il `UID` e `GID` dell'utente che ha eseguito il comando). - -Quando un `SUID` (e/o `SGID`) è impostato su un comando, l'attuale `UID` (e/o `GID`) diventa quello del proprietario (e/o gruppo proprietario) del comando e non più quello dell'utente o del gruppo di utenti che ha emesso il comando. Effettivo e reale **UIDs** sono quindi **differenti**. - -Ogni volta che si accede a un file, il sistema controlla i diritti del processo in base ai suoi effettivi identificatori. - -## Gestione dei processi - -Un processo non può essere eseguito indefinitamente, perchè questo sarebbe a discapito di altri processi in esecuzione e impedirebbe il multitasking. - -Il tempo totale di elaborazione disponibile è quindi diviso in piccoli intervalli, e ogni processo (con una priorità) accede al processore in modo sequenziale. Il processo prenderà diversi stati durante la sua vita tra gli stati: - -* pronto: in attesa della disponibilità del processo; -* in esecuzione: accede al processore; -* sospeso: aspettando un I/O (input/output); -* fermato: aspettando un segnale da un altro processo; -* zombie: richiesta di distruzione; -* morto: il padre del processo chiude il suo processo figlio. - -La sequenza di chiusura del processo è la seguente: - -1. Chiusura dei file aperti; -2. Rilascio della memoria usata; -3. Invio di un segnale ai processi genitore e figlio. - -Quando un processo genitore muore, si dice che i suoi processi figli sono orfani. Sono quindi adottati dal processo `init` che li distruggerà. - -### La priorità di un processo - -Il processore funziona in condivisione del tempo (time sharing) con ogni processo occupando una determinata quantità di tempo del processore. - -I processi sono classificati per priorità il cui valore varia da **-20** (la massima priorità) a **+19** (la priorità più bassa). - -La priorità predefinita di un processo è **0**. - -### Modalità di funzionamento - -I processi possono essere eseguiti in due modi: - -* **sincrona**: l'utente perde l'accesso alla shell durante l'esecuzione del comando. Il prompt dei comandi riappare alla fine dell'esecuzione del processo. -* **asincrona**: il processo viene elaborato in background. Il prompt dei comandi viene visualizzato di nuovo immediatamente. - -I vincoli della modalità asincrona: - -* il comando o lo script non devono attendere l'input della tastiera; -* il comando o lo script non devono restituire alcun risultato sullo schermo; -* lasciare che la shell termini il processo. - -## Controlli per la gestione dei processi - -### comando `kill` - -Il comando `kill` invia un segnale di arresto a un processo. - -```bash -kill [-signal] PID -``` - -Esempio: - -```bash -$ kill -9 1664 -``` - -| Codice | Segnale | Descrizione | -| ------ | --------- | ---------------------------------------------------------- | -| `2` | _SIGINT_ | Arresto immediato del processo | -| `9` | _SIGKILL_ | Interruzione del processo (CTRL + D) | -| `15` | _SIGTERM_ | Arresto pulito del processo | -| `18` | _SIGCONT_ | Riprendere il processo | -| `19` | _SIGSTOP_ | Sospendere il processo | - -I segnali sono i mezzi di comunicazione tra i processi. Il comando `kill` invia un segnale a un processo. - -!!! Tip "Suggerimento" - L'elenco completo dei segnali presi in considerazione dal comando `kill` è disponibile digitando il comando: - -```bash -$ man 7 signal -``` - -### comando `nohup` - -`nohup` consente il lancio di un processo indipendentemente da una connessione. - -```bash -nohup command -``` - -Esempio: - -```bash -$ nohup myprogram.sh 0CTRL + Z contemporaneamente, il processo sincrono è temporaneamente sospeso. L'accesso al prompt viene ripristinato dopo aver visualizzato il numero del processo che è stato appena sospeso. - -### istruzione `&` - -La dichiarazione `&` esegue il comando in modo asincrono (il comando viene quindi chiamato _job_) e visualizza il numero di _job_. L'accesso al prompt viene quindi restituito. - -Esempio: - -```bash -$ time ls -lR / > list.ls 2> /dev/null & -[1] 15430 -$ -``` - -Il numero _job_ è ottenuto durante l'elaborazione in background e viene visualizzato in parentesi quadre, seguito dal numero di `PID`. - -### comandi `fg` e `bg` - -Il comando `fg` mette il processo in primo piano: - -```bash -$ time ls -lR / > list.ls 2>/dev/null & -$ fg 1 -time ls -lR / > list.ls 2/dev/null -``` - -mentre il comando `bg` lo colloca in background: - -```bash -[CTRL]+[Z] -^Z -[1]+ Stopped -$ bg 1 -[1] 15430 -$ -``` - -Se è stato messo in background quando è stato creato con l'argomento `&` o più tardi con la combinazione CTRL +Z, un processo può essere riportato in primo piano con il comando `fg` e il suo numero di lavoro. - -### comando `jobs` - -Il comando `jobs` visualizza l'elenco dei processi in esecuzione in background e specifica il loro numero di lavoro. - -Example: - -```bash -$ jobs -[1]- Running sleep 1000 -[2]+ Running find / > arbo.txt -``` - -Le colonne rappresentano: - -1. numero di lavoro; -2. l'ordine in cui i processi sono in esecuzione - -- un `+` : questo processo è il prossimo processo da eseguire per impostazione predefinita con `fg` o `bg` ; -- un `-` : questo processo è il prossimo processo a prendere il `+` ; - -3. _Running_ (processo in esecuzione) o _Stopped_ (processo sospeso). -4. il comando - -### comandi `nice` e `renice` - -Il comando `nice` consente l'esecuzione di un comando specificando la sua priorità. - -```bash -nice priority command -``` - -Esempio: - -```bash -$ nice -n+15 find / -name "file" -``` - -a differenza di `root`, un utente standard può solo ridurre la priorità di un processo. Saranno accettati solo valori tra +0 e +19. - -!!! Tip "Suggerimento" - Quest'ultima limitazione può essere modificata su base utente o per gruppo modificando il file `/etc/security/limits.conf`. - -Il comando `renice` ti consente di modificare la priorità di un processo di esecuzione. - -```bash -renice priority [-g GID] [-p PID] [-u UID] -``` - -Esempio: - -```bash -$ renice +15 -p 1664 -``` - -| Opzione | Descrizione | -| ------- | ------------------------------------------- | -| `-g` | `GID` del gruppo proprietario del processo. | -| `-p` | `PID` del processo. | -| `-u` | `UID` del proprietario del processo. | - -Il comando `renice` agisce sui processi già in esecuzione. È quindi possibile modificare la priorità di un processo specifico, ma anche di diversi processi appartenenti a un utente o un gruppo. - -!!! Tip "Suggerimento" - Il comando `pidof`, accoppiato con il comando `xargs` (vedi il pagina dei comandi avanzati), consente di applicare una nuova priorità in un singolo comando: - -```bash -$ pidof sleep | xargs renice 20 -``` - -### comando `top` - -Il comando `top` visualizza i processi e il loro consumo di risorse. - -```bash -$ top -PID USER PR NI ... %CPU %MEM TIME+ COMMAND -2514 root 20 0 15 5.5 0:01.14 top -``` - -| Colonna | Descrizione | -| --------- | --------------------------------- | -| `PID` | Identificatore del processo. | -| `USER` | Utente proprietario. | -| `PR` | Priorità del processo. | -| `NI` | Valore di Nice. | -| `%CPU` | Carico del processore. | -| `%MEM` | Carico di memoria. | -| `TIME+` | Tempo di utilizzo del processore. | -| `COMMAND` | Comando eseguito. | - -Il comando `top` consente il controllo dei processi in tempo reale e in modalità interattiva. - -### comandi `pgrep` e `pkill` - -Il comando `pgrep` cerca i processi in esecuzione per un nome di processo e visualizza il _PID_ che soddisfa i criteri di selezione sull'output standard. - -Il comando `pkill` invierà il segnale specificato (per impostazione predefinita _SIGTERM_) ad ogni processo. - -```bash -pgrep process -pkill [-signal] process -``` - -Esempi: - -* Ottenere il numero di processo di `sshd`: - -```bash -$ pgrep -u root sshd -``` - -* Termina tutti i processi `tomcat`: - -```bash -$ pkill tomcat -``` diff --git a/docs/books/admin_guide/09-backups.it.md b/docs/books/admin_guide/09-backups.it.md deleted file mode 100644 index 82925b4bc5..0000000000 --- a/docs/books/admin_guide/09-backups.it.md +++ /dev/null @@ -1,833 +0,0 @@ ---- -title: Backup e Ripristino -author: Antoine Le Morvan -contributors: Steven Spencer, Franco Colussi -update: 11-10-2021 ---- -# Backup e ripristino - -In questo capitolo imparerai come eseguire il backup e ripristinare i tuoi dati con Linux. - ---- - -**Obiettivi** : In questo capitolo, futuri amministratori Linux impareranno come: - -:heavy_check_mark: usare i comandi `tar` e `cpio` per effettuare un backup; -:heavy_check_mark: controllare i loro backup e ripristinare i dati; -:heavy_check_mark: comprimere o decomprimere i loro backup. - -:checkered_flag: **backup**, **ripristino**, **compressione** - -**Conoscenza**: :star: :star: :star: -**Complessità**: :star: :star: - -**Tempo di lettura**: 40 minuti - ---- - -!!! Note "Nota" - In questo capitolo le strutture di comando utilizzano "dispositivo" per specificare sia un percorso di destinazione per il backup, e sia la posizione sorgente durante il ripristino. Il dispositivo può essere un supporto esterno o un file locale. Dovresti sviluppare una certa confidenza con questo concetto durante lo svolgimento del capitolo, ma puoi sempre ritornare a questa nota per chiarimenti se ne hai bisogno. - -Il backup risponde a una necessità di conservare e ripristinare i dati in modo sicuro ed efficace. - -Il backup consente di proteggersi dai seguenti problemi: - -* **Distruzione**: volontaria o involontaria. Umana o tecnica. Virus, ... -* **Cancellazione**: volontaria o involontaria. Umana o tecnica. Virus, ... -* **Integrità** : i dati diventano inutilizzabili. - -Nessun sistema è infallibile, nessun umano è infallibile, quindi per evitare di perdere dati, questi devono essere salvati per poi essere in grado di ripristinarli dopo un problema. - -Il supporto di backup dovrebbe essere tenuto in un'altra stanza (o edificio) rispetto al server in modo che un disastro non distrugga il server e i backup. - -Inoltre, l'amministratore deve controllare regolarmente che i supporti siano ancora leggibili. - -## Generalità - -Ci sono due principi, il **backup** e l'**archivio**. - -* L'archivio distrugge la fonte delle informazioni dopo l'operazione. -* Il backup conserva la fonte delle informazioni dopo l'operazione. - -Queste operazioni consistono nel salvare informazioni in un file, su un supporto periferico o supportato (nastri, dischi, ...). - -### Il processo - -I backup richiedono molta disciplina e rigore da parte dell'amministratore di sistema. È necessario porsi le seguenti domande: - -* Qual è il mezzo appropriato? -* Cosa dovrebbe essere salvato? -* Quante copie? -* Quanto durerà il backup? -* Metodo? -* Quante volte? -* Automatico o manuale? -* Dove conservarlo? -* Quanto tempo sarà conservato? - -### Metodi di backup - -* **Completo**: uno o più **filesystems** sono salvati (kernel, dati, utilità, ...). -* **Parziale**: uno o più **files** sono salvati (configurazioni, directories, ...). -* **Differenziale**: solo i file modificati dall'ultimo backup **completo** sono salvati. -* **Incrementale**: solo i file modificati dall'ultimo backup sono salvati. - -### Periodicità - -* **Pre-corrente** : in un dato momento (prima di un aggiornamento del sistema, ...). -* **Periodica**: Ogni giorno, settimana, mese, ... - -!!! Tip "Suggerimento" - Prima di effettuare modifiche al sistema, può essere utile effettuare un backup. Tuttavia, non ha senso eseguire il backup dei dati ogni giorno se vengono modificati solo ogni mese. - -### Metodi di ripristino - -A seconda delle utilità disponibili, sarà possibile eseguire diversi tipi di ripristini. - -* **Ripristino Completo**: alberi delle directory, ... -* **Ripristino Selettivo**: parte dell'albero, files, ... - -È possibile ripristinare un intero backup ma è anche possibile ripristinarne solo una parte. Tuttavia, quando si ripristina una directory, i file creati dopo il backup non vengono eliminati. - -!!! Tip "Suggerimento" - Per ripristinare una directory com'era al momento del backup, è necessario eliminarne completamente il contenuto prima di avviare il ripristino. - -### Gli strumenti - -Ci sono molte utilità per fare il backup. - -* **strumenti di editor** ; -* **strumenti grafici**; -* **strumenti da riga di comando**: `tar`, `cpio`, `pax`, `dd`, `dump`, ... - -I comandi che useremo qui sono `tar` e `cpio`. - -* `tar`: - * facile da usare ; - * consente di aggiungere file a un backup esistente. -* `cpio`: - * conserva i proprietari; - * conserva gruppi, date e permessi; - * salta i file danneggiati; - * file system completo. - -!!! Note "Nota" - Questi comandi salvano in un formato proprietario e standardizzato. - -### Convenzione di denominazione - -L'uso di una convenzione di denominazione consente di indirizzare rapidamente il contenuto di un file di backup ed evitare così ripristini pericolosi. - -* nome della directory; -* utilità utilizzata; -* opzioni utilizzate; -* data. - -!!! Tip "Suggerimento" - Il nome del backup deve essere un nome esplicito. - -!!! Note "Nota" - La nozione di estensione sotto Linux non esiste. In altre parole, il nostro uso delle estensioni qui è per l'operatore umano. Se l'amministratore di sistema vede un'estensione di file `.tar.gz` o `.tgz`, ad esempio, allora sa come gestire il file. - -### Contenuto di un backup - -Un backup contiene in genere i seguenti elementi: - -* il file; -* il nome; -* il proprietario; -* la dimensione; -* i permessi; -* data di accesso. - -!!! Note "Nota" - Manca il numero di `inode`. - -### Modalità di archiviazione - -Esistono due diverse modalità di archiviazione: - -* file su disco; -* dispositivo. - -## Tape ArchiveR - `tar` - -Il comando `tar` consente di salvare su più supporti successivi (opzioni multi-volume). - -È possibile estrarre tutto o parte di un backup. - -`tar` esegue implicitamente il backup in modalità relativa anche se il percorso delle informazioni di cui eseguire il backup è menzionato in modalità assoluta. Tuttavia, sono possibili backup e ripristini in modalità assoluta. - -### Linee guida per il ripristino - -Le domande giuste da porsi sono: - -* cosa: parziale o completo; -* dove: il luogo in cui i dati saranno ripristinati; -* come: assoluto o relativo. - -!!! Warning "Avvertimento" - Prima di un ripristino, è importante prendersi del tempo per pensare e determinare il metodo più appropriato, questo per evitare errori. - -I ripristini vengono solitamente eseguiti dopo che si è verificato un problema che deve essere risolto rapidamente. Un ripristino scadente può, in alcuni casi, peggiorare la situazione. - -### Backup con `tar` - -L'utilità predefinita per la creazione di backup su sistemi UNIX è il comando `tar`. Questi backup possono essere compressi con `bzip2`, `xz`, `lzip`, `lzma`, `lzop`, `gzip`, `compress` o `zstd`. - -`tar` consente di estrarre un singolo file o una directory da un backup, visualizzarne il contenuto o convalidarne l'integrità. - -#### Stimare le dimensioni di un backup - -Il comando seguente stima la dimensione in kilobyte di un possibile file _tar_: - -```bash -$ tar cf - /directory/to/backup/ | wc -c -20480 -$ tar czf - /directory/to/backup/ | wc -c -508 -$ tar cjf - /directory/to/backup/ | wc -c -428 -``` - -!!! Warning "Avvertimento" - Attenzione, la presenza di "-" nella riga di comando disturba `zsh`. Passa a `bash`! - -#### Convenzione di denominazione per un backup `tar` - -Ecco un esempio di convenzione di denominazione per un backup `tar`, sapendo che la data deve essere aggiunta al nome. - -| Opzioni | Files | Suffisso | Osservazione | -| ------- | ------- | ---------------- | ------------------------------------------------- | -| `cvf` | `home` | `home.tar` | `/home` in modalità relativa, forma non compressa | -| `cvfP` | `/etc` | `etc.A.tar` | `/etc` in modalità assoluta, nessuna compressione | -| `cvfz` | `usr` | `usr.tar.gz` | `/usr` in modalità relativa, compressione _gzip_ | -| `cvfj` | `usr` | `usr.tar.bz2` | `/usr` in modalità relativa, compressione _bzip2_ | -| `cvfPz` | `/home` | `home.A.tar.gz` | `home` in modalità assoluta, compressione _gzip_ | -| `cvfPj` | `/home` | `home.A.tar.bz2` | `home` in modalità assoluta, compressione _bzip2_ | -| … | | | | - -#### Creare un backup - -##### Creare un backup in modalità relativa - -La creazione di un backup non compresso in modalità relativa viene eseguita con le opzioni `cvf`: - -```bash -tar c[vf] [device] [file(s)] -``` - -Esempio: - -```bash -[root]# tar cvf /backups/home.133.tar /home/ -``` - -| Opzione | Descrizione | -| ------- | ------------------------------------------------------ | -| `c` | Crea un backup. | -| `v` | Visualizza il nome dei file elaborati. | -| `f` | Consente di specificare il nome del backup (supporto). | - -!!! Tip "Suggerimento" - Il trattino (`-`) davanti alle opzioni di 'tar' non è necessario! - -##### Creare un backup in modalità assoluta - -La creazione di un backup non compresso in modo esplicito in modalità assoluta viene eseguita con le opzioni `cvfP`: - -```bash -tar c[vf]P [device] [file(s)] -``` - -Esempio: - -```bash -[root]# tar cvfP /backups/home.133.P.tar /home/ -``` - -| Opzione | Descrizione | -| ------- | ------------------------------------ | -| `P` | Crea un backup in modalità assoluta. | - -!!! Warning "Avvertimento" - Con la chiave `P`, il percorso dei file di cui eseguire il backup deve essere inserito come **assoluto**. Se le due condizioni (chiave `P` e percorso **assoluto**) non sono indicate, il backup è in modalità relativa. - -##### Creazione di un backup compresso con `gzip` - -La creazione di un backup compresso con 'gzip' viene eseguita con le opzioni `cvfz`: - -```bash -$ tar cvzf backup.tar.gz dirname/ -``` - -| Opzione | Descrizione | -| ------- | ------------------------------ | -| `z` | Comprime il backup con _gzip_. | - -!!! Note "Nota" - L'estensione `.tgz` è un'estensione equivalente a `.tar.gz`. - -!!! Note "Nota" - Mantenere invariate le opzioni `cvf` (`tvf` o `xvf`) per tutte le operazioni di backup e aggiungere semplicemente la chiave di compressione alla fine delle chiavi rende il comando più facile da capire (ad esempio `cvfz` o `cvfj`, ecc.). - -##### Creazione di un backup compresso con `bzip` - -La creazione di un backup compresso con `bzip` viene eseguita con le opzioni `cvfj`: - -```bash -$ tar cvfj backup.tar.bz2 dirname/ -``` - -| Opzione | Descrizione | -| ------- | ------------------------------ | -| `j` | Comprime il backup con_bzip2_. | - -!!! Note "Nota" - Le estensioni `.tbz` and `.tb2` sono equivalenti all'estensione `.tar.bz2`. - -##### Compressione `compress`, `gzip`, `bzip2`, `lzip` e `xz` - -La compressione, e di conseguenza la decompressione, avrà un impatto sul consumo di risorse (tempo e utilizzo della CPU). - -Ecco una classifica della compressione di un insieme di file di testo, dal meno al più efficiente: - -* compress (`.tar.Z`) -* gzip (`.tar.gz`) -* bzip2 (`.tar.bz2`) -* lzip (`.tar.lz`) -* xz (`.tar.xz`) - -#### Aggiungere un file o una directory a un backup esistente - -È possibile aggiungere uno o più elementi a un backup esistente. - -```bash -tar {r|A}[key(s)] [device] [file(s)] -``` - -Per aggiungere `/etc/passwd` al backup `/backups/home.133.tar`: - -```bash -[root]# tar rvf /backups/home.133.tar /etc/passwd -``` - -L'aggiunta di una directory è simile. Qui aggiungi `dirtoadd` a `backup_name.tar`: - -```bash -$ tar rvf backup_name.tar dirtoadd -``` - -| Opzione | Descrizione | -| --- --- | ----------------------------------------------------------------------------------------------- | -| `r` | Aggiunge uno o più file alla fine di un backup multimediale ad accesso diretto (disco rigido). | -| `A` | Aggiunge uno o più file al termine di un backup su un supporto di accesso sequenziale (nastro). | - -!!! Note "Nota" - Non è possibile aggiungere file o cartelle a un backup compresso. - -```bash - $ tar rvfz backup.tgz filetoadd - tar: Cannot update compressed archives - Try `tar --help' or `tar --usage' for more information. -``` - -!!! Note "Nota" - Se il backup è stato eseguito in modalità relativa, aggiungere i file in modalità relativa. Se il backup è stato eseguito in modalità assoluta, aggiungere i file in modalità assoluta. Le modalità miste possono causare problemi durante il ripristino. - -#### Elencare il contenuto di un backup - -È possibile visualizzare il contenuto di un backup senza estrarlo. - -```bash -tar t[key(s)] [device] -``` - -| Opzione | Descrizione | -| -------- | -------------------------------------------------------- | -| `t` | Visualizza il contenuto di un backup (compresso o meno). | - -Esempi: - -```bash -$ tar tvf backup.tar -$ tar tvfz backup.tar.gz -$ tar tvfj backup.tar.bz2 -``` - -Quando il numero di file in un backup diventa grande, è possibile inviare in _pipe_ il risultato del comando `tar` ad un _impaginatore_ (`more`, `less`, `most`, ecc.): - -```bash -$ tar tvf backup.tar | less -``` - -!!! Tip "Suggerimento" - Per elencare o recuperare il contenuto di un backup, non è necessario menzionare l'algoritmo di compressione utilizzato al momento della creazione del backup. Cioè, un `tar tvf` equivale a `tar tvfj`, per leggere il contenuto, e un `tar xvf` è equivalente a `tar xvfj`, per estrarre. - -!!! Tip "Suggerimento" - Controllare sempre il contenuto di un backup. - -#### Verificare l'integrità di un backup - -L'integrità di un backup può essere testata con la chiave `W` al momento della sua creazione: - -```bash -$ tar cvfW file_name.tar dir/ -``` - -L'integrità di un backup può essere testata con la chiave `d` dopo la sua creazione: - -```bash -$ tar vfd file_name.tar dir/ -``` - -!!! Tip "Suggerimento" - Aggiungendo una seconda `v` alla chiave precedente, si otterrà l'elenco dei file archiviati e le differenze tra i file archiviati e quelli presenti nel file system. - ```bash - $ tar vvfd /tmp/quodlibet.tar .quodlibet/ - drwxr-x--- rockstar/rockstar 0 2021-05-21 00:11 .quodlibet/ - -rw-r--r-- rockstar/rockstar 0 2021-05-19 00:59 .quodlibet/queue - […] - -rw------- rockstar/rockstar 3323 2021-05-21 00:11 .quodlibet/config - .quodlibet/config: Mod time differs - .quodlibet/config: Size differs - […] - ``` - -L'opzione `W` viene utilizzata anche per confrontare il contenuto di un archivio con il filesystem: - -```bash -$ tar tvfW file_name.tar -Verify 1/file1 -1/file1: Mod time differs -1/file1: Size differs -Verify 1/file2 -Verify 1/file3 -``` - -La verifica con l'opzione `W` non può essere eseguita con un archivio compresso. Deve essere utilizzata l'opzione `d` : - -```bash -$ tar dfz file_name.tgz -$ tar dfj file_name.tar.bz2 -``` - -#### Estrarre (_untar_) un backup - -L'estrazione di un backup (_untar_) `*.tar` viene eseguito con le opzioni `xvf`: - -Estrarre il file `etc/exports` dal backup `/savings/etc.133.tar` nella cartella `etc` della directory corrente: - -```bash -$ tar xvf /backups/etc.133.tar etc/exports -``` - -Estrarre tutti i file dal backup compresso `/backups/home.133.tar.bz2` nella directory corrente: - -```bash -[root]# tar xvfj /backups/home.133.tar.bz2 -``` - -Estrarre tutti i file dal backup `/backups/etc.133.P.tar` nella loro directory originale: - -```bash -$ tar xvfP /backups/etc.133.P.tar -``` - -!!! Warning "Avvertimento" - Posizionati nel posto giusto. - -Controlla il contenuto del backup. - -| Opzione | Descrizione | -| ------- | --------------------------------------------- | -| `x` | Estrarre i file dal backup, compressi o meno. | - -L'estrazione di un backup _tar-gzipped_ ('*.tar.gz') viene eseguita con le opzioni `xvfz`: - -```bash -$ tar xvfz backup.tar.gz -``` - -L'estrazione di un _tar-bzipped_ (`*.tar.bz2`) viene eseguita con le opzioni `xvfj`: - -```bash -$ tar xvfj backup.tar.bz2 -``` - -!!! Tip "Suggerimento" - Per estrarre o elencare il contenuto di un backup, non è necessario menzionare l'algoritmo di compressione utilizzato per creare il backup. Cioè, un `tar xvf` equivale a `tar xvfj`, per estrarre il contenuto, e un `tar tvf` è equivalente a `tar tvfj`, per elencare. - -!!! Warning "Avvertimento" - Per ripristinare i file nella loro directory originale (chiave `P` di un `tar xvf`), è necessario aver generato il backup con il percorso assoluto. Cioè, con la chiave `P` di un `tar cvf`. - -##### Estrarre solo un file da un backup _tar_ - -Per estrarre un file specifico da un backup _tar_, specificare il nome di tale file alla fine del comando `tar xvf`. - -```bash -$ tar xvf backup.tar /path/to/file -``` - -Il comando precedente estrae solo il file `/path/to/file` dal backup `backup.tar`. Questo file verrà ripristinato nella directory `/path/to/` creata, o già presente, nella directory corrente. - -```bash -$ tar xvfz backup.tar.gz /path/to/file -$ tar xvfj backup.tar.bz2 /path/to/file -``` - -##### Estrarre una cartella da un backup _tar_ - -Per estrarre una sola directory (incluse le sottodirectory e i file) da un backup, specificare il nome della directory alla fine del comando `tar xvf`. - -```bash -$ tar xvf backup.tar /path/to/dir/ -``` - -Per estrarre più directory, specificare ciascuno dei nomi uno dopo l'altro: - -```bash -$ tar xvf backup.tar /path/to/dir1/ /path/to/dir2/ -$ tar xvfz backup.tar.gz /path/to/dir1/ /path/to/dir2/ -$ tar xvfj backup.tar.bz2 /path/to/dir1/ /path/to/dir2/ -``` - -##### Estrarre un gruppo di file da un backup _tar_ utilizzando espressioni regolari (_regex_) - -Specificate un _regex_ per estrarre i file corrispondenti al modello di selezione specificato. - -Ad esempio, per estrarre tutti i file con l'estensione `.conf` : - -```bash -$ tar xvf backup.tar --wildcards '*.conf' -``` - -chiavi : - -* `--wildcards *.conf` corrisponde ai file con estensione `.conf`. - -## _CoPy Input Output_ - `cpio` - -Il comando `cpio` consente di salvare su più supporti successivi senza specificare alcuna opzione. - -È possibile estrarre tutto o parte di un backup. - -Non c'è alcuna opzione, a differenza del comando `tar`, per eseguire il backup e comprimere allo stesso tempo. -Quindi è fatto in due passaggi: backup e compressione. - -Per eseguire un backup con `cpio`, è necessario specificare un elenco di file di cui eseguire il backup. - -Questo elenco è fornito con i comandi `find`, `ls` o `cat`. - -* `find` : sfogliare un albero, ricorsivo o meno; -* `ls` : elencare una directory, ricorsiva o meno; -* `cat` : legge un file contenente gli alberi delle directory o i file da salvare. - -!!! Note "Nota" - `ls` non può essere usato con `-l` (dettagli) o `-R` (ricorsivo). - Richiede un semplice elenco di nomi. - -### Creare un backup con il comando `cpio` - -Sintassi del comando `cpio`: - -```bash -[files command |] cpio {-o| --create} [-options] [device] -``` - -Esempio: - -Con un reindirizzamento dell'output di `cpio`: - -```bash -$ find /etc | cpio -ov > /backups/etc.cpio -``` - -Utilizzo del nome di un supporto di backup: - -```bash -$ find /etc | cpio -ovF /backups/etc.cpio -``` - -Il risultato del comando `find` viene inviato come input al comando `cpio` tramite una _pipe_ (carattere `|`, AltGr + |). - -Qui, il comando `find /etc` restituisce un elenco di file corrispondenti al contenuto della directory `/etc` (ricorsivamente) al comando `cpio`, che esegue il backup. - -Non dimenticare il segno `>` durante il salvataggio o l'opzione `F save_name_cpio`. - -| Opzione | Descrizione | -| ------- | -------------------------------------------- | -| `-o` | Crea un backup (_output_). | -| `-v` | Visualizza il nome dei file elaborati. | -| `-F` | Indica il backup da modificare (supporto). | - -Backup su un supporto: - -```bash -$ find /etc | cpio -ov > /dev/rmt0 -``` - -Il supporto può essere di diversi tipi: - -* unità nastro: `/dev/rmt0` ; -* una partizione: `/dev/sda5`, `/dev/hda5`, etc. - -### Tipo di backup - -#### Backup con percorso relativo - -```bash -$ cd / -$ find etc | cpio -o > /backups/etc.cpio -``` - -#### Backup con percorso assoluto - -```bash -$ find /etc | cpio -o > /backups/etc.A.cpio -``` - -!!! Warning "Avvertimento" - Se il percorso specificato nel comando `find` è **assoluto** il backup verrà eseguito in **assoluto**. - Se il percorso indicato nel comando `find` è **relativo** il backup verrà eseguito in **relativo**. - -### Aggiungere a un backup - -```bash -[files command |] cpio {-o| --create} -A [-options] [device} -``` - -Esempio: - -```bash -$ find /etc/shadow | cpio -o -AF SystemFiles.A.cpio -``` - -L'aggiunta di file è possibile solo su supporti ad accesso diretto. - -| Opzione | Descrizione | -| ------- | ---------------------------------------------- | -| `-A` | Aggiunge uno o più file a un backup su disco. | -| `-F` | Indica il backup da modificare. | - -### Compressione di un backup - -* Salva **poi** comprimi - -```bash -$ find /etc | cpio –o > etc.A.cpio -$ gzip /backups/etc.A.cpio -$ ls /backups/etc.A.cpio* -/backups/etc.A.cpio.gz -``` - -* Salva **e** comprimi - -```bash -$ find /etc | cpio –o | gzip > /backups/etc.A.cpio.gz -``` - -Non c'è alcuna opzione, a differenza del comando `tar`, per salvare e comprimere allo stesso tempo. -Quindi è fatto in due passaggi: salvataggio e compressione. - -La sintassi del primo metodo è più facile da capire e ricordare, perché viene eseguita in due passaggi. - -Per il primo metodo, il file di backup viene automaticamente rinominato dall'utilità `gzip` che aggiunge `.gz` alla fine del nome del file. Allo stesso modo l'utilità `bzip2` aggiunge automaticamente `.bz2`. - -### Leggere il contenuto di un backup - -Sintassi del comando `cpio` per leggere il contenuto di un backup _cpio_: - -```bash -cpio -t [-options] [ tmp -cpio –iuE tmp -F etc.A.cpio -rm -f tmp -``` - -## Utilità di Compressione - decompressione - -L'utilizzo della compressione al momento di un backup può avere una serie di inconvenienti: - -* Allunga il tempo di backup e il tempo di ripristino. -* Rende impossibile aggiungere file al backup. - -!!! Note "Nota" - È quindi meglio fare un backup e comprimerlo piuttosto che comprimerlo durante il backup. - -### Compressione con `gzip` - -Il comando `gzip` comprime i dati. - -Sintassi del comando `gzip`: - -```bash -gzip [options] [file ...] -``` - -Esempio: - -```bash -$ gzip usr.tar -$ ls -usr.tar.gz -``` - -Il file riceve l'estensione `.gz`. - -Mantiene gli stessi permessi e le stesse date di ultimo accesso e modifica. - -### Compressione con `bunzip2` - -Anche il comando 'bunzip2' comprime i dati. - -Sintassi del comando `bzip2`: - -```bash -bzip2 [options] [file ...] -``` - -Esempio: - -```bash -$ bzip2 usr.cpio -$ ls -usr.cpio.bz2 -``` - -Al nome del file viene assegnata l'estensione `.bz2`. - -La compressione con `bzip2` è migliore della compressione con `gzip` ma ci vuole più tempo per eseguirla. - -### Decompressione con `gunzip` - -Il comando `gunzip` decomprime i dati compressi. - -Sintassi del comando `gunzip`: - -```bash -gunzip [options] [file ...] -``` - -Esempio: - -```bash -$ gunzip usr.tar.gz -$ ls -usr.tar -``` - -Il nome del file viene troncato da `gunzip` e l'estensione `.gz` viene rimossa. - -`gunzip` decomprime anche i file con le seguenti estensioni: - -* `.z` ; -* `-z` ; -* `_z` . - -### Decompressione con `bunzip2` - -Il comando `bunzip2` decomprime i dati compressi. - -Sintassi del comando `bzip2: - -```bash -bzip2 [options] [file ...] -``` - -Esempio: - -```bash -$ bunzip2 usr.cpio.bz2 -$ ls -usr.cpio -``` - -Il nome del file viene troncato da `bunzip2` e l'estensione `.bz2` viene rimossa. - -`bunzip2` decomprime anche il file con le seguenti estensioni: - -* `-bz` ; -* `.tbz2` ; -* `tbz` . diff --git a/docs/books/admin_guide/10-boot.it.md b/docs/books/admin_guide/10-boot.it.md deleted file mode 100644 index 9a76e4acec..0000000000 --- a/docs/books/admin_guide/10-boot.it.md +++ /dev/null @@ -1,419 +0,0 @@ ---- -title: Avvio del sistema -author: Antoine Le Morvan -contributors: Steven Spencer, Franco Colussi -update: 11-10-2021 ---- - -# Avvio del sistema - -In questo capitolo imparerai come si avvia il sistema. - -**** -**Obiettivi** : In questo capitolo, i futuri amministratori Linux apprenderanno: - -:heavy_check_mark: Le diverse fasi del processo di avvio; -:heavy_check_mark: Come Rocky Linux supporta questo avvio tramite Grub2 e systemd; -:heavy_check_mark: Come proteggere Grub2 da un attacco; -:heavy_check_mark: Come gestire i servizi; -:heavy_check_mark: Come accedere ai registri di log con journald. - -:checkered_flag: **utenti** - -**Conoscenza**: :star: :star: -**Complessità**: :star: :star: :star: - -**Tempo di lettura**: 20 minuti -**** - -## Il processo di avvio - -È importante capire il processo di avvio di Linux per poter risolvere i problemi che potrebbero verificarsi. - -Il processo di avvio include: - -### L'avvio del BIOS - -Il **BIOS** (Basic Input/Output System) esegue il **POST** (power on self test) per rilevare, testare e inizializzare i componenti hardware del sistema. - -Quindi carica il **MBR** (Master Boot Record). - -### Il Master boot record (MBR) - -Il Master Boot Record sono i primi 512 byte del disco di avvio. Il MBR trova il dispositivo di avvio e carica il bootloader **GRUB2** in memoria passando il controllo ad esso. - -I successivi 64 byte contengono la tabella delle partizioni del disco. - -### Il bootloader Grub2 - -Il bootloader predefinito per la distribuzione Rocky 8 è **GRUB2** (GRand Unified Bootloader). GRUB2 sostituisce il vecchio. GRUB bootloader (chiamato anche GRUB legacy). - -Il file di configurazione di GRUB2 si trova in `/boot/grub2/grub.cfg` ma questo file non dovrebbe mai essere modificato direttamente. - -Le impostazioni di configurazione del menu GRUB2 si trovano in `/etc/default/grub` e sono usate per generare il file `grub.cfg`. - -```bash -# cat /etc/default/grub -GRUB_TIMEOUT=5 -GRUB_DEFAULT=saved -GRUB_DISABLE_SUBMENU=true -GRUB_TERMINAL_OUTPUT="console" -GRUB_CMDLINE_LINUX="rd.lvm.lv=rhel/swap crashkernel=auto rd.lvm.lv=rhel/root rhgb quiet net.ifnames=0" -GRUB_DISABLE_RECOVERY="true" -``` - -Se vengono apportate modifiche a uno o più di questi parametri, deve essere eseguito il comando `grub2-mkconfig` per rigenerare il file `/boot/grub2/grub.cfg`. - -```bash -[root] # grub2-mkconfig –o /boot/grub2/grub.cfg -``` - -* GRUB2 cerca l'immagine del kernel compresso (il file `vmlinuz`) nella cartella `/boot`. -* GRUB2 carica l'immagine del kernel in memoria ed estrae il contenuto del file immagine `initramfs` in una cartella temporanea in memoria usando il file system `tmpfs`. - -### Il kernel - -Il kernel inizia il processo `systemd` con PID 1. - -```bash -root 1 0 0 02:10 ? 00:00:02 /usr/lib/systemd/systemd --switched-root --system --deserialize 23 -``` - -### `systemd` - -Systemd è il genitore di tutti i processi di sistema. Legge il target del link `/etc/systemd/system/default.target` (es. `/usr/lib/systemd/system/multi-user.target`) per determinare l'obiettivo predefinito del sistema. Il file definisce i servizi da avviare. - -Systemd posiziona quindi il sistema nello stato definito dall'obiettivo eseguendo le seguenti attività di inizializzazione: - -1. Imposta il nome della macchina -2. Inizializza la rete -3. Inizializza SELinux -4. Mostra il banner di benvenuto -5. Inizializza l'hardware in base agli argomenti forniti al kernel al momento dell'avvio -6. Monta i file system, inclusi i file system virtuali come /proc -7. Pulisce le directory in /var -8. Avvia la memoria virtuale (swap) - -## Protezione del bootloader GRUB2 - -Perché proteggere il bootloader con una password? - -1. Prevenire l'accesso in *Single user mode* - Se un utente malintenzionato può avviare in single user mode, diventa l'utente root. -2. Impedire l'accesso alla console di GRUB - Se un utente malintenzionato riesce a utilizzare la console Grub, può modificare la sua configurazione o raccogliere informazioni sul sistema utilizzando il comando `cat`. -3. Impedire l'accesso ai sistemi operativi insicuri. Se c'è un doppio avvio sul sistema, un utente malintenzionato può selezionare un sistema operativo come DOS che all'avvio ignora i controlli di accesso e le autorizzazioni dei file. - -Per proteggere con password il bootloader GRUB2: - -* Rimuovere `-unrestricted` dalla dichiarazione principale `CLASS=` nel file `/etc/grub.d/10_linux`. - -* Se un utente non è stato ancora configurato, utilizzare il comando `grub2-setpassword` per fornire una password per l'utente root: - -```bash -# grub2-setpassword -``` - -Un file `/boot/grub2/user.cfg` sarà creato se non era già presente. Contiene la password hashed. di GRUB2. - -!!! Note "Nota" - Questo comando supporta solo le configurazioni con un singolo utente root. - -```bash -[root]# cat /boot/grub2/user.cfg -GRUB2_PASSWORD=grub.pbkdf2.sha512.10000.CC6F56....A21 -``` - -* Ricreare il file di configurazione con il comando `grub2-mkconfig`: - -```bash -[root]# grub2-mkconfig -o /boot/grub2/grub.cfg -Generating grub configuration file ... -Found linux image: /boot/vmlinuz-3.10.0-327.el7.x86_64 -Found initrd image: /boot/initramfs-3.10.0-327.el7.x86_64.img -Found linux image: /boot/vmlinuz-0-rescue-f9725b0c842348ce9e0bc81968cf7181 -Found initrd image: /boot/initramfs-0-rescue-f9725b0c842348ce9e0bc81968cf7181.img -done -``` - -* Riavviare il sistema e controllare. - -Tutte le voci definite nel menu GRUB richiederanno ora un utente e una password da inserire a ciascun avvio. Il sistema non avvierà un kernel senza l'intervento diretto dell'utente dalla console. - -* Quando viene richiesto l'utente, inserire `root`; -* Quando viene richiesta una password, inserire la password fornita al comando `grub2-setpassword`. - -Per proteggere solo la modifica delle voci del menu GRUB e l'accesso alla console, l'esecuzione del comando `grub2-setpassword` è sufficiente. Ci possono però essere casi in cui ci sono buone ragioni per non farlo. Questo potrebbe essere particolarmente vero in un data center remoto in cui l'inserimento di una password ogni volta che viene riavviato un server è difficile o impossibile da fare. - -## Systemd - -*Systemd* è un gestore di servizi per i sistemi operativi Linux. - -È sviluppato per: - -* rimanere compatibile con gli script di inizializzazione del vecchio SysV, -* fornire molte funzionalità, come l'avvio parallelo dei servizi di sistema all'avvio del sistema, l'attivazione su richiesta dei demoni, il supporto per le istantanee o la gestione delle dipendenze tra i servizi. - -!!! Note "Nota" - Systemd è il sistema di inizializzazione predefinito da RedHat/CentOS 7. - -Systemd introduce il concetto di unità systemd. - -| Tipo | Estensione del file | Osservazioni | -|-------------------------|----------------------------|-----------------------------------------------------| -| Unità di servizio | `.service` | Servizio di sistema | -| Unità di destinazione | `.target` | Un gruppo di unità systemd | -| Mount unit | `.automount` | Un punto di montaggio automatico per il file system | - -!!! Note "Nota" - Ci sono molti tipi di unità: Device unit, Mount unit, Path unit, Scope unit, Slice unit, Snapshot unit, Socket unit, Swap unit, Timer unit. - -* Systemd supporta le istantanee dello stato del sistema e il ripristino. - -* Mount points possono essere configurati come target di systemd. - -* All'avvio, systemd crea socket di ascolto per tutti i servizi di sistema che supportano questo tipo di attivazione e passa questi socket ai relativi servizi non appena vengono avviati. Ciò consente di riavviare un servizio senza perdere un singolo messaggio inviato dalla rete durante la sua indisponibilità. Il socket corrispondente rimane accessibile e tutti i messaggi vengono accodati. - -* I servizi di sistema che utilizzano D-BUS per le comunicazioni tra processi possono essere avviati su richiesta la prima volta che vengono utilizzati da un client. - -* Systemd arresta o riavvia solo i servizi in esecuzione. Le versioni precedenti (prima di RHEL7) tentavano di arrestare direttamente i servizi senza controllarne lo stato corrente. - -* I servizi di sistema non ereditano alcun contesto (come le variabili di ambiente HOME e PATH). Ogni servizio opera nel proprio contesto di esecuzione. - -Tutte le operazioni delle unità di servizio sono soggette a un timeout predefinito di 5 minuti per evitare che un servizio malfunzionante blocchi il sistema. - -### Gestione dei servizi di sistema - -Le unità di servizio terminano con l'estensione di file `.service` e hanno uno scopo simile a quello degli script di init. Il comando `systemctl` viene utilizzato per `visualizzare`, `avviare`, `fermare`, `riavviare` un servizio di sistema: - -| systemctl | Descrizione | -|-------------------------------------------|---------------------------------------------| -| systemctl start _name_.service | Avvia un servizio | -| systemctl stop _name_.service | Arresta un servizio | -| systemctl restart _name_.service | Riavvia un servizio | -| systemctl reload _name_.service | Ricarica una configurazione | -| systemctl status _name_.service | Controlla se un servizio è in esecuzione | -| systemctl try-restart _name_.service | Riavvia un servizio solo se è in esecuzione | -| systemctl list-units --type service --all | Visualizza lo stato di tutti i servizi | - -Il comando `systemctl` viene utilizzato anche per `abilitare` o `disabilitare` un servizio di sistema e la visualizzazione dei servizi associati: - -| systemctl | Descrizione | -|------------------------------------------|--------------------------------------------------------------| -| systemctl enable _name_.service | Attivare un servizio | -| systemctl disable _name_.service | Disabilitare un servizio | -| systemctl list-unit-files --type service | Elenca tutti i servizi e i controlli se sono in esecuzione | -| systemctl list-dependencies --after | Elenca i servizi che si avviano prima dell'unità specificata | -| systemctl list-dependencies --before | Elenca i servizi che si avviano dopo l'unità specificata | - -Esempi: - -```bash -systemctl stop nfs-server.service -# or -systemctl stop nfs-server -``` - -Per elencare tutte le unità attualmente caricate: - -```bash -systemctl list-units --type service -``` - -Per elencare tutte le unità e per verificare se sono attivate: - -```bash -systemctl list-unit-files --type service -``` - -```bash -systemctl enable httpd.service -systemctl disable bluetooth.service -``` - -### Esempio di un file .service per il servizio postfix - -```bash -postfix.service Unit File -What follows is the content of the /usr/lib/systemd/system/postfix.service unit file as currently provided by the postfix package: - -[Unit] -Description=Postfix Mail Transport Agent -After=syslog.target network.target -Conflicts=sendmail.service exim.service - -[Service] -Type=forking -PIDFile=/var/spool/postfix/pid/master.pid -EnvironmentFile=-/etc/sysconfig/network -ExecStartPre=-/usr/libexec/postfix/aliasesdb -ExecStartPre=-/usr/libexec/postfix/chroot-update -ExecStart=/usr/sbin/postfix start -ExecReload=/usr/sbin/postfix reload -ExecStop=/usr/sbin/postfix stop - -[Install] -WantedBy=multi-user.target -``` - -### Utilizzo degli obiettivi di sistema - -Su Rocky8/RHEL8, il concetto di runlevel è stato sostituito dagli obiettivi systemd. - -I sistemi di destinazione sono rappresentati da unità di destinazione. Le unità di destinazione terminano con l'estenzione `.target` e il loro unico scopo è di raggruppare altre unità systemd in una catena di dipendenze. - -Ad esempio, l'unità `graphical.target`, che viene utilizzata per avviare una sessione grafica, inizializza i servizi di sistema come il **GNOME display manager** (`gdm.service`) o l'**accounts service** (`accounts-daemon.service`) e attiva anche l'unità `multi-user.target`. - -Allo stesso modo, l'unità `multi-user.target` inizializza altri servizi di sistema essenziali, come **NetworkManager** (`NetworkManager.service`) o **D-Bus** (`dbus.service`) e attiva un'altra unità di destinazione denominata `basic.target`. - -| Unità di destinazione. | Descrizione | -|------------------------|---------------------------------------------------------| -| poweroff.target | Chiude il sistema e lo spegne | -| rescue.target | Attiva una shell di salvataggio | -| multi-user.target | Attiva un sistema multiutente senza interfaccia grafica | -| graphical.target | Attiva un sistema multiutente con interfaccia grafica | -| reboot.target | Spegne e riavvia il sistema | - -#### La destinazione predefinita - -Per determinare quale obiettivo viene utilizzato per impostazione predefinita: - -```bash -systemctl get-default -``` - -Questo comando cerca l'obiettivo del collegamento simbolico situato in `/etc/systemd/system/default.target` e visualizza il risultato. - -```bash -$ systemctl get-default -graphical.target -``` - -Il comando `systemctl` può anche fornire un elenco di obiettivi disponibili: - -```bash -systemctl list-units --type target -UNIT LOAD ACTIVE SUB DESCRIPTION -basic.target loaded active active Basic System -bluetooth.target loaded active active Bluetooth -cryptsetup.target loaded active active Encrypted Volumes -getty.target loaded active active Login Prompts -graphical.target loaded active active Graphical Interface -local-fs-pre.target loaded active active Local File Systems (Pre) -local-fs.target loaded active active Local File Systems -multi-user.target loaded active active Multi-User System -network-online.target loaded active active Network is Online -network.target loaded active active Network -nss-user-lookup.target loaded active active User and Group Name Lookups -paths.target loaded active active Paths -remote-fs.target loaded active active Remote File Systems -slices.target loaded active active Slices -sockets.target loaded active active Sockets -sound.target loaded active active Sound Card -swap.target loaded active active Swap -sysinit.target loaded active active System Initialization -timers.target loaded active active Timers -``` - -Per configurare il sistema all'utilizzo di un diverso target predefinito: - -```bash -systemctl set-default name.target -``` - -Esempio: - -```bash -# systemctl set-default multi-user.target -rm '/etc/systemd/system/default.target' -ln -s '/usr/lib/systemd/system/multi-user.target' '/etc/systemd/system/default.target' -``` - -Per passare a un'unità di destinazione diversa nella sessione corrente: - -```bash -systemctl isolate name.target -``` - -La **Modalità di ripristino** fornisce un ambiente semplice per riparare il sistema nei casi in cui è impossibile eseguire un normale processo di avvio. - -In `modalità di ripristino`, il sistema tenta di montare tutti i file system locali e avviare diversi servizi di sistema importanti, ma non abilita un'interfaccia di rete o consente ad altri utenti di connettersi al sistema contemporaneamente. - -Su Rocky 8, la `modalità di ripristino` è equivalente al vecchio `single user mode` e richiede la password di root. - -Per modificare la destinazione corrente immettere `rescue mode` nella sessione corrente: - -```bash -systemctl rescue -``` - -**Modalità di emergenza** fornisce l'ambiente più minimalista possibile e consente di riparare il sistema anche in situazioni in cui il sistema non è in grado di inserire la modalità di salvataggio. Nella modalità di emergenza, il sistema monta il file system root solo per la lettura. Non tenterà di montare qualsiasi altro file system locale, non attiverà alcuna interfaccia di rete e inizializzerà alcuni servizi essenziali. - -Per modificare il target corrente e immettere la modalità di emergenza nella sessione corrente: - -```bash -systemctl emergency -``` - -#### Arresto, sospensione e ibernazione - -Il comando `systemctl` sostituisce alcuni dei comandi di gestione dell'alimentazione utilizzati nelle versioni precedenti: - -|Vecchio comando | Nuovo comando | Descrizione | -|---------------------|--------------------------|-------------------------------------| -| `halt` | `systemctl halt` |Spegne il sistema. | -| `poweroff` | `systemctl poweroff` |Arresta elettricamente il sistema. | -| `reboot` | `systemctl reboot` |Riavvia il sistema. | -| `pm-suspend` | `systemctl suspend` |Sospende il sistema. | -| `pm-hibernate` | `systemctl hibernate` |Iberna il sistema. | -| `pm-suspend-hybrid` | `systemctl hybrid-sleep` |Iberna e sospende il sistema. | - -### Il processo `journald` - -I file di registro possono, oltre a `rsyslogd`, essere gestiti anche dal demone `journald` che è un componente di `systemd`. - -Il demone `journald` cattura i messaggi Syslog, i messaggi di registro del kernel, i messaggi dal disco RAM iniziale e dall'inizio dell'avvio, nonché i messaggi scritti nell'output standard e l'output di errore standard di tutti i servizi, quindi li indicizza e li rende disponibili all'utente. - -Il formato del file di registro nativo, che è un file binario strutturato e indicizzato, migliora le ricerche e consente un funzionamento più rapido, memorizza anche le informazioni dei metadati, come i timestamp o gli ID utente. - -### comando `journalctl` - -Il comando `journalctl` visualizza i file di registro. - -```bash -journalctl -``` - -Il comando elenca tutti i file di registro generati sul sistema. La struttura di questa uscita è simile a quella utilizzata in `/var/log/messages/` ma offre alcuni miglioramenti: - -* la priorità delle voci è segnata visivamente; -* i timestamp sono convertiti nella zona oraria locale del sistema; -* vengono visualizzati tutti i dati registrati, inclusi i registri rotativi; -* l'inizio di un avvio è contrassegnato da una linea speciale. - -#### Uso del display continuo - -Con il display continuo, i messaggi di registro vengono visualizzati in tempo reale. - -```bash -journalctl -f -``` - -Questo comando restituisce un elenco delle dieci linee di registro più recenti. L'utilità continua quindi a funzionare e attende che avvengano nuove modifiche per visualizzarle immediatamente. - -#### Filtrare i Messaggi - -È possibile utilizzare diversi metodi di filtraggio per estrarre informazioni che si adattano a diverse esigenze. I messaggi di registro vengono spesso utilizzati per monitorare il comportamento errato del sistema. Per visualizzare le voci con una priorità selezionata o superiore: - -```bash -journalctl -p priority -``` - -È necessario sostituire la priorità con una delle seguenti parole chiave (o un numero): - -* debug (7), -* info (6), -* notice (5), -* warning (4), -* err (3), -* crit (2), -* alert (1), -* and emerg (0). diff --git a/docs/books/admin_guide/11-tasks.it.md b/docs/books/admin_guide/11-tasks.it.md deleted file mode 100644 index ef3d728b56..0000000000 --- a/docs/books/admin_guide/11-tasks.it.md +++ /dev/null @@ -1,257 +0,0 @@ ---- -title: Gestione dei compiti -author: Antoine Le Morvan -contributors: Steven Spencer, Franco Colussi -update: 11-10-2021 ---- - -# Gestione dei compiti - -In questo capitolo imparerai come gestire le attività programmate. - ---- - -**Obiettivi** : In questo capitolo, futuri amministratori Linux impareranno come: - -:heavy_check_mark: Linux si occupa della pianificazione dei compiti; -:heavy_check_mark: limitare l'uso di **`cron`** a determinati utenti; -:heavy_check_mark: pianificare le attività. - -:checkered_flag: **crontab**, **crond**, **pianificazione**, **linux** - -**Conoscenza**: :star: :star: -**Complessità**: :star: :star: - -**Tempo di lettura**: 15 minuti - ---- - -## Generalità - -La pianificazione delle attività è gestita con l'utilità `cron`. Essa permette l'esecuzione periodica dei compiti. - -È riservata all'amministratore per le attività di sistema ma può essere utilizzata da utenti normali per attività o script a cui hanno accesso. Per accedere all'utilità `cron`, usiamo: `crontab`. - -Il servizio `cron` è usato per: - -* Operazioni di amministrazione ripetitive; -* Backups; -* Monitoraggio dell'attività del sistema; -* Esecuzione di un programma. - -`crontab` è un'abbreviazione per **cron table**, ma può essere pensato come una tabella di programmazione attività. - -!!! Warning "Avvertimento" - Per impostare una pianificazione, il sistema deve avere l'ora locale impostata correttamente. - -## Come funziona il servizio - -Il servizio di `cron` è gestito da un demone `crond` presente in memoria. - -Per verificare il suo stato: - -```bash -[root] # systemctl status crond -``` - -!!! Tip "Suggerimento" - Se il demone `crond` non è in esecuzione, dovrai inizializzarlo manualmente e/o automaticamente all'avvio. Quindi, anche se sono programmati dei compiti, questi non saranno eseguiti fino all'avvio dello stesso. - -Inizializzazione manuale del demone `crond`: - -```bash -[root]# systemctl {status|start|restart|stop} crond -``` - -Initializzazione del demone `crond` all'avvio del sistema: - -```bash -[root]# systemctl enable crond -``` - -## Sicurezza - -Per implementare una pianificazione, un utente deve disporre dell'autorizzazione all'utilizzo del servizio `cron`. - -Questa autorizzazione varia in base alle informazioni contenute nei file seguenti: - -* `/etc/cron.allow` -* `/etc/cron.deny` - -!!! Warning "Avvertimento" - Se nessuno dei due file è presente, tutti gli utenti possono usare `cron`. - -### I files `cron.allow` and `cron.deny` - -File `/etc/cron.allow` - -Solo gli utenti contenuti in questo file sono autorizzati a utilizzare `cron`. - -Se esiste ed è vuoto, nessun utente può usare `cron`. - -!!! Warning "Avvertimento" - Se è presente `cron.allow`,`cron.deny` è **ignorato**. - -File `/etc/cron.deny` - -Gli utenti di questo file non sono autorizzati a utilizzare `cron`. - -Se è vuoto, tutti gli utenti possono usare `cron`. - -Per impostazione predefinita, `/etc/cron.deny` esiste ed è vuoto e `/etc/cron.allow` non esiste. - -### Consentire ad un utente - -Solo **user1** sarà in grado di utilizzare`cron`. - -```bash -[root]# vi /etc/cron.allow -user1 -``` - -### Proibire ad un utente - -Solo **user2** non sarà in grado di usare `cron`. - -```bash -[root]# vi /etc/cron.deny -user2 -``` - -`cron.allow` non deve essere presente. - -## Pianificazione delle attività - -Quando un utente pianifica un'attività, viene creato un file con il suo nome in `/var/spool/cron/`. - -Questo file contiene tutte le informazioni che il `crond` deve sapere riguardo a tutte le attività create da questo utente, i comandi o i programmi da eseguire e quando eseguirli (ora, minuto, giorno ...). - -![Cron tree](images/tasks-001.png) - -### Il comando `crontab` - -Il comando `crontab` viene utilizzato per gestire il file di pianificazione. - -```bash -crontab [-u user] [-e | -l | -r] -``` - -Esempio: - -```bash -[root]# crontab -u user1 -e -``` - -| Opzione | Descrizione | -| ------- | --------------------------------------------------------------------- | -| `-e` | Modifica il file di pianificazione con VI | -| `-l` | Visualizza il contenuto del file di pianificazione | -| `-u` | Nome dell'utente il cui file di pianificazione deve essere manipolato | -| `-r` | Elimina il file di pianificazione | - -!!! Warning "Avvertimento" - `crontab` Senza opzioni elimina il vecchio file di pianificazione e attende che l'utente inserisca nuove linee. Devi premere ctrl + d per uscire da questa modalità di modifica. - Solo `root` può utilizzare l'opzione `-u utente` per gestire il file di pianificazione di un altro utente. - L'esempio sopra consente a root di pianificare un'attività per l'utente1. - -### Usi di `crontab` - -Gli usi di `crontab` sono molti e includono: - -* Modifiche ai file `crontab` presi in considerazione immediatamente; -* Nessun bisogno di riavviare. - -D'altra parte, devono essere presi in considerazione i seguenti punti: - -* Il programma deve essere autonomo; -* Fornire reindirizzamenti (stdin, stdout, stderr); -* Non è rilevante per eseguire comandi che utilizzano richieste di ingresso/uscita su un terminale. - -!!! Note "Nota" - È importante capire che lo scopo della pianificazione è quello di eseguire automaticamente attività, senza la necessità di un intervento esterno. - -## Il file `crontab` - -Il file `crontab` è strutturato in base alle seguenti regole. - -* Ogni riga di questo file corrisponde a una pianificazione; -* Ogni linea ha sei campi, 5 per il tempo e 1 per l'ordine; -* Ogni campo è separato da uno spazio o da una tabulazione; -* Ogni linea termina con un ritorno a capo; -* Un `#` all'inizio della linea la commenta. - -```bash -[root]# crontab –e -10 4 1 * * /root/scripts/backup.sh -1 2 3 4 5 6 -``` - -| Campo | Descrizione | Dettaglio | -| ----- | ------------------------- | ------------------------- | -| 1 | Minuto(i) | Da 0 a 59 | -| 2 | Ora(e) | Da 0 a 23 | -| 3 | Giorno(i) del mese | Da 1 a 31 | -| 4 | Mese dell'anno | Da 1 a 12 | -| 5 | Giorno(i) della settimana | Da 0 a 7 (0=7=Domenica) | -| 6 | Compito da eseguire | Comando completo o script | - -!!! Warning "Avvertimento" - Le attività da eseguire devono utilizzare percorsi assoluti e, se possibile, utilizzare reindirizzamenti. - -Al fine di semplificare la notazione per la definizione del tempo, è consigliabile utilizzare simboli speciali. - -| Wildcards | Descrizione | -| --------- | ---------------------------------- | -| `*` | Tutti i possibili valori del campo | -| `-` | Indica una gamma di valori | -| `,` | Indica un elenco di valori | -| `/` | Definisce un passo | - -Esempi: - -Script eseguito il 15 Aprile alle 10:25am: - -```bash -25 10 15 04 * /root/scripts/script > /log/… -``` - -Esegui alle 11am e quindi alle 4pm di ogni giorno: - -```bash -00 11,16 * * * /root/scripts/script > /log/… -``` - -Esegui ogni ora dalle 11am alle 4pm di ogni giorno: - -```bash -00 11-16 * * * /root/scripts/script > /log/… -``` - -Esegui ogni 10 minuti durante l'orario di lavoro: - -```bash -*/10 8-17 * * 1-5 /root/scripts/script > /log/… -``` - -Per l'utente root, `crontab` ha anche alcune impostazioni speciali del tempo: - -| Impostazioni | Descrizione | -| ------------ | ----------------------------------------------------------------- | -| @reboot | Eseguire il comando al riavvio del sistema | -| @hourly | Esegui il comando ogni ora | -| @daily | Esegui giornalmente dopo la mezzanotte | -| @weekly | Esegui il comando ogni domenica dopo la mezzanotte | -| @monthly | Esegui il comando il primo giorno del mese subito dopo mezzanotte | -| @annually | Esegui il 1 gennaio subito dopo mezzanotte | - -### Processo di esecuzione dell'attività - -Un utente, rockstar, vuole modificare il suo file `crontab`: - -1) `crond` controlla se è permesso (`/etc/cron.allow` e `/etc/cron.deny`). -2) Se lo è, accede al file `crontab` (`/var/spool/cron/rockstar`). - -Ogni minuto `cron` legge il file di pianificazione. - -3) Esegue le attività pianificate. -4) Riporta sistematicamente in un file di registro (`/var/log/cron`). diff --git a/docs/books/admin_guide/12-network.it.md b/docs/books/admin_guide/12-network.it.md deleted file mode 100644 index 1b7e6f13a0..0000000000 --- a/docs/books/admin_guide/12-network.it.md +++ /dev/null @@ -1,740 +0,0 @@ ---- -title: Implementazione della Rete -author: Antoine Le Morvan -contributors: Steven Spencer, Franco Colussi -update: 11-15-2021 ---- - -# Implementazione della Rete - -In questo capitolo imparerai come gestire e lavorare con la rete. - -**** - -**Obiettivi** : In questo capitolo imparerai come: - -:heavy_check_mark: Configurare una workstation per usare DHCP; -:heavy_check_mark: Configurare una workstation per utilizzare una configurazione statica; -:heavy_check_mark: Configura una workstation per utilizzare un gateway; -:heavy_check_mark: Configurare una workstation per utilizzare i server DNS; -:heavy_check_mark: Risolvere i problemi relativi alla rete di una workstation. - -:checkered_flag: **rete**, **linux**, **ip** - -**Knowledge**: :star: :star: -**Complexity**: :star: :star: - -**Tempo di lettura**: 30 minuti - -**** - -## Generalità - -Per illustrare questo capitolo, useremo la seguente architettura. - -![Illustration of our network architecture](images/network-001.png) - -Ci consentirà di prendere in considerazione: - -* l'integrazione in una LAN (local area network); -* la configurazione di un gateway per raggiungere un server remoto; -* la configurazione di un server DNS e l'implementazione della risoluzione dei nomi. - -I parametri minimi da definire per la macchina sono: - -* il nome della macchina; -* l'indirizzo IP; -* la subnet mask. - -Esempio: - -* `pc-rocky`; -* `192.168.1.10`; -* `255.255.255.0`. - -La notazione chiamata CIDR è sempre più frequente: 192.168.1.10/24 - -Gli indirizzi IP vengono utilizzati per il corretto routing dei messaggi (pacchetti). Sono divisi in due parti: - -* la parte fissa, identifica la rete; -* l'identificatore dell'host nella rete. - -La subnet mask è un insieme di **4 byte** destinato a isolare: - -* l'indirizzo di rete (**NetID** o **SubnetID**) eseguendo un AND logico bit per bit tra l'indirizzo IP e la maschera; -* l'indirizzo dell'host. (**HostID**) eseguendo un AND logico bit per bit tra l'indirizzo IP e il complemento della maschera. - - Ci sono anche indirizzi specifici all'interno di una rete, che devono essere identificati. Il primo indirizzo di un intervallo e l'ultimo hanno un ruolo particolare: - -* Il primo indirizzo di un intervallo è l'**indirizzo di rete**. Viene utilizzato per identificare le reti e per instradare le informazioni da una rete all'altra. - -* L'ultimo indirizzo di un intervallo è l'**indirizzo di trasmissione**. Viene utilizzato per trasmettere informazioni a tutte le macchine sulla rete. - -### Indirizzo MAC / Indirizzo IP - -L'**indirizzo MAC** è un identificatore fisico scritto in fabbrica sul dispositivo. Questo a volte viene definito l'indirizzo hardware. Consiste di 6 byte spesso espressi in forma esadecimale (per esempio 5E:FF:56:A2:AF:15). -È composto da: 3 byte dell'identificatore del produttore e 3 byte del numero di serie. - -!!! Warning "Avvertimento" - Quest'ultima affermazione è al giorno d'oggi un po' meno vera con la virtualizzazione. Ci sono anche soluzioni software per cambiare l'indirizzo MAC. - -Un indirizzo Internet Protocol (**IP**) è un numero di identificazione permanente o temporaneo assegnato a ciascun dispositivo collegato a una rete di computer che utilizza l'Internet Protocol. -Una parte definisce l'indirizzo di rete (NetID o SubnetID a seconda dei casi), l'altra parte definisce l'indirizzo dell'host nella rete (HostID). La dimensione relativa di ciascuna parte varia in base alla (sub)mask della rete. - -Un indirizzo IPv4 definisce un indirizzo su 4 byte. Per il numero di indirizzi disponibili che è vicino alla saturazione è stato creato un nuovo standard, l'IPv6 definito su 16 byte. - -IPv6 è spesso rappresentato da 8 gruppi di 2 byte separati da un due punti. Gli zeri insignificanti possono essere omessi, uno o più gruppi di 4 zeri consecutivi possono essere sostituiti da un doppio due punti. - -Le maschere di sottorete hanno da 0 a 128 bit. (Per esempio 21ac:0000:0000:0611:21e0:00ba:321b:54da/64 o 21ac::611:21e0:ba:321b:54da/64) - -In un indirizzo web o URL (Uniform Resource Locator), un indirizzo IP può essere seguito da un due punti e dall'indirizzo della porta (che indica l'applicazione a cui i dati sono destinati). Inoltre per evitare confusione in un URL, l'indirizzo IPv6 è scritto in parentesi quadre [ ], due punti, indirizzo della porta. - -Gli indirizzi IP e MAC devono essere univoci su una rete! - -### Dominio DNS - -Le macchine client possono far parte di un dominio DNS (**Domain Name System**, ad esempio `mydomain.lan`). - -Il nome completo del computer (**FQDN**) diventa `pc-rocky.mydomain.lan`. - -Un insieme di computer può essere raggruppato in un set logico, che risolve i nomi, chiamato dominio DNS. Un dominio DNS non è, ovviamente, limitato a una singola rete fisica. - -Affinché un computer faccia parte di un dominio DNS, è necessario fornire un suffisso DNS (qui `mydomain.lan`) e un server da poter interrogare. - -### Promemoria del modello OSI - -!!! Note " Aiuto alla memoria " - Per ricordare l'ordine dei livelli del modello OSI, ricordare la seguente frase: __Please Do Not Touch Steven's Pet Alligator__. - -| Livello | Protocolli | -|---------------------------|----------------------------------------------| -| 7 - Applicazione | POP, IMAP, SMTP, SSH, SNMP, HTTP, FTP, ... | -| 6 - Presentazione | ASCII, MIME, ... | -| 5 - Sessione | TLS, SSL, NetBIOS, ... | -| 4 - Trasporto | TLS, SSL, TCP, UDP, ... | -| 3 - Rete | IPv4, IPv6, ARP, ... | -| 2 - Collegamento dati | Ethernet, WiFi, Token Ring, ... | -| 1 - Collegamento fisici | Cavi, fibre ottiche, onde radio, ... | - -**Livello 1** (Fisico) supporta la trasmissione su un canale di comunicazione (Wifi, fibra ottica, cavo RJ, ecc.). -Unità: il bit. - -**Livello 2** (Data Link) supporta la topologia di rete -(token-ring, star, bus, etc.), divisione dei dati ed errori di trasmissione. -Unità: il frame. - -**Livello 3** (Rete) supporta la trasmissione dati end-to-end (Routing IP = Gateway). -Unità: il pacchetto. - -**Livello 4** (Trasporto) supporta il tipo di servizio (connesso o non connesso) crittografia e controllo del flusso. -Unità: il segmento o il datagramma. - -**Livello 5** (Sessione) supporta la comunicazione tra due computer. - -**Livello 6** (Presentazione) rappresenta l'area indipendente dai dati a livello di applicazione. Essenzialmente questo livello traduce dal formato di rete al formato dell'applicazione, o dal formato dell'applicazione al formato di rete. - -**Layer 7** (Applicazione) rappresenta il contatto con l'utente. -Fornisce i servizi offerti dalla rete: http, dns, ftp, imap, -pop, smtp, etc. - -## La denominazione delle interfacce - -*lo* è l'intefaccia di "**loopback**" che consente ai programmi TCP/IP di comunicare tra loro senza lasciare la macchina locale. Ciò consente di verificare se il modulo di rete **del sistema funziona correttamente** e consente anche il ping del localhost. Tutti i pacchetti che entrano attraverso localhost escono attraverso localhost. I pacchetti ricevuti corrispondono ai pacchetti inviati. - -Il kernel Linux assegna i nomi delle interfacce con un prefisso specifico a seconda del tipo. Ad esempio tradizionalmente, tutte le interfacce **Ethernet**, iniziano con **eth**. Il prefisso è seguito da un numero, il primo è 0 (eth0, eth1, eth2...). Alle interfacce wifi è stato assegnato un prefisso wlan. - -Sulle distribuzioni Linux Rocky 8, systemd nominerà le interfacce seguendo la nuova politica in cui "X" rappresenta un numero: - -* `enoX`: dispositivi on-board -* `ensX`: slot hotplug PCI Express -* `enpXsX`: posizione fisica/geografica del connettore dell'hardware -* ... - -## Uso del comandi `ip` - -Dimentica il vecchio comando `ifconfig`! Pensa `ip`! - -!!! Note "Nota" - Commento per gli amministratori dei vecchi sistemi Linux: - Il comando storico di gestione della rete è `ifconfig`. Questo comando è stato sostituito dal comando `ip`, che è già ben noto agli amministratori di rete. - Il comando `ip` è l'unico comando per gestire **indirizzo IP, ARP, routing, ecc.**. - Il comando `ifconfig` non è più installato per impostazione predefinita in Rocky8. - -È importante iniziare con le buone abitudini ora. - -## Il nome host - -Il comando `hostname` visualizza o imposta il nome host del sistema - -```bash -hostname [-f] [hostname] -``` - -| Opzione | Descrizione | -|----------|-----------------------------------------| -| `-f` | Mostra il FQDN | -| `-i` | Visualizza gli indirizzi IP del sistema | - -!!! Tip "Suggerimento" - Questo comando viene utilizzato da vari programmi di rete per identificare la macchina. - -Per assegnare un nome host, è possibile utilizzare il comando`hostname`, ma le modifiche non verranno mantenute all'avvio successivo. Il comando senza argomenti visualizza il nome host. - -Per impostare il nome host, bisogna modificare il file `/etc/sysconfig/network`: - -```bash -NETWORKING=yes -HOSTNAME=pc-rocky.mondomaine.lan -``` - -Lo script di avvio di RedHat consulta anche il file `/etc/hosts` per risolvere il nome host del sistema. - -All'avvio del sistema, Linux valuta il valore `HOSTNAME` nel file `/etc/sysconfig/network`. - -Utilizza quindi il file `/etc/hosts` per valutare l'indirizzo IP principale del server e il suo nome host. E dedurre il nome di dominio DNS. - -È quindi essenziale compilare questi due file prima di qualsiasi configurazione dei servizi di rete. - -!!! Tip "Suggerimento" - Per sapere se questa configurazione è ben fatta, i comandi `hostname` e `hostname -f` devono restituire i valori previsti. - -## /etc/hosts file - -Il file `/etc/hosts` è una tabella di mapping dei nomi host statici, che segue il seguente formato: - -```bash -@IP [alias] [# comment] -``` - -Esempio di un file `/etc/hosts`: - -```bash -127.0.0.1 localhost localhost.localdomain -::1 localhost localhost.localdomain -192.168.1.10 rockstar.rockylinux.lan rockstar -``` - -Il file `/etc/hosts` viene ancora utilizzato dal sistema, soprattutto al momento dell'avvio quando viene determinato il nome di dominio completo del sistema (FQDN). - -!!! Tip "Suggerimento" - RedHat raccomanda che sia compilata almeno una linea con il nome del sistema. - -Se il servizio **DNS** (**D**domain **N**ame **S**ervice) non è presente, è necessario compilare tutti i nomi nel file hosts per ciascuno dei computer. - -Il file `/etc/hosts` contiene una riga per voce, con l'indirizzo IP, il nome di dominio completo, quindi il nome host (in quest'ordine) e una serie di alias (alias1 alias2 ...). L'alias è opzionale. - -## il file `/etc/nsswitch.conf` - -Il **NSS** (**N**ame **S**ervice **S**witch) consente di sostituire i file di configurazione (ad esempio `/etc/passwd`, `/etc/group`, `/etc/hosts`) con uno o più database centralizzati. - -Il file `/etc/nsswitch.conf` viene utilizzato per configurare i database del servizio dei nomi. - -```bash -passwd: files -shadow: files -group: files - -hosts: files dns -``` - -In questo caso, Linux cercherà prima una corrispondenza del nome host (riga `hosts:`) nel file `/etc/hosts` (valore `files`) prima di interrogare il DNS (valore `dns`)! Questo comportamento può essere variato modificando il file `/etc/nsswitch.conf`. - -Naturalmente, è possibile immaginare di interrogare un LDAP, MySQL o altro server configurando il servizio dei nomi per rispondere alle richieste di sistema per host, utenti, gruppi, ecc. - -La risoluzione del servizio dei nomi può essere testata con il comando `getent` che vedremo più avanti in questo corso. - -## file `/etc/resolv.conf` - -Il file `/etc/resolv.conf` contiene la configurazione della risoluzione dei nomi DNS. - -```bash -#Generated by NetworkManager -domain mondomaine.lan -search mondomaine.lan -nameserver 192.168.1.254 -``` - -!!! Tip "Suggerimento" - Questo file è ormai storia. Non è più compilato direttamente! - -Le nuove generazioni di distribuzioni hanno generalmente integrato il servizio `NetworkManager`. Questo servizio consente di gestire la configurazione in modo più efficiente, sia in modalità grafica che console. - -Consente l'aggiunta di server DNS dal file di configurazione di un'interfaccia di rete. Quindi popola dinamicamente il file `/etc/resolv.conf` che non dovrebbe mai essere modificato direttamente, altrimenti le modifiche alla configurazione andranno perse al successivo avvio del servizio di rete. - -## comando `ip` - -Il comando `ip` del pacchetto `iproute2` consente di configurare un'interfaccia e la relativa tabella di routing. - -Mostra le interfacce : - -```bash -[root]# ip link -``` - -Mostra le informazioni sulle interfacce: - -```bash -[root]# ip addr show -``` - -Mostra le informazioni su una interfaccia : - -```bash -[root]# ip addr show eth0 -``` - -Mostra la tabella ARP: - -```bash -[root]# ip neigh -``` - -Tutti i comandi di gestione della rete storici sono stati raggruppati sotto il comando `ip`, che è ben noto agli amministratori di rete. - -## configurazione DHCP - -Il protocollo **DHCP** (**D**ynamic **H**ost **C**Control **P**rotocol) consente di ottenere una configurazione IP completa tramite la rete. Questa è la modalità di configurazione predefinita di un'interfaccia di rete sotto Rocky Linux, il che spiega perché un sistema connesso alla rete attraverso un router internet può funzionare senza ulteriori configurazioni. - -La configurazione delle interfacce sotto Rocky Linux è contenuta nella cartella `/etc/sysconfig/network-scripts/`. - -Per ogni interfaccia Ethernet, un file `ifcfg-ethX` consente la configurazione dell'interfaccia associata. - -```bash -DEVICE=eth0 -ONBOOT=yes -BOOTPROTO=dhcp -HWADDR=00:0c:29:96:32:e3 -``` - -* Nome dell'interfaccia : (deve essere nel nome del file) - -```bash -DEVICE=eth0 -``` - -* Avvia automaticamente l'interfaccia: - -```bash -ONBOOT=yes -``` - -* Effettuare una richiesta DHCP all'avvio dell'interfaccia: - -```bash -BOOTPROTO=dhcp -``` - -* Specificare l'indirizzo MAC (opzionale ma utile quando ci sono diverse interfacce): - -```bash -HWADDR=00:0c:29:96:32:e3 -``` - -!!! Tip "Suggerimento" - Se NetworkManager è installato, le modifiche vengono prese in considerazione automaticamente. In caso contrario, è necessario riavviare il servizio di rete. - -* Riavviare il servizio di rete: - -```bash -[root]# systemctl restart NetworkManager -``` - -## Configurazione statica - -La configurazione statica richiede almeno: - -```bash -DEVICE=eth0 -ONBOOT=yes -BOOTPROTO=none -IPADDR=192.168.1.10 -NETMASK=255.255.255.0 -``` - -* Qui stiamo sostituendo "dhcp" con "none" che equivale alla configurazione statica: - -```bash -BOOTPROTO=none -``` - -* Indirizzo IP: - -```bash -IPADDR=192.168.1.10 -``` - -* Subnet mask: - -```bash -NETMASK=255.255.255.0 -``` - -* La maschera può essere specificata con un prefisso: - -```bash -PREFIX=24 -``` - -!!! Warning "Avvertimento" - È necessario utilizzare il NETMASK o il PREFISSO - Non entrambi! - -## Routing (Instradamento) - -![Network architecture with a gateway](images/network-002.png) - -```bash -DEVICE=eth0 -ONBOOT=yes -BOOTPROTO=none -HWADDR=00:0c:29:96:32:e3 -IPADDR=192.168.1.10 -NETMASK=255.255.255.0 -GATEWAY=192.168.1.254 -``` - -Il comando `ip route`: - -```bash -[root]# ip route show -192.168.1.0/24 dev eth0 […] src 192.168.1.10 metric 1 -default via 192.168.1.254 dev eth0 proto static -``` - -È una buona idea sapere come leggere una tabella di routing, specialmente in un ambiente con più interfacce di rete. - -* Nell'esempio mostrato, la rete `192.168.1.0/24` è raggiungibile direttamente dal dispositivo `eth0`, quindi c'è una metrica a `1` (non attraversa un router). - -* Tutte le altre reti oltre alla precedente saranno raggiungibili, sempre dal dispositivo `eth0`, ma questa volta i pacchetti saranno indirizzati a un gateway `192.168.1.254`. Il protocollo di routing è un protocollo statico (anche se è possibile aggiungere una route a un indirizzo assegnato dinamicamente in Linux). - -## Risoluzione dei nomi - -Un sistema deve risolvere: - -* FQDN in indirizzi IP - -```bash -www.free.fr = 212.27.48.10 -``` - -* Indirizzi IP in nomi - -```bash -212.27.48.10 = www.free.fr -``` - -* o per ottenere informazioni su un'area: - -```bash -MX de free.fr = 10 mx1.free.fr + 20 mx2.free.fr -``` - -```bash -DEVICE=eth0 -ONBOOT=yes -BOOTPROTO=none -HWADDR=00:0c:29:96:32:e3 -IPADDR=192.168.1.10 -NETMASK=255.255.255.0 -GATEWAY=192.168.1.254 -DNS1=172.16.1.2 -DNS2=172.16.1.3 -DOMAIN=rockylinux.lan -``` - -In questo caso, per raggiungere il DNS, devi passare attraverso il gateway. - -```bash - #Generated by NetworkManager - domain mondomaine.lan - search mondomaine.lan - nameserver 172.16.1.2 - nameserver 172.16.1.3 -``` - -Il file è stato aggiornato da NetworkManager. - -## Risoluzione dei problemi - -Il comando `ping` invia i datagrammi a un'altra macchina e attende una risposta. - -È il comando di base per testare la rete perché controlla la connettività tra l'interfaccia di rete e un'altra. - -Sintassi del comando `ping`: - -```bash -ping [-c numerical] destination -``` - -L'opzione `-c` (conteggio) consente di interrompere il comando dopo il conto alla rovescia in secondi. - -Esempio: - -```bash -[root]# ping –c 4 localhost -``` - -!!! Tip "Suggerimento" - Convalida la connettività da vicino a lontano - -1) Convalidare il livello software TCP/IP - -```bash -[root]# ping localhost -``` - -Il "Pinging" del loop interno non rileva un errore hardware sull'interfaccia di rete. Determina semplicemente se la configurazione del software IP è corretta. - -2) Convalidare la scheda di rete - -```bash -[root]# ping 192.168.1.10 -``` - -Per determinare se la scheda di rete è funzionante, ora dobbiamo eseguire il ping del suo indirizzo IP. La scheda di rete, se il cavo di rete non è collegato, dovrebbe essere in uno stato "down". - -Se il ping non funziona, controllare prima il cavo di rete allo switch di rete e riassemblare l'interfaccia (vedere il comando `if up`), quindi controllare l'interfaccia stessa. - -3) Convalidare la connettività del gateway - -```bash -[root]# ping 192.168.1.254 -``` - -4) Convalidare la connettività di un server remoto - -```bash -[root]# ping 172.16.1.2 -``` - -5) Convalidare il servizio DNS - -```bash -[root]# ping www.free.fr -``` - -### comando `dig` - -Il comando `dig` viene utilizzato per interrogare il server DNS. - -La sintassi del comando `dig`: - -```bash -dig [-t type] [+short] [name] -``` - -Esempi: - -```bash -[root]# dig +short rockylinux.org -76.223.126.88 -[root]# dig -t MX +short rockylinux.org  ✔ -5 alt1.aspmx.l.google.com. -... -``` - -Il comando `dig` viene utilizzato per eseguire query sui server DNS. È molto prolisso per impostazione predefinita, ma questo comportamento può essere modificato con l'opzione `+short`. - -È anche possibile specificare un **tipo di record** DNS da risolvere, ad esempio un **tipo** MX per ottenere informazioni sugli scambiatori di posta per un dominio. - -### comando `getent` - -Il comando 'getent' (get entry) viene utilizzato per ottenere una voce NSSwitch (`hosts` + `dns`) - -Sintassi del comando `getent`: - -```bash -getent hosts name -``` - -Esempio: - -```bash -[root]# getent hosts rockylinux.org - 76.223.126.88 rockylinux.org -``` - -Interrogare solo un server DNS può restituire un risultato errato che non tiene conto del contenuto di un file `hosts`, anche se questo dovrebbe essere raro al giorno d'oggi. - -Per prendere in considerazione anche il file `/etc/hosts`, è necessario interrogare il servizio dei nomi NSSwitch, che si occuperà di qualsiasi risoluzione DNS. - -### comando `ipcalc` - -Il comando `ipcalc` (**calcolo ip**) viene utilizzato per calcolare l'indirizzo di una rete o di trasmissione da un indirizzo IP e una maschera. - -Sintassi del comando `ipcalc`: - -```bash -ipcalc [options] IP -``` - -Esempio: - -```bash -[root]# ipcalc –b 172.16.66.203 255.255.240.0 -BROADCAST=172.16.79.255 -``` - -!!! Tip "Suggerimento" - Questo comando è interessante se seguito da un reindirizzamento per compilare automaticamente i file di configurazione delle interfacce: - - ```bash - [root]# ipcalc –b 172.16.66.203 255.255.240.0 >> /etc/sysconfig/network-scripts/ifcfg-eth0 - ``` - -| Opzione | Descrizione | -|----------|------------------------------------------------| -| `-b` | Visualizza l'indirizzo di trasmissione. | -| `-n` | Visualizza l'indirizzo di rete e la maschera. | - -`ipcalc` è un modo semplice per calcolare le informazioni IP di un host. Le varie opzioni indicano a `ipcalc` quali informazioni devono essere visualizzate sull'uscita standard. È possibile specificare più opzioni. È necessario specificare un indirizzo IP su cui operare. La maggior parte delle operazioni richiede anche una maschera di rete o un prefisso CIDR. - -| Opzione corta | Opzione lunga | Descrizione | -|---------------|---------------|------------------------------------------------------------------------------------------------------| -| `-b` | `--broadcast` | Visualizza l'indirizzo di trasmissione dell'indirizzo IP specifico e la maschera di rete. | -| `-h` | `--hostname` | Visualizza il nome host dell'indirizzo IP fornito tramite DNS. | -| `-n` | `--netmask` | Calcola la maschera di rete per l'indirizzo IP indicato. Presuppone che l'indirizzo IP faccia parte di una rete completa di classe A, B o C. Molte reti non utilizzano maschere di rete predefinite, nel qual caso verrà restituito un valore errato. | -| `-p` | `--prefix` | Indica il prefisso della maschera/indirizzo IP. | -| `-n` | `--network` | Indica l'indirizzo di rete dell'indirizzo IP e della maschera forniti. | -| `-s` | `--silent` | Non visualizza mai alcun messaggio di errore. | - -### comando `ss` - -Il comando `ss` (**statistiche socket**) visualizza le porte in ascolto sulla rete. - -Sintassi del comando `ss`: - -```bash -ss [-tuna] -``` - -Esempio: - -```bash -[root]# ss –tuna -tcp LISTEN 0 128 *:22 *:* -``` - -I comandi `ss` e `netstat` (che segue) saranno molto importanti per il resto della tua vita con Linux. - -Quando si implementano i servizi di rete, è molto comune verificare con uno di questi due comandi che il servizio sia in ascolto sulle porte previste. - -### comando `netstat` - -!!! Warning "Avvertimento" - Il comando `netstat` è ora deprecato e non è più installato per impostazione predefinita su Rocky Linux. Potresti ancora trovare alcune versioni di Linux che lo hanno installato, ma è meglio passare all'uso di "ss" per tutto ciò per cui avresti usato "netstat". - -Il comando `netstat` (**statistiche di rete**) visualizza le porte in ascolto sulla rete. - -Sintassi del comando `netstat`: - -```bash -netstat -tapn -``` - -Esempio: - -```bash -[root]# netstat –tapn -tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 2161/sshd -``` - -### Conflitti di indirizzi IP o MAC - -Una configurazione errata può causare l'utilizzo dello stesso indirizzo IP da parte di più interfacce. Ciò può verificarsi quando una rete dispone di più server DHCP o quando lo stesso indirizzo IP viene assegnato manualmente più volte. - -Quando la rete non funziona correttamente e quando la causa potrebbe essere un conflitto di indirizzi IP, è possibile utilizzare il software `arp-scan` (richiede il repository EPEL): - -```bash -$ dnf install arp-scan -``` - -Esempio: - -```bash -$ arp-scan -I eth0 -l - -172.16.1.104 00:01:02:03:04:05 3COM CORPORATION -172.16.1.107 00:0c:29:1b:eb:97 VMware, Inc. -172.16.1.250 00:26:ab:b1:b7:f6 (Unknown) -172.16.1.252 00:50:56:a9:6a:ed VMWare, Inc. -172.16.1.253 00:50:56:b6:78:ec VMWare, Inc. -172.16.1.253 00:50:56:b6:78:ec VMWare, Inc. (DUP: 2) -172.16.1.253 00:50:56:b6:78:ec VMWare, Inc. (DUP: 3) -172.16.1.253 00:50:56:b6:78:ec VMWare, Inc. (DUP: 4) -172.16.1.232 88:51:fb:5e:fa:b3 (Unknown) (DUP: 2) -``` - -!!! Tip "Suggerimento" - Come mostra l'esempio precedente, è anche possibile avere conflitti di indirizzi MAC! Questi problemi sono causati dalle tecnologie di virtualizzazione e dalla copia delle macchine virtuali. - -## Configurazione a caldo - -Il comando `ip` può aggiungere a caldo un indirizzo IP a un'interfaccia - -```bash -ip addr add @IP dev DEVICE -``` - -Esempio: - -```bash -[root]# ip addr add 192.168.2.10 dev eth1 -``` - -Il comando `ip` consente l'attivazione o la disattivazione di un'interfaccia: - -```bash -ip link set DEVICE up -ip link set DEVICE down -``` - -Esempio: - -```bash -[root]# ip link set eth1 up -[root]# ip link set eth1 down -``` - -Il comando `ip` viene utilizzato per aggiungere una route: - -```bash -ip route add [default|netaddr] via @IP [dev device] -``` - -Esempio: - -```bash -[root]# ip route add default via 192.168.1.254 -[root]# ip route add 192.168.100.0/24 via 192.168.2.254 dev eth1 -``` - -## In sintesi - -I file utilizzati in questo capitolo sono: - -![Synthesis of the files implemented in the network part](images/network-003.png) - -Una configurazione completa dell'interfaccia potrebbe essere questa (file `/etc/sysconfig/network-scripts/ifcfg-eth0`): - -```bash - DEVICE=eth0 - ONBOOT=yes - BOOTPROTO=none - HWADDR=00:0c:29:96:32:e3 - IPADDR=192.168.1.10 - NETMASK=255.255.255.0 - GATEWAY=192.168.1.254 - DNS1=172.16.1.1 - DNS2=172.16.1.2 - DOMAIN=rockylinux.lan -``` - -Il metodo di risoluzione dei problemi dovrebbe andare dal più vicino al più lontano: - -1. ping localhost (test del software) -2. ping indirizzo-IP (test dell'hardware) -3. ping gateway (test di connettività) -4. ping server remoto (test di instradamento) -5. DNS query (dig o ping) - -![Method of troubleshooting or network validation](images/network-004.png) diff --git a/docs/books/admin_guide/13-softwares.it.md b/docs/books/admin_guide/13-softwares.it.md deleted file mode 100644 index 801cbb50d7..0000000000 --- a/docs/books/admin_guide/13-softwares.it.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Gestione del software -author: Antoine Le Morvan -contributors: Steven Spencer, Franco Colussi -update: 11-15-2021 ---- - -# Gestione del software - -## Generalità - -Su un sistema Linux, è possibile installare il software in due modi: - -* Utilizzando un pacchetto di installazione; -* Compilandolo da un file sorgente. - -!!! Note "Nota" - L'installazione dall'origine non è trattata qui. Di norma, è necessario utilizzare il metodo del pacchetto a meno che il software desiderato non sia disponibile tramite il gestore pacchetti. La ragione di ciò è che le dipendenze sono generalmente gestite dal sistema di pacchetti, mentre con il sorgente, è necessario gestire manualmente le dipendenze. - -**Il pacchetto**: si tratta di un singolo file contenente tutti i dati necessari per installare il programma. Può essere eseguito direttamente sul sistema da un repository software. - -**I file sorgente** : Alcuni software non sono forniti in pacchetti pronti per essere installati, ma tramite un archivio contenente i file sorgente. Spetta all'amministratore preparare questi file e compilarli per installare il programma. - -## RPM : Gestione pacchetti RedHat - -**RPM** (RedHat Package Manager) è un sistema di gestione software. È possibile installare, disinstallare, aggiornare o controllare il software contenuto nei pacchetti. - -**RPM** è il formato utilizzato da tutte le distribuzioni basate su RedHat (RockyLinux, Fedora, CentOS, SuSe, Mandriva, ...). Il suo equivalente nel mondo Debian è DPKG (Debian Package). - -Il nome di un pacchetto RPM segue una nomenclatura specifica: - -![Illustration of a package name](images/software-001.png) - -### comando `rpm` - -Il comando rpm consente di installare un pacchetto. - -```bash -rpm [-i][-U] package.rpm [-e] package -``` - -Esempio (per un pacchetto denominato 'package'): - -```bash -[root]# rpm -ivh package.rpm -``` - -| Opzione | Descrizione | -|-------------------|-----------------------------------------------------| -| `-i package.rpm` | Installa il pacchetto. | -| `-U package.rpm` | Aggiorna un pacchetto già installato. | -| `-e package.rpm` | Disinstalla il pacchetto. | -| `-h` | Visualizza una barra di avanzamento. | -| `-v` | Informa sullo stato di avanzamento dell'operazione. | -| `--test` | Esegue il test del comando senza eseguirlo. | - -Il comando `rpm` consente inoltre di interrogare il database dei pacchetti sul sistema aggiungendo l'opzione `-q`. - -È possibile eseguire diversi tipi di ricerche per ottenere informazioni sui pacchetti installati. Il database RPM si trova nella directory `/var/lib/rpm`. - -Esempio: - -```bash -[root]# rpm -qa -``` - -Questo comando esegue una ricerca su tutti i pacchetti installati nel sistema. - -```bash -rpm -q [-a][-i][-l] package [-f] file -``` - -Esempio: - -```bash -[root]# rpm -qil package -[root]# rpm -qf /path/to/file -``` - -| Opzione | Descrizione | -|------------------|------------------------------------------------------------------------------------------------| -| `-a` | Elenca tutti i pacchetti installati nel sistema. | -| `-i __package__` | Visualizza le informazioni sul pacchetto. | -| `-l __package__` | Elenca i file contenuti nel pacchetto. | -| `-f` | Mostra il nome del pacchetto contenente il file specificato. | -| `--last` | L'elenco dei pacchetti è indicato per data di installazione (gli ultimi pacchetti installati vengono visualizzati per primi). | - -!!! Warning "Avvertimento" - Dopo l'opzione `-q`, il nome del pacchetto deve essere esatto. I metacaratteri (caratteri jolly) non sono supportati. - -!!! Tip "Suggerimento" - Tuttavia, è possibile elencare tutti i pacchetti installati e filtrarli con il comando 'grep'. - -Esempio: elencare gli ultimi pacchetti installati: - -```bash -sudo rpm -qa --last | head -NetworkManager-config-server-1.26.0-13.el8.noarch Mon 24 May 2021 02:34:00 PM CEST -iwl2030-firmware-18.168.6.1-101.el8.1.noarch Mon 24 May 2021 02:34:00 PM CEST -iwl2000-firmware-18.168.6.1-101.el8.1.noarch Mon 24 May 2021 02:34:00 PM CEST -iwl135-firmware-18.168.6.1-101.el8.1.noarch Mon 24 May 2021 02:34:00 PM CEST -iwl105-firmware-18.168.6.1-101.el8.1.noarch Mon 24 May 2021 02:34:00 PM CEST -iwl100-firmware-39.31.5.1-101.el8.1.noarch Mon 24 May 2021 02:34:00 PM CEST -iwl1000-firmware-39.31.5.1-101.el8.1.noarch Mon 24 May 2021 02:34:00 PM CEST -alsa-sof-firmware-1.5-2.el8.noarch Mon 24 May 2021 02:34:00 PM CEST -iwl7260-firmware-25.30.13.0-101.el8.1.noarch Mon 24 May 2021 02:33:59 PM CEST -iwl6050-firmware-41.28.5.1-101.el8.1.noarch Mon 24 May 2021 02:33:59 PM CEST -``` - -Esempio: elencare la cronologia di installazione del kernel: - -```bash -sudo rpm -qa --last kernel -kernel-4.18.0-305.el8.x86_64 Tue 25 May 2021 06:04:56 AM CEST -kernel-4.18.0-240.22.1.el8.x86_64 Mon 24 May 2021 02:33:35 PM CEST -``` - -Esempio: elencare tutti i pacchetti installati con un nome specifico utilizzando 'grep': - -```bash -sudo dnf list installed | grep httpd -centos-logos-httpd.noarch 80.5-2.el8 @baseos -httpd.x86_64 2.4.37-30.module_el8.3.0+561+97fdbbcc @appstream -httpd-filesystem.noarch 2.4.37-30.module_el8.3.0+561+97fdbbcc @appstream -httpd-tools.x86_64 2.4.37-30.module_el8.3.0+561+97fdbbcc @appstream -``` - -## DNF : Dandified Yum - -**DNF** (**Dandified Yum**) è un gestore di pacchetti software, successore di **YUM** (**Y**ellow Dog **U**pdater **M**odified). Funziona con pacchetti **RPM** raggruppati in un repository locale o remoto (una directory per l'archiviazione dei pacchetti). Per i comandi più comuni, il suo utilizzo è identico a quello di `yum`. - -Il comando `dnf` permette la gestione dei pacchetti confrontando quelli installati sul sistema con quelli nei repository definiti sul server. Installa inoltre automaticamente le dipendenze, se sono presenti anche nei repository. - -`dnf` è il gestore utilizzato da molte distribuzioni basate su RedHat (RockyLinux, Fedora, CentOS, ...). Il suo equivalente nel mondo Debian è **APT** (**A**dvanced **P**ackaging **T**ool). - -### comando `dnf` - -Il comando dnf consente di installare un pacchetto specificando solo il nome breve. - -```bash -dnf [install][remove][list all][search][info] package -``` - -Esempio: - -```bash -[root]# dnf install tree -``` - -È richiesto solo il nome breve del pacchetto. - -| Opzione | Descrizione | -|----------------------------|-----------------------------------------------| -| `install` | Installa il pacchetto. | -| `remove` | Disinstalla il pacchetto. | -| `list all` | Elenca i pacchetti già nel repository. | -| `search` | Cerca un pacchetto nel repository. | -| `provides */command_name` | Cerca un comando. | -| `info` | Visualizza le informazioni sul pacchetto. | - -Il comando `dnf list` elenca tutti i pacchetti installati sul sistema e presenti nel repository. Accetta diversi parametri: - -| Parametro | Descrizione | -|-------------|----------------------------------------------------------------------------| -| `all` | Elenca i pacchetti installati e quindi quelli disponibili nei repository. | -| `available` | Elenca solo i pacchetti disponibili per l'installazione. | -| `updates` | Elenca i pacchetti che possono essere aggiornati. | -| `obsoletes` | Elenca i pacchetti resi obsoleti dalle versioni superiori disponibili. | -| `recent` | Elenca i pacchetti più recenti aggiunti al repository. | - -Esempio di ricerca del comando `semanage`: - -```bash -[root]# dnf provides */semanage -``` - -### Come funziona DNF - -Il gestore DNF si basa su uno o più file di configurazione per indirizzare i repository contenenti i pacchetti RPM. - -Questi file si trovano in `/etc/yum.repos.d/` e devono terminare con `.repo` per poter essere utilizzati da DNF. - -Esempio: - -```bash -/etc/yum.repos.d/Rocky-BaseOS.repo -``` - -Ogni file `.repo` è costituito da almeno le seguenti informazioni, una direttiva per riga. - -Esempio: - -```bash -[baseos] # Short name of the repository -name=Rocky Linux $releasever - BaseOS # Short name of the repository #Detailed name -mirrorlist=http://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=BaseOS-$releasever # http address of a list or mirror -#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/BaseOS/$basearch/os/ # http address for direct access -gpgcheck=1 # Repository requiring a signature -enabled=1 # Activated =1, or not activated =0 -gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial # GPG public key path -``` - -Per impostazione predefinita, la direttiva `enabled` è assente, il che significa che il repository è abilitato. Per disabilitare un repository, è necessario specificare la direttiva `enabled=0`. - -## Il repository EPEL - -**EPEL** (**E**xtra **P**ackages for **E**nterprise **L**inux) è un repository contenente pacchetti software aggiuntivi per Enterprise Linux, che include RedHat Enterprise Linux (RHEL), RockyLinux, CentOS, ecc. - -### Installazione - -Scarica e installa l'rpm dal repository: - -Se sei dietro un proxy internet: - -```bash -[root]# export http_proxy=http://172.16.1.10:8080 -``` - -Quindi: - -```bash -[root]# dnf install epel-release -```