From aa34692260d5358a03d34a8a243ac39f68d5589b Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:38 -0500 Subject: [PATCH 01/37] New translations 00-toc.md (French) --- docs/books/admin_guide/00-toc.fr.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 docs/books/admin_guide/00-toc.fr.md diff --git a/docs/books/admin_guide/00-toc.fr.md b/docs/books/admin_guide/00-toc.fr.md new file mode 100644 index 0000000000..5ae1c75505 --- /dev/null +++ b/docs/books/admin_guide/00-toc.fr.md @@ -0,0 +1,27 @@ +--- +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. + From c1e4b15171c32eaa88bc179c9ba5b2ce55eaf05f Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:39 -0500 Subject: [PATCH 02/37] New translations 10-boot.md (Chinese Simplified) --- docs/books/admin_guide/10-boot.zh.md | 412 +++++++++++++++++++++++++++ 1 file changed, 412 insertions(+) create mode 100644 docs/books/admin_guide/10-boot.zh.md diff --git a/docs/books/admin_guide/10-boot.zh.md b/docs/books/admin_guide/10-boot.zh.md new file mode 100644 index 0000000000..ca30dd55fb --- /dev/null +++ b/docs/books/admin_guide/10-boot.zh.md @@ -0,0 +1,412 @@ +--- +title: System Startup +--- + +# System Startup + +In this chapter you will learn how the system start. + +**** +**Objectives** : In this chapter, future Linux administrators will learn: + +:heavy_check_mark: The different stages of the booting process; +:heavy_check_mark: How Rocky Linux supports this boot via GRUB2 and systemd; +:heavy_check_mark: How to protect GRUB2 from an attack; +:heavy_check_mark: How to manage the services; +:heavy_check_mark: How to access to the logs from journald. + +:checkered_flag: **users** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: :star: + +**阅读时间**: 20 分钟 +**** + +## The boot process + +It is important to understand the boot process of Linux in order to be able to solve problems that may occur. + +The boot process includes: + +### The BIOS startup + +The **BIOS** (Basic Input/Output System) performs the **POST** (power on self test) to detect, test and initialize the system hardware components. + +It then loads the **MBR** (Master Boot Record). + +### The Master boot record (MBR) + +The Master Boot Record is the first 512 bytes of the boot disk. The MBR discovers the boot device and loads the bootloader **GRUB2** into memory and transfers control to it. + +The next 64 bytes contain the partition table of the disk. + +### The GRUB2 bootloader + +The default bootloader for the Rocky 8 distribution is **GRUB2** (GRand Unified Bootloader). GRUB2 replaces the old GRUB bootloader (also called GRUB legacy). + +The GRUB 2 configuration file is located under `/boot/grub2/grub.cfg` but this file should not be edited directly. + +The GRUB2 menu configuration settings are located under `/etc/default/grub` and are used to generate the `grub.cfg` file. + +``` +# 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" +``` + +If changes are made to one or more of these parameters, the `grub2-mkconfig` command must be run to regenerate the `/boot/grub2/grub.cfg` file. + +``` +[root] # grub2-mkconfig –o /boot/grub2/grub.cfg +``` + +* GRUB2 looks for the compressed kernel image (the `vmlinuz` file) in the `/boot` directory. +* GRUB2 loads the kernel image into memory and extracts the contents of the `initramfs` image file into a temporary folder in memory using the `tmpfs` file system. + +### The kernel + +The kernel starts the `systemd` process with PID 1. +``` +root 1 0 0 02:10 ? 00:00:02 /usr/lib/systemd/systemd --switched-root --system --deserialize 23 +``` + +### `systemd` + +Systemd is the parent of all system processes. It reads the target of the `/etc/systemd/system/default.target` link (e.g. `/usr/lib/systemd/system/multi-user.target`) to determine the default target of the system. The file defines the services to be started. + +Systemd then places the system in the target-defined state by performing the following initialization tasks: + +1. Set the machine name +2. Initialize the network +3. Initialize SELinux +4. Display the welcome banner +5. Initialize the hardware based on the arguments given to the kernel at boot time +6. Mount the file systems, including virtual file systems like /proc +7. Clean up directories in /var +8. Start the virtual memory (swap) + +## Protecting the GRUB2 bootloader + +Why protect the bootloader with a password? + +1. Prevent *Single* user mode access - If an attacker can boot into single user mode, he becomes the root user. +2. Prevent access to GRUB console - If an attacker manages to use GRUB console, he can change its configuration or collect information about the system by using the `cat` command. +3. Prevent access to insecure operating systems. If there is a dual boot on the system, an attacker can select an operating system like DOS at boot time that ignores access controls and file permissions. + +To password protect the GRUB2 bootloader: + +* Remove `-unrestricted` from the main `CLASS=` statement in the `/etc/grub.d/10_linux` file. + +* If a user has not yet been configured, use the `grub2-setpassword` command to provide a password for the root user: + +``` +# grub2-setpassword +``` + +A `/boot/grub2/user.cfg` file will be created if it was not already present. It contains the hashed password of the GRUB2. + +!!! Note This command only supports configurations with a single root user. + +``` +[root]# cat /boot/grub2/user.cfg +GRUB2_PASSWORD=grub.pbkdf2.sha512.10000.CC6F56....A21 +``` + +* Recreate the configuration file with the `grub2-mkconfig` command: + +``` +[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 +``` + +* Restart the server and check. + +All entries defined in the GRUB menu will now require a user and password to be entered at each boot. The system will not boot a kernel without direct user intervention from the console. + +* When the user is requested, enter `root`; +* When a password is requested, enter the password provided at the `grub2-setpassword` command. + +To protect only the editing of GRUB menu entries and access to the console, the execution of the `grub2-setpassword` command is sufficient. There may be cases where you have good reasons for doing only that. This might be particularly true in a remote data center where entering a password each time a server is rebooted is either difficult or impossible to do. + +## Systemd + +*Systemd* is a service manager for the Linux operating systems. + +It is developed to: + +* remain compatible with older SysV initialization scripts, +* provide many features, such as parallel start of system services at system startup, on-demand activation of daemons, support for snapshots, or management of dependencies between services. + +!!! Note Systemd is the default initialization system since RedHat/CentOS 7. + +Systemd introduces the concept of systemd units. + +| Type | File extension | Observation | +| ------------ | -------------- | ---------------------------------------- | +| Service unit | `.service` | System service | +| Target unit | `.target` | A group of systemd units | +| Mount unit | `.automount` | An automatic mount point for file system | + +!!! Note There are many types of units: Device unit, Mount unit, Path unit, Scope unit, Slice unit, Snapshot unit, Socket unit, Swap unit, Timer unit. + +* Systemd supports system state snapshots and restore. + +* Mount points can be configured as systemd targets. + +* At startup, systemd creates listening sockets for all system services that support this type of activation and passes these sockets to these services as soon as they are started. This makes it possible to restart a service without losing a single message sent to it by the network during its unavailability. The corresponding socket remains accessible and all messages are queued. + +* System services that use D-BUS for their inter-process communications can be started on demand the first time they are used by a client. + +* Systemd stops or restarts only running services. Previous versions (before RHEL7) attempted to stop services directly without checking their current status. + +* System services do not inherit any context (like HOME and PATH environment variables). Each service operates in its own execution context. + +All service unit operations are subject to a default timeout of 5 minutes to prevent a malfunctioning service from freezing the system. + +### Managing system services + +Service units end with the `.service` file extension and have a similar purpose to init scripts. The `systemctl` command is used to `display`, `start`, `stop`, `restart` a system service: + +| systemctl | Description | +| ----------------------------------------- | --------------------------------------- | +| systemctl start _name_.service | Start a service | +| systemctl stop _name_.service | Stops a service | +| systemctl restart _name_.service | Restart a service | +| systemctl reload _name_.service | Reload a configuration | +| systemctl status _name_.service | Checks if a service is running | +| systemctl try-restart _name_.service | Restart a service only if it is running | +| systemctl list-units --type service --all | Display the status of all services | + +The `systemctl` command is also used for the `enable` or `disable` of system a service and displaying associated services: + +| systemctl | Description | +| ---------------------------------------- | ------------------------------------------------------- | +| systemctl enable _name_.service | Activate a service | +| systemctl disable _name_.service | Disable a service | +| systemctl list-unit-files --type service | Lists all services and checks if they are running | +| systemctl list-dependencies --after | Lists the services that start before the specified unit | +| systemctl list-dependencies --before | Lists the services that start after the specified unit | + +Examples: + +``` +systemctl stop nfs-server.service +# or +systemctl stop nfs-server +``` + +To list all units currently loaded: + +``` +systemctl list-units --type service +``` + +To list all units to check if they are activated: + +``` +systemctl list-unit-files --type service +``` + +``` +systemctl enable httpd.service +systemctl disable bluetooth.service +``` + +### Example of a .service file for the postfix service + +``` +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 +``` + +### Using system targets + +On Rocky8/RHEL8, the concept of run levels has been replaced by Systemd targets. + +Systemd targets are represented by target units. Target units end with the `.target` file extension and their sole purpose is to group other Systemd units into a chain of dependencies. + +For example, the `graphical.target` unit, which is used to start a graphical session, starts system services such as the **GNOME display manager** (`gdm.service`) or the **accounts service** (`accounts-daemon.service`) and also activates the `multi-user.target` unit. + +Similarly, the `multi-user.target` unit starts other essential system services, such as **NetworkManager** (`NetworkManager.service`) or **D-Bus** (`dbus.service`) and activates another target unit named `basic.target`. + +| Target Units | Description | +| ----------------- | --------------------------------------------------------- | +| poweroff.target | Shuts down the system and turns it off | +| rescue.target | Activates a rescue shell | +| multi-user.target | Activates a multi-user system without graphical interface | +| graphical.target | Activates a multi-user system with graphical interface | +| reboot.target | Shuts down and restarts the system | + +#### The default target + +To determine which target is used by default: + +``` +systemctl get-default +``` + +This command searches for the target of the symbolic link located at `/etc/systemd/system/default.target` and displays the result. + +``` +$ systemctl get-default +graphical.target +``` + +The `systemctl` command can also provide a list of available targets: + +``` +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 +``` + +To configure the system to use a different default target: + +``` +systemctl set-default name.target +``` + +Example: + +``` +# 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' +``` + +To switch to a different target unit in the current session: + +``` +systemctl isolate name.target +``` + +The **Rescue mode** provides a simple environment to repair your system in cases where it is impossible to perform a normal boot process. + +In `rescue mode`, the system attempts to mount all local file systems and start several important system services, but does not enable a network interface or allow other users to connect to the system at the same time. + +On Rocky 8, the `rescue mode` is equivalent to the old `single user mode` and requires the root password. + +To change the current target and enter `rescue mode` in the current session: + +``` +systemctl rescue +``` + +**Emergency mode** provides the most minimalist environment possible and allows the system to be repaired even in situations where the system is unable to enter rescue mode. In the emergency mode, the system mounts the root file system only for reading. It will not attempt to mount any other local file system, will not activate any network interface, and will start some essential services. + +To change the current target and enter emergency mode in the current session: + +``` +systemctl emergency +``` + +#### Shutdown, suspension and hibernation + +The `systemctl` command replaces a number of power management commands used in previous versions: + +| Old command | New command | Description | +| ------------------- | ------------------------ | ----------------------------------- | +| `halt` | `systemctl halt` | Shuts down the system. | +| `poweroff` | `systemctl poweroff` | Turns off the system. | +| `reboot` | `systemctl reboot` | Restarts the system. | +| `pm-suspend` | `systemctl suspend` | Suspends the system. | +| `pm-hibernate` | `systemctl hibernate` | Hibernates the system. | +| `pm-suspend-hybrid` | `systemctl hybrid-sleep` | Hibernates and suspends the system. | + +### The `journald` process + +Log files can, in addition to `rsyslogd`, also be managed by the `journald` daemon which is a component of `systemd`. + +The `journald` daemon captures Syslog messages, kernel log messages, messages from the initial RAM disk and from the start of boot, as well as messages written to the standard output and the standard error output of all services, then indexes them and makes them available to the user. + +The format of the native log file, which is a structured and indexed binary file, improves searches and allows for faster operation, it also stores metadata information, such as timestamps or user IDs. + +### `journalctl` command + +The `journalctl` command displays the log files. + +``` +journalctl +``` + +The command lists all log files generated on the system. The structure of this output is similar to that used in `/var/log/messages/` but it offers some improvements: + +* the priority of entries is marked visually; +* timestamps are converted to the local time zone of your system; +* all logged data is displayed, including rotating logs; +* the beginning of a start is marked with a special line. + +#### Using continuous display + +With continuous display, log messages are displayed in real time. + +``` +journalctl -f +``` + +This command returns a list of the ten most recent log lines. The journalctl utility then continues to run and waits for new changes to occur before displaying them immediately. + +#### Filtering messages + +It is possible to use different filtering methods to extract information that fits different needs. Log messages are often used to track erroneous behavior on the system. To view entries with a selected or higher priority: + +``` +journalctl -p priority +``` + +You must replace priority with one of the following keywords (or a number): + +* debug (7), +* info (6), +* notice (5), +* warning (4), +* err (3), +* crit (2), +* alert (1), +* and emerg (0). From f2e087bb9af275490bd4a61d829ea1efeb3bdd67 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:40 -0500 Subject: [PATCH 03/37] New translations 08-process.md (Italian) --- docs/books/admin_guide/08-process.it.md | 378 ++++++++++++++++++++++++ 1 file changed, 378 insertions(+) create mode 100644 docs/books/admin_guide/08-process.it.md diff --git a/docs/books/admin_guide/08-process.it.md b/docs/books/admin_guide/08-process.it.md new file mode 100644 index 0000000000..2bcec414a9 --- /dev/null +++ b/docs/books/admin_guide/08-process.it.md @@ -0,0 +1,378 @@ +--- +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. +``` +ps [-e] [-f] [-u login] +``` + +Esempio: +``` +# 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: + +``` +# 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: + +``` +# 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. + +``` +kill [-signal] PID +``` + +Esempio: +``` +$ 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: +``` +$ man 7 signal +``` + +### comando `nohup` + +`nohup` consente il lancio di un processo indipendentemente da una connessione. + +``` +nohup command +``` + +Esempio: +``` +$ 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: +``` +$ 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: + +``` +$ 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: + +``` +[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. + +Esempio: +``` +$ 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à. + +``` +nice priority command +``` + +Esempio: +``` +$ 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. + +``` +renice priority [-g GID] [-p PID] [-u UID] +``` + +Esempio: +``` +$ 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: +``` +$ pidof sleep | xargs renice 20 +``` + +### comando `top` + +Il comando `top` visualizza i processi e il loro consumo di risorse. + +``` +$ 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. + +``` +pgrep process +pkill [-signal] process +``` + +Esempi: + +* Ottenere il numero di processo di `sshd`: + +``` +$ pgrep -u root sshd +``` + +* Termina tutti i processi `tomcat`: + +``` +$ pkill tomcat +``` From 777308abdc9814524c14a803899f18478f9fcddd Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:40 -0500 Subject: [PATCH 04/37] New translations 08-process.md (Chinese Simplified) --- docs/books/admin_guide/08-process.zh.md | 374 ++++++++++++++++++++++++ 1 file changed, 374 insertions(+) create mode 100644 docs/books/admin_guide/08-process.zh.md diff --git a/docs/books/admin_guide/08-process.zh.md b/docs/books/admin_guide/08-process.zh.md new file mode 100644 index 0000000000..cd0493a9bf --- /dev/null +++ b/docs/books/admin_guide/08-process.zh.md @@ -0,0 +1,374 @@ +--- +title: Process Management +--- + +# Process Management + +In this chapter you will learn how to work with processes. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: Recognize the `PID` and `PPID` of a process; +:heavy_check_mark: View and search for processes; +:heavy_check_mark: Manage processes. + +:checkered_flag: **process**, **linux** + +**Knowledge**: :star: :star: +**Complexity**: :star: + +**阅读时间**: 20 分钟 + +**** + +## 概论 + +An operating system consists of processes. These processes are executed in a specific order and are related to each other. There are two categories of processes, those focused on the user environment and those focused on the hardware environment. + +When a program runs, the system will create a process by placing the program data and code in memory and creating a **runtime stack**. A process is therefore an instance of a program with an associated processor environment (ordinal counter, registers, etc...) and memory environment. + +Each process has: + +* a _PID_ : _**P**rocess **ID**entifier_, a unique process identifier; +* a _PPID_ : _**P**arent **P**rocess **ID**entifier_, unique identifier of parent process. + +By successive filiations, the `init` process is the father of all processes. + +* A process is always created by a parent process; +* A parent process can have multiple child processes. + +There is a parent/child relationship between processes. A child process is the result of the parent process calling the _fork()_ primitive and duplicating its own code to create a child. The _PID_ of the child is returned to the parent process so that it can talk to it. Each child has its parent's identifier, the _PPID_. + +The _PID_ number represents the process at the time of execution. When the process finishes, the number is available again for another process. Running the same command several times will produce a different _PID_ each time.!!! Note Processes are not to be confused with _threads_. Each process has its own memory context (resources and address space), while _threads_ from the same process share this same context. + +## Viewing processes + +The `ps` command displays the status of running processes. +``` +ps [-e] [-f] [-u login] +``` + +Example: +``` +# ps -fu root +``` + +| Option | Description | +| ---------- | -------------------------------- | +| `-e` | Displays all processes. | +| `-f` | Displays additional information. | +| `-u` login | Displays the user's processes. | + +Some additional options: + +| Option | Description | +| --------------------- | ------------------------------------------------- | +| `-g` | Displays the processes in the group. | +| `-t tty` | Displays the processes running from the terminal. | +| `-p PID` | Displays the process information. | +| `-H` | Displays the information in a tree structure. | +| `-I` | Displays additional information. | +| `--sort COL` | Sort the result according to a column. | +| `--headers` | Displays the header on each page of the terminal. | +| `--format "%a %b %c"` | Customize the output display format. | + +Without an option specified, the `ps` command only displays processes running from the current terminal. + +The result is displayed in columns: + +``` +# ps -ef +UID PID PPID C STIME TTY TIME CMD +root 1 0 0 Jan01 ? 00:00/03 /sbin/init +``` + +| Column | Description | +| ------- | --------------------------- | +| `UID` | Owner user. | +| `PID` | Process identifier. | +| `PPID` | Parent process identifier. | +| `C` | Priority of the process. | +| `STIME` | Date and time of execution. | +| `TTY` | Execution terminal. | +| `TIME` | Processing duration. | +| `CMD` | Command executed. | + +The behaviour of the control can be fully customized: + +``` +# 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 +``` + +## Types of processes + +The user process: + +* is started from a terminal associated with a user; +* accesses resources via requests or daemons. + +The system process (_demon_): + +* is started by the system; +* is not associated with any terminal, and is owned by a system user (often `root`); +* is loaded at boot time, resides in memory, and is waiting for a call; +* is usually identified by the letter `d` associated with the process name. + +System processes are therefore called daemons (_**D**isk **A**nd **E**xecution **MON**itor_). + +## Permissions and rights + +When a command is executed, the user's credentials are passed to the created process. + +By default, the actual `UID` and `GID` (of the process) are therefore identical to the **actual** `UID` and `GID` (the `UID` and `GID` of the user who executed the command). + +When a `SUID` (and/or `SGID`) is set on a command, the actual `UID` (and/or `GID`) becomes that of the owner (and/or owner group) of the command and no longer that of the user or user group that issued the command. Effective and real **UIDs** are therefore **different**. + +Each time a file is accessed, the system checks the rights of the process according to its effective identifiers. + +## Process management + +A process cannot be run indefinitely, as this would be to the detriment of other running processes and would prevent multitasking. + +The total processing time available is therefore divided into small ranges, and each process (with a priority) accesses the processor in a sequenced manner. The process will take several states during its life among the states: + +* ready: waiting for the availability of the process; +* in execution: accesses the processor; +* suspended: waiting for an I/O (input/output); +* stopped: waiting for a signal from another process; +* zombie: request for destruction; +* dead: the father of the process kills his son. + +The end of process sequencing is as follows: + +1. Closing of the open files; +2. Release of the used memory; +3. Sending a signal to the parent and child processes. + +When a parent process dies, its children are said to be orphans. They are then adopted by the `init` process which will destroy them. + +### The priority of a process + +The processor works in time sharing with each process occupying a quantity of processor time. + +The processes are classified by priority whose value varies from **-20** (the highest priority) to **+19** (the lowest priority). + +The default priority of a process is **0**. + +### Modes of operation + +Processes can run in two ways: + +* **synchronous**: the user loses access to the shell during command execution. The command prompt reappears at the end of the process execution. +* **asynchronous**: the process is processed in the background. The command prompt is displayed again immediately. + +The constraints of the asynchronous mode: + +* the command or script must not wait for keyboard input; +* the command or script must not return any result on the screen; +* quitting the shell ends the process. + +## Process management controls + +### `kill` command + +The `kill` command sends a stop signal to a process. + +``` +kill [-signal] PID +``` + +Example: +``` +$ kill -9 1664 +``` + +| Code | Signal | Description | +| ---- | --------- | ------------------------------------ | +| `2` | _SIGINT_ | Immediate termination of the process | +| `9` | _SIGKILL_ | 中断进程(CTRL + D) | +| `15` | _SIGTERM_ | Clean termination of the process | +| `18` | _SIGCONT_ | Resume the process | +| `19` | _SIGSTOP_ | Suspend the process | + +Signals are the means of communication between processes. The `kill` command sends a signal to a process. + +!!! Tip The complete list of signals taken into account by the `kill` command is available by typing the command : +``` +$ man 7 signal +``` + +### `nohup` command + +`nohup` allows the launching of a process independently of a connection. + +``` +nohup command +``` + +Example: +``` +$ nohup myprogram.sh 0CTRL + Z keys simultaneously, the synchronous process is temporarily suspended. Access to the prompt is restored after displaying the number of the process that has just been suspended. + +### `&` instruction + +The `&` statement executes the command asynchronously (the command is then called _job_) and displays the number of _job_. Access to the prompt is then returned. + +Example: +``` +$ time ls -lR / > list.ls 2> /dev/null & +[1] 15430 +$ +``` + +The _job_ number is obtained during background processing and is displayed in square brackets, followed by the `PID` number. + +### `fg` and `bg` commands + +The `fg` command puts the process in the foreground: + +``` +$ time ls -lR / > list.ls 2>/dev/null & +$ fg 1 +time ls -lR / > list.ls 2/dev/null +``` + +while the command `bg` places it in the background: + +``` +[CTRL]+[Z] +^Z +[1]+ Stopped +$ bg 1 +[1] 15430 +$ +``` + +Whether it was put in the background when it was created with the `&` argument or later with the CTRL +Z keys, a process can be brought back to the foreground with the `fg` command and its job number. + +### `jobs` command + +The `jobs` command displays the list of processes running in the background and specifies their job number. + +Example: +``` +$ jobs +[1]- Running sleep 1000 +[2]+ Running find / > arbo.txt +``` + +The columns represent: + +1. job number; +2. the order in which the processes run +- a `+` : this process is the next process to run by default with `fg` or `bg` ; +- a `-` : this process is the next process to take the `+` ; +3. _Running_ (running process) or _Stopped_ (suspended process). +4. the command + +### `nice` and `renice` commands + +The command `nice` allows the execution of a command by specifying its priority. + +``` +nice priority command +``` + +Example: +``` +$ nice -n+15 find / -name "file" +``` + +Unlike `root`, a standard user can only reduce the priority of a process. Only values between +0 and +19 will be accepted. + +!!! Tip This last limitation can be lifted on a per-user or per-group basis by modifying the `/etc/security/limits.conf` file. + +The `renice` command allows you to change the priority of a running process. + +``` +renice priority [-g GID] [-p PID] [-u UID] +``` + +Example: +``` +$ renice +15 -p 1664 +``` +| Option | Description | +| ------ | --------------------------------- | +| `-g` | `GID` of the process owner group. | +| `-p` | `PID` of the process. | +| `-u` | `UID` of the process owner. | + +The `renice` command acts on processes already running. It is therefore possible to change the priority of a specific process, but also of several processes belonging to a user or a group. + +!!! Tip The `pidof` command, coupled with the `xargs` command (see the Advanced Commands course), allows a new priority to be applied in a single command: +``` +$ pidof sleep | xargs renice 20 +``` + +### `top` command + +The `top` command displays the processes and their resource consumption. + +``` +$ top +PID USER PR NI ... %CPU %MEM TIME+ COMMAND +2514 root 20 0 15 5.5 0:01.14 top +``` + +| Column | Description | +| --------- | --------------------- | +| `PID` | Process identifier. | +| `USER` | Owner user. | +| `PR` | Process priority. | +| `NI` | Nice value. | +| `%CPU` | Processor load. | +| `%MEM` | Memory load. | +| `TIME+` | Processor usage time. | +| `COMMAND` | Command executed. | + +The `top` command allows control of the processes in real time and in interactive mode. + +### `pgrep` and `pkill` commands + +The `pgrep` command searches the running processes for a process name and displays the _PID_ matching the selection criteria on the standard output. + +The `pkill` command will send the specified signal (by default _SIGTERM_) to each process. + +``` +pgrep process +pkill [-signal] process +``` + +Examples: + +* Get the process number from `sshd`: + +``` +$ pgrep -u root sshd +``` + +* Kill all `tomcat` processes: + +``` +$ pkill tomcat +``` From c81fc5fb234f4050a09315905a7b9fec754714bd Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:41 -0500 Subject: [PATCH 05/37] New translations 09-backups.md (French) --- docs/books/admin_guide/09-backups.fr.md | 812 ++++++++++++++++++++++++ 1 file changed, 812 insertions(+) create mode 100644 docs/books/admin_guide/09-backups.fr.md diff --git a/docs/books/admin_guide/09-backups.fr.md b/docs/books/admin_guide/09-backups.fr.md new file mode 100644 index 0000000000..1f2316c97d --- /dev/null +++ b/docs/books/admin_guide/09-backups.fr.md @@ -0,0 +1,812 @@ +--- +title: Backup and Restore +--- + +# Backup and Restore + +In this chapter you will learn how to back up and restore your data with Linux. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: use the `tar` and `cpio` command to make a backup; +:heavy_check_mark: check their backups and restore data; +:heavy_check_mark: compress or decompress their backups. + +:checkered_flag: **backup**, **restore**, **compression** + +**Knowledge**: :star: :star: :star: +**Complexity**: :star: :star: + +**Temps de lecture : **40 minutes + +**** + +!!! Note Throughout this chapter the command structures use "device" to specify both a target location for backup, and the source location when restoring. The device can be either external media or a local file. You should get a feel for this as the chapter unfolds, but you can always refer back to this note for clarification if you need to. + +The backup will answer a need to conserve and restore data in a sure and effective way. + +The backup allows you to protect yourself from the following: + +* **Destruction**: voluntary or involuntary. Human or technical. Virus, ... +* **Deletion**: voluntary or involuntary. Human or technical. Virus, ... +* **Integrity** : data becomes unusable. + +No system is infallible, no human is infallible, so to avoid losing data, it must be backed up to be able to restore after a problem. + +The backup media should be kept in another room (or building) than the server so that a disaster does not destroy the server and the backups. + +In addition, the administrator must regularly check that the media are still readable. + +## Generalities + +There are two principles, the **backup** and the **archive**. + +* The archive destroys the information source after the operation. +* The backup preserves the source of information after the operation. + +These operations consist of saving information in a file, on a peripheral or a supported media (tapes, disks, ...). + +### The process + +Backups require a lot of discipline and rigor from the system administrator. It is necessary to ask the following questions: + +* What is the appropriate medium? +* What should be backed up? +* How many copies? +* How long will the backup take? +* Method? +* How often? +* Automatic or manual? +* Where to store it? +* How long will it be kept? + +### Backup methods + +* **Complete**: one or more **filesystems** are backed up (kernel, data, utilities, ...). +* **Partial**: one or more **files** are backed up (configurations, directories, ...). +* **Differential**: only files modified since the last **complete** backup are backed up. +* **Incremental**: only files modified since the last backup are backed up. + +### Periodicity + +* **Pre-current** : at a given time (before a system update, ...). +* **Periodic**: Daily, weekly, monthly, ... + +!!! Tip Before a system change, it can be useful to make a backup. However, there is no point in backing up data every day that is only changed every month. + +### Restoration methods + +Depending on the utilities available, it will be possible to perform several types of restorations. + +* **Complete restoration**: trees, ... +* **Selective restoration**: part of tree, files, ... + +It is possible to restore a whole backup but it is also possible to restore only a part of it. However, when restoring a directory, the files created after the backup are not deleted. + +!!! Tip To recover a directory as it was at the time of the backup, it is necessary to completely delete its contents before launching the restoration. + +### The tools + +There are many utilities to make backups. + +* **editor tools** ; +* **graphical tools**; +* **command line tools**: `tar`, `cpio`, `pax`, `dd`, `dump`, ... + +The commands we will use here are `tar` and `cpio`. + +* `tar`: + * easy to use ; + * allows adding files to an existing backup. +* `cpio` : + * retains owners; + * retains groups, dates and rights; + * skips damaged files; + * complete file system. + +!!! Note These commands save in a proprietary and standardized format. + +### Naming convention + +The use of a naming convention makes it possible to quickly target the contents of a backup file and thus avoid hazardous restorations. + +* name of the directory; +* utility used; +* options used; +* date. + +!!! Tip The name of the backup must be an explicit name. + +!!! Note The notion of extension under Linux does not exist. In other words, our use of extensions here is for the human operator. If the systems administrator sees a `.tar.gz` or `.tgz` file extension, for instance, then he knows how to deal with the file. + +### Contents of a backup + +A backup generally contains the following elements: + +* the file; +* the name; +* the owner; +* the size; +* the permissions +* access date. + +!!! Note The `inode` number is missing. + +### Storage modes + +There are two different storage modes: + +* file on disk; +* device. + +## Tape ArchiveR - `tar` + +The `tar` command allows saving on several successive media (multi-volume options). + +It is possible to extract all or part of a backup. + +`tar` implicitly backs up in relative mode even if the path of the information to be backed up is mentioned in absolute mode. However, backups and restores in absolute mode are possible. + +### Restoration guidelines + +The right questions to ask are: + +* what: partial or complete; +* where: the place where the data will be restored; +* how: absolute or relative. + +!!! Warning Before a restoration, it is important to take time to think about and determine the most appropriate method to avoid mistakes. + +Restorations are usually performed after a problem has occurred that needs to be resolved quickly. A poor restoration can, in some cases, make the situation worse. + +### Backing up with `tar` + +The default utility for creating backups on UNIX systems is the `tar` command. These backups can be compressed by `bzip2`, `xz`, `lzip`, `lzma`, `lzop`, `gzip`, `compress` or `zstd`. + +`tar` allows you to extract a single file or a directory from a backup, view its contents or validate its integrity. + +#### Estimate the size of a backup + +The following command estimates the size in kilobytes of a possible _tar_ file: + +``` +$ 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 Beware, the presence of "-" in the command line disturbs `zsh`. Switch to `bash`! + +#### Naming convention for a `tar` backup + +Here is an example of a naming convention for a `tar` backup, knowing that the date is to be added to the name. + +| keys | Files | Suffix | Observation | +| ------- | ------- | ---------------- | -------------------------------------------- | +| `cvf` | `home` | `home.tar` | `/home` in relative mode, uncompressed form | +| `cvfP` | `/etc` | `etc.A.tar` | `/etc` in absolute mode, no compression | +| `cvfz` | `usr` | `usr.tar.gz` | `/usr` in relative mode, _gzip_ compression | +| `cvfj` | `usr` | `usr.tar.bz2` | `/usr` in relative mode, _bzip2_ compression | +| `cvfPz` | `/home` | `home.A.tar.gz` | `home` in absolute mode, _gzip_ compression | +| `cvfPj` | `/home` | `home.A.tar.bz2` | `home` in absolute mode, _bzip2_ compression | +| … | | | | + +#### Create a backup + +##### Create a backup in relative mode + +Creating a non-compressed backup in relative mode is done with the `cvf` keys: + +``` +tar c[vf] [device] [file(s)] +``` + +Example: + +``` +[root]# tar cvf /backups/home.133.tar /home/ +``` + + +| Key | Description | +| --- | ------------------------------------------------------ | +| `c` | Creates a backup. | +| `v` | Displays the name of the processed files. | +| `f` | Allows you to specify the name of the backup (medium). | + +!!! Tip The hyphen (`-`) in front of the `tar` keys is not necessary! + +##### Create a backup in absolute mode + +Creating a non-compressed backup explicitly in absolute mode is done with the `cvfP` keys: + +``` +$ tar c[vf]P [device] [file(s)] +``` + +Example: + +``` +[root]# tar cvfP /backups/home.133.P.tar /home/ +``` + +| Key | Description | +| --- | --------------------------------- | +| `P` | Create a backup in absolute mode. | + + +!!! Warning With the `P` key, the path of the files to be backed up must be entered as **absolute**. If the two conditions (key `P` and path **absolute**) are not indicated, the backup is in relative mode. + +##### Creating a compressed backup with `gzip` + +Creating a compressed backup with `gzip` is done with the `cvfz` keys: + +``` +$ tar cvzf backup.tar.gz dirname/ +``` + +| Key | Description | +| --- | -------------------------------- | +| `z` | Compresses the backup in _gzip_. | + + +!!! Note The `.tgz` extension is an equivalent extension to `.tar.gz`. + +!!! Note Keeping the `cvf` (`tvf` or `xvf`) keys unchanged for all backup operations and simply adding the compression key to the end of the keys makes the command easier to understand (e.g. `cvfz` or `cvfj`, etc.). + +##### Creating a compressed backup with `bzip` + +Creating a compressed backup with `bzip` is done with the keys `cvfj`: + +``` +$ tar cvfj backup.tar.bz2 dirname/ +``` + +| Key | Description | +| --- | --------------------------------- | +| `j` | Compresses the backup in _bzip2_. | + +!!! Note The `.tbz` and `.tb2` extensions are equivalent to `.tar.bz2` extensions. + +##### Compression `compress`, `gzip`, `bzip2`, `lzip` and `xz` + +Compression, and consequently decompression, will have an impact on resource consumption (time and CPU usage). + +Here is a ranking of the compression of a set of text files, from least to most efficient: + +- compress (`.tar.Z`) +- gzip (`.tar.gz`) +- bzip2 (`.tar.bz2`) +- lzip (`.tar.lz`) +- xz (`.tar.xz`) + +#### Add a file or directory to an existing backup + +It is possible to add one or more items to an existing backup. + +``` +tar {r|A}[key(s)] [device] [file(s)] +``` + +To add `/etc/passwd` to the backup `/backups/home.133.tar`: + +``` +[root]# tar rvf /backups/home.133.tar /etc/passwd +``` + +Adding a directory is similar. Here add `dirtoadd` to `backup_name.tar`: + +``` +$ tar rvf backup_name.tar dirtoadd +``` + +| Key | Description | +| --- | -------------------------------------------------------------------------------- | +| `r` | Adds one or more files at the end of a direct access media backup (hard disk). | +| `A` | Adds one or more files at the end of a backup on sequential access media (tape). | + +!!! Note It is not possible to add files or folders to a compressed backup. + + ``` + $ tar rvfz backup.tgz filetoadd + tar: Cannot update compressed archives + Try `tar --help' or `tar --usage' for more information. + ``` + +!!! Note If the backup was performed in relative mode, add files in relative mode. If the backup was done in absolute mode, add files in absolute mode. + + Mixing modes can cause problems when restoring. + +#### List the contents of a backup + +Viewing the contents of a backup without extracting it is possible. + +``` +tar t[key(s)] [device] +``` + +| Key | Description | +| --- | ----------------------------------------------------- | +| `t` | Displays the content of a backup (compressed or not). | + +Examples: + +``` +$ tar tvf backup.tar +$ tar tvfz backup.tar.gz +$ tar tvfj backup.tar.bz2 +``` + +When the number of files in a backup becomes large, it is possible to _pipe_ the result of the `tar` command to a _pager_ (`more`, `less`, `most`, etc.): + +``` +$ tar tvf backup.tar | less +``` + +!!! Tip To list or retrieve the contents of a backup, it is not necessary to mention the compression algorithm used when the backup was created. That is, a `tar tvf` is equivalent to `tar tvfj`, to read the contents, and a `tar xvf` is equivalent to `tar xvfj`, to extract. + +!!! Tip Always check the contents of a backup. + +#### Check the integrity of a backup + +The integrity of a backup can be tested with the `W` key at the time of its creation: + +``` +$ tar cvfW file_name.tar dir/ +``` + +The integrity of a backup can be tested with the key `d` after its creation: + +``` +$ tar vfd file_name.tar dir/ +``` + +!!! Tip By adding a second `v` to the previous key, you will get the list of archived files as well as the differences between the archived files and those present in the file system. + + ``` + $ 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 + […] + ``` + +The `W` key is also used to compare the content of an archive against the filesystem: + +``` +$ tar tvfW file_name.tar +Verify 1/file1 +1/file1: Mod time differs +1/file1: Size differs +Verify 1/file2 +Verify 1/file3 +``` + +The verification with the `W` key cannot be done with a compressed archive. The key `d` must be used: + +``` +$ tar dfz file_name.tgz +$ tar dfj file_name.tar.bz2 +``` + +#### Extract (_untar_) a backup + +Extract (_untar]_) a `*.tar` backup is done with the `xvf` keys: + +Extract the `etc/exports` file from the `/savings/etc.133.tar` backup into the `etc` directory of the active directory: + +``` +$ tar xvf /backups/etc.133.tar etc/exports +``` + +Extract all files from the compressed backup `/backups/home.133.tar.bz2` into the active directory: + +``` +[root]# tar xvfj /backups/home.133.tar.bz2 +``` + +Extract all files from the backup `/backups/etc.133.P.tar` to their original directory: + +``` +$ tar xvfP /backups/etc.133.P.tar +``` + +!!! Warning Go to the right place. + + Check the contents of the backup. + +| Key | Description | +| --- | ------------------------------------------------- | +| `x` | Extract files from the backup, compressed or not. | + + +Extracting a _tar-gzipped_ (`*.tar.gz`) backup is done with the `xvfz` keys: + +``` +$ tar xvfz backup.tar.gz +``` + +Extracting a _tar-bzipped_ (`*.tar.bz2`) backup is done with the `xvfj` keys: + +``` +$ tar xvfj backup.tar.bz2 +``` + +!!! Tip To extract or list the contents of a backup, it is not necessary to mention the compression algorithm used to create the backup. That is, a `tar xvf` is equivalent to `tar xvfj`, to extract the contents, and a `tar tvf` is equivalent to `tar tvfj`, to list. + +!!! Warning To restore the files in their original directory (key `P` of a `tar xvf`), you must have generated the backup with the absolute path. That is, with the `P` key of a `tar cvf`. + +##### Extract only a file from a _tar_ backup + +To extract a specific file from a _tar_ backup, specify the name of that file at the end of the `tar xvf` command. + +``` +$ tar xvf backup.tar /path/to/file +``` + +The previous command extracts only the `/path/to/file` file from the `backup.tar` backup. This file will be restored to the `/path/to/` directory created, or already present, in the active directory. + +``` +$ tar xvfz backup.tar.gz /path/to/file +$ tar xvfj backup.tar.bz2 /path/to/file +``` + +##### Extract a folder from a backup _tar_ + +To extract only one directory (including its subdirectories and files) from a backup, specify the directory name at the end of the `tar xvf` command. + +``` +$ tar xvf backup.tar /path/to/dir/ +``` + +To extract multiple directories, specify each of the names one after the other: + +``` +$ 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/ +``` + +##### Extract a group of files from a _tar_ backup using regular expressions (_regex_) + +Specify a _regex_ to extract the files matching the specified selection pattern. + +For example, to extract all files with the extension `.conf` : + +``` +$ tar xvf backup.tar --wildcards '*.conf' +``` + +keys : + + * **--wildcards *.conf** corresponds to files with the extension `.conf`. + +## _CoPy Input Output_ - `cpio` + +The `cpio` command allows saving on several successive media without specifying any options. + +It is possible to extract all or part of a backup. + +There is no option, unlike the `tar` command, to backup and compress at the same time. So it is done in two steps: backup and compression. + +To perform a backup with `cpio`, you have to specify a list of files to backup. + +This list is provided with the commands `find`, `ls` or `cat`. + +* `find` : browse a tree, recursive or not; +* `ls` : list a directory, recursive or not; +* `cat` : reads a file containing the trees or files to be saved. + +!!! Note `ls` cannot be used with `-l` (details) or `-R` (recursive). + + It requires a simple list of names. + +### Create a backup with `cpio` command + +Syntax of the `cpio` command: + +``` +[files command |] cpio {-o| --create} [-options] [device] +``` + +Example: + +With a redirection of the output of `cpio`: + +``` +$ find /etc | cpio -ov > /backups/etc.cpio +``` + +Using the name of a backup media : + +``` +$ find /etc | cpio -ovF /backups/etc.cpio +``` + +The result of the `find` command is sent as input to the `cpio` command via a _pipe_ (character `|`, AltGr + 6). + +Here, the `find /etc` command returns a list of files corresponding to the contents of the `/etc` directory (recursively) to the `cpio` command, which performs the backup. + +Do not forget the `>` sign when saving or the `F save_name_cpio`. + +| Options | Description | +| ------- | ---------------------------------------------- | +| `-o` | Creates a backup (_output_). | +| `-v` | Displays the name of the processed files. | +| `-F` | Designates the backup to be modified (medium). | + +Backup to a media : + +``` +$ find /etc | cpio -ov > /dev/rmt0 +``` + +The support can be of several types: + +* tape drive: `/dev/rmt0` ; +* a partition: `/dev/sda5`, `/dev/hda5`, etc. + +### Type of backup + +#### Backup with relative path + +``` +$ cd / +$ find etc | cpio -o > /backups/etc.cpio +``` + +#### Backup with absolute path + +``` +$ find /etc | cpio -o > /backups/etc.A.cpio +``` + +!!! Warning If the path specified in the `find` command is **absolute** then the backup will be performed in **absolute**. + + If the path indicated in the `find` command is **relative** then the backup will be done in **relative**. + +### Add to a backup + +``` +[files command |] cpio {-o| --create} -A [-options] [device} +``` + +Example: + +``` +$ find /etc/shadow | cpio -o -AF SystemFiles.A.cpio +``` + +Adding files is only possible on direct access media. + +| Option | Description | +| ------ | ------------------------------------------- | +| `-A` | Adds one or more files to a backup on disk. | +| `-F` | Designates the backup to be modified. | + +### Compressing a backup + +* Save **then** compress + +``` +$ find /etc | cpio –o > etc.A.cpio +$ gzip /backups/etc.A.cpio +$ ls /backups/etc.A.cpio* +/backups/etc.A.cpio.gz +``` + +* Save **and** compress + +``` +$ find /etc | cpio –o | gzip > /backups/etc.A.cpio.gz +``` + +There is no option, unlike the `tar` command, to save and compress at the same time. So it is done in two steps: saving and compressing. + +The syntax of the first method is easier to understand and remember, because it is done in two steps. + +For the first method, the backup file is automatically renamed by the `gzip` utility which adds `.gz` to the end of the file name. Similarly the `bzip2` utility automatically adds `.bz2`. + +### Read the contents of a backup + +Syntax of the `cpio` command to read the contents of a _cpio_ backup: + +``` +cpio -t [-options] [ tmp +cpio –iuE tmp -F etc.A.cpio +rm -f tmp +``` + +## Compression - decompression utilities + +Using compression at the time of a backup can have a number of drawbacks: + +* Lengthens the backup time as well as the restore time. +* It makes it impossible to add files to the backup. + +!!! Note It is therefore better to make a backup and compress it than to compress it during the backup. + +### Compressing with `gzip` + +The `gzip` command compresses data. + +Syntax of the `gzip` command: + +``` +gzip [options] [file ...] +``` + +Example: + +``` +$ gzip usr.tar +$ ls +usr.tar.gz +``` + +The file receives the extension `.gz`. + +It keeps the same rights and the same last access and modification dates. + +### Compressing with `bunzip2` + +The `bunzip2` command also compresses data. + +Syntax of the `bzip2` command: + +``` +bzip2 [options] [file ...] +``` + +Example: + +``` +$ bzip2 usr.cpio +$ ls +usr.cpio.bz2 +``` + +The file name is given the extension `.bz2`. + +Compression by `bzip2` is better than compression by `gzip` but it takes longer to execute. + +### Decompressing with `gunzip` + +The `gunzip` command decompresses compressed data. + +Syntax of the `gunzip` command: + +``` +gunzip [options] [file ...] +``` + +Example: + +``` +$ gunzip usr.tar.gz +$ ls +usr.tar +``` + +The file name is truncated by `gunzip` and the extension `.gz` is removed. + +`gunzip` also decompresses files with the following extensions: + +* `.z` ; +* `-z` ; +* `_z` . + +### Decompressing with `bunzip2` + +The `bunzip2` command decompresses compressed data. + +Syntax of the `bzip2` command: + +``` +bzip2 [options] [file ...] +``` + +Example: + +``` +$ bunzip2 usr.cpio.bz2 +$ ls +usr.cpio +``` + +The file name is truncated by `bunzip2` and the extension `.bz2` is removed. + +`bunzip2` also decompresses the file with the following extensions: + +* `-bz` ; +* `.tbz2` ; +* `tbz` . From 7bedee3237490608cc20af270bb25dd04340e37a Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:43 -0500 Subject: [PATCH 06/37] New translations 09-backups.md (Italian) --- docs/books/admin_guide/09-backups.it.md | 812 ++++++++++++++++++++++++ 1 file changed, 812 insertions(+) create mode 100644 docs/books/admin_guide/09-backups.it.md diff --git a/docs/books/admin_guide/09-backups.it.md b/docs/books/admin_guide/09-backups.it.md new file mode 100644 index 0000000000..084dd66767 --- /dev/null +++ b/docs/books/admin_guide/09-backups.it.md @@ -0,0 +1,812 @@ +--- +title: Backup e Ripristino +--- + +# 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_: + +``` +$ 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`: + +``` +tar c[vf] [device] [file(s)] +``` + +Esempio: + +``` +[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`: + +``` +tar c[vf]P [device] [file(s)] +``` + +Esempio: + +``` +[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`: + +``` +$ 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`: + +``` +$ 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. + +``` +tar {r|A}[key(s)] [device] [file(s)] +``` + +Per aggiungere `/etc/passwd` al backup `/backups/home.133.tar`: + +``` +[root]# tar rvf /backups/home.133.tar /etc/passwd +``` + +L'aggiunta di una directory è simile. Qui aggiungi `dirtoadd` a `backup_name.tar`: + +``` +$ 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. + + ``` + $ 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. + +``` +tar t[key(s)] [device] +``` + +| Opzione | Descrizione | +| ------- | -------------------------------------------------------- | +| `t` | Visualizza il contenuto di un backup (compresso o meno). | + +Esempi: + +``` +$ 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.): + +``` +$ 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: + +``` +$ tar cvfW file_name.tar dir/ +``` + +L'integrità di un backup può essere testata con la chiave `d` dopo la sua creazione: + +``` +$ 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. + + ``` + $ 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: + +``` +$ 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` : + +``` +$ 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: + +``` +$ tar xvf /backups/etc.133.tar etc/exports +``` + +Estrarre tutti i file dal backup compresso `/backups/home.133.tar.bz2` nella directory corrente: + +``` +[root]# tar xvfj /backups/home.133.tar.bz2 +``` + +Estrarre tutti i file dal backup `/backups/etc.133.P.tar` nella loro directory originale: + +``` +$ 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`: + +``` +$ tar xvfz backup.tar.gz +``` + +L'estrazione di un _tar-bzipped_ (`*.tar.bz2`) viene eseguita con le opzioni `xvfj`: + +``` +$ 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`. + +``` +$ 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. + +``` +$ 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`. + +``` +$ tar xvf backup.tar /path/to/dir/ +``` + +Per estrarre più directory, specificare ciascuno dei nomi uno dopo l'altro: + +``` +$ 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` : + +``` +$ 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`: + +``` +[files command |] cpio {-o| --create} [-options] [device] +``` + +Esempio: + +Con un reindirizzamento dell'output di `cpio`: + +``` +$ find /etc | cpio -ov > /backups/etc.cpio +``` + +Utilizzo del nome di un supporto di backup: + +``` +$ find /etc | cpio -ovF /backups/etc.cpio +``` + +Il risultato del comando `find` viene inviato come input al comando `cpio` tramite una _pipe_ (carattere `|`, AltGr + 6). + +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`. + +| Opzioni | Descrizione | +| ------- | ---------------------------------------- | +| `-o` | Crea un backup (_output_). | +| `-v` | Visualizza il nome dei file elaborati. | +| `-F` | Indica il backup da modificare (medium). | + +Backup su un supporto: + +``` +$ find /etc | cpio -ov > /dev/rmt0 +``` + +Il supporto può essere di vari tipi: + +* unità nastro: `/dev/rmt0` ; +* una partizione: `/dev/sda5`, `/dev/hda5`, etc. + +### Tipo di backup + +#### Backup con percorso relativo + +``` +$ cd / +$ find etc | cpio -o > /backups/etc.cpio +``` + +#### Backup con percorso assoluto + +``` +$ find /etc | cpio -o > /backups/etc.A.cpio +``` + +!!! Warning "Avvertimento" Se il percorso specificato nel comando `find` è **assoluto** il backup verrà eseguito in **modalità assoluta**. + + Se il percorso indicato nel comando `find` è **relativo** il backup verrà eseguito in **relativo**. + +### Aggiungere a un backup + +``` +[files command |] cpio {-o| --create} -A [-options] [device} +``` + +Esempio: + +``` +$ 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 + +``` +$ 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 + +``` +$ 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_: + +``` +cpio -t [-options] [ tmp +cpio –iuE tmp -F etc.A.cpio +rm -f tmp +``` + +## Utilità di Compressione - decompressione + +Using compression at the time of a backup can have a number of drawbacks: + +* Allunga il tempo di backup e il tempo di ripristino. +* Rende impossibile aggiungere file al backup. + +!!! Note It is therefore better to make a backup and compress it than to compress it during the backup. + +### Compressione con `gzip` + +The `gzip` command compresses data. + +Syntax of the `gzip` command: + +``` +gzip [options] [file ...] +``` + +Example: + +``` +$ gzip usr.tar +$ ls +usr.tar.gz +``` + +The file receives the extension `.gz`. + +It keeps the same rights and the same last access and modification dates. + +### Compressione con `bunzip2` + +The `bunzip2` command also compresses data. + +Syntax of the `bzip2` command: + +``` +bzip2 [options] [file ...] +``` + +Example: + +``` +$ bzip2 usr.cpio +$ ls +usr.cpio.bz2 +``` + +The file name is given the extension `.bz2`. + +Compression by `bzip2` is better than compression by `gzip` but it takes longer to execute. + +### Decompressione con `gunzip` + +The `gunzip` command decompresses compressed data. + +Syntax of the `gunzip` command: + +``` +gunzip [options] [file ...] +``` + +Example: + +``` +$ gunzip usr.tar.gz +$ ls +usr.tar +``` + +The file name is truncated by `gunzip` and the extension `.gz` is removed. + +`gunzip` also decompresses files with the following extensions: + +* `.z` ; +* `-z` ; +* `_z` . + +### Decompressione con `bunzip2` + +The `bunzip2` command decompresses compressed data. + +Syntax of the `bzip2` command: + +``` +bzip2 [options] [file ...] +``` + +Example: + +``` +$ bunzip2 usr.cpio.bz2 +$ ls +usr.cpio +``` + +The file name is truncated by `bunzip2` and the extension `.bz2` is removed. + +`bunzip2` also decompresses the file with the following extensions: + +* `-bz` ; +* `.tbz2` ; +* `tbz` . From 8ce3152fb69d7a64f03e7959d03fe9363569b9ea Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:44 -0500 Subject: [PATCH 07/37] New translations 09-backups.md (Chinese Simplified) --- docs/books/admin_guide/09-backups.zh.md | 812 ++++++++++++++++++++++++ 1 file changed, 812 insertions(+) create mode 100644 docs/books/admin_guide/09-backups.zh.md diff --git a/docs/books/admin_guide/09-backups.zh.md b/docs/books/admin_guide/09-backups.zh.md new file mode 100644 index 0000000000..e7f929df2e --- /dev/null +++ b/docs/books/admin_guide/09-backups.zh.md @@ -0,0 +1,812 @@ +--- +title: Backup and Restore +--- + +# Backup and Restore + +In this chapter you will learn how to back up and restore your data with Linux. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: use the `tar` and `cpio` command to make a backup; +:heavy_check_mark: check their backups and restore data; +:heavy_check_mark: compress or decompress their backups. + +:checkered_flag: **backup**, **restore**, **compression** + +**Knowledge**: :star: :star: :star: +**Complexity**: :star: :star: + +**阅读时间**: 40 分钟 + +**** + +!!! Note Throughout this chapter the command structures use "device" to specify both a target location for backup, and the source location when restoring. The device can be either external media or a local file. You should get a feel for this as the chapter unfolds, but you can always refer back to this note for clarification if you need to. + +The backup will answer a need to conserve and restore data in a sure and effective way. + +The backup allows you to protect yourself from the following: + +* **Destruction**: voluntary or involuntary. Human or technical. Virus, ... +* **Deletion**: voluntary or involuntary. Human or technical. Virus, ... +* **Integrity** : data becomes unusable. + +No system is infallible, no human is infallible, so to avoid losing data, it must be backed up to be able to restore after a problem. + +The backup media should be kept in another room (or building) than the server so that a disaster does not destroy the server and the backups. + +In addition, the administrator must regularly check that the media are still readable. + +## 概论 + +There are two principles, the **backup** and the **archive**. + +* The archive destroys the information source after the operation. +* The backup preserves the source of information after the operation. + +These operations consist of saving information in a file, on a peripheral or a supported media (tapes, disks, ...). + +### The process + +Backups require a lot of discipline and rigor from the system administrator. It is necessary to ask the following questions: + +* What is the appropriate medium? +* What should be backed up? +* How many copies? +* How long will the backup take? +* Method? +* How often? +* Automatic or manual? +* Where to store it? +* How long will it be kept? + +### Backup methods + +* **Complete**: one or more **filesystems** are backed up (kernel, data, utilities, ...). +* **Partial**: one or more **files** are backed up (configurations, directories, ...). +* **Differential**: only files modified since the last **complete** backup are backed up. +* **Incremental**: only files modified since the last backup are backed up. + +### Periodicity + +* **Pre-current** : at a given time (before a system update, ...). +* **Periodic**: Daily, weekly, monthly, ... + +!!! Tip Before a system change, it can be useful to make a backup. However, there is no point in backing up data every day that is only changed every month. + +### Restoration methods + +Depending on the utilities available, it will be possible to perform several types of restorations. + +* **Complete restoration**: trees, ... +* **Selective restoration**: part of tree, files, ... + +It is possible to restore a whole backup but it is also possible to restore only a part of it. However, when restoring a directory, the files created after the backup are not deleted. + +!!! Tip To recover a directory as it was at the time of the backup, it is necessary to completely delete its contents before launching the restoration. + +### The tools + +There are many utilities to make backups. + +* **editor tools** ; +* **graphical tools**; +* **command line tools**: `tar`, `cpio`, `pax`, `dd`, `dump`, ... + +The commands we will use here are `tar` and `cpio`. + +* `tar`: + * easy to use ; + * allows adding files to an existing backup. +* `cpio` : + * retains owners; + * retains groups, dates and rights; + * skips damaged files; + * complete file system. + +!!! Note These commands save in a proprietary and standardized format. + +### Naming convention + +The use of a naming convention makes it possible to quickly target the contents of a backup file and thus avoid hazardous restorations. + +* name of the directory; +* utility used; +* options used; +* date. + +!!! Tip The name of the backup must be an explicit name. + +!!! Note The notion of extension under Linux does not exist. In other words, our use of extensions here is for the human operator. If the systems administrator sees a `.tar.gz` or `.tgz` file extension, for instance, then he knows how to deal with the file. + +### Contents of a backup + +A backup generally contains the following elements: + +* the file; +* the name; +* the owner; +* the size; +* the permissions +* access date. + +!!! Note The `inode` number is missing. + +### Storage modes + +There are two different storage modes: + +* file on disk; +* device. + +## Tape ArchiveR - `tar` + +The `tar` command allows saving on several successive media (multi-volume options). + +It is possible to extract all or part of a backup. + +`tar` implicitly backs up in relative mode even if the path of the information to be backed up is mentioned in absolute mode. However, backups and restores in absolute mode are possible. + +### Restoration guidelines + +The right questions to ask are: + +* what: partial or complete; +* where: the place where the data will be restored; +* how: absolute or relative. + +!!! Warning Before a restoration, it is important to take time to think about and determine the most appropriate method to avoid mistakes. + +Restorations are usually performed after a problem has occurred that needs to be resolved quickly. A poor restoration can, in some cases, make the situation worse. + +### Backing up with `tar` + +The default utility for creating backups on UNIX systems is the `tar` command. These backups can be compressed by `bzip2`, `xz`, `lzip`, `lzma`, `lzop`, `gzip`, `compress` or `zstd`. + +`tar` allows you to extract a single file or a directory from a backup, view its contents or validate its integrity. + +#### Estimate the size of a backup + +The following command estimates the size in kilobytes of a possible _tar_ file: + +``` +$ 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 Beware, the presence of "-" in the command line disturbs `zsh`. Switch to `bash`! + +#### Naming convention for a `tar` backup + +Here is an example of a naming convention for a `tar` backup, knowing that the date is to be added to the name. + +| keys | Files | Suffix | Observation | +| ------- | ------- | ---------------- | -------------------------------------------- | +| `cvf` | `home` | `home.tar` | `/home` in relative mode, uncompressed form | +| `cvfP` | `/etc` | `etc.A.tar` | `/etc` in absolute mode, no compression | +| `cvfz` | `usr` | `usr.tar.gz` | `/usr` in relative mode, _gzip_ compression | +| `cvfj` | `usr` | `usr.tar.bz2` | `/usr` in relative mode, _bzip2_ compression | +| `cvfPz` | `/home` | `home.A.tar.gz` | `home` in absolute mode, _gzip_ compression | +| `cvfPj` | `/home` | `home.A.tar.bz2` | `home` in absolute mode, _bzip2_ compression | +| … | | | | + +#### Create a backup + +##### Create a backup in relative mode + +Creating a non-compressed backup in relative mode is done with the `cvf` keys: + +``` +tar c[vf] [device] [file(s)] +``` + +Example: + +``` +[root]# tar cvf /backups/home.133.tar /home/ +``` + + +| Key | Description | +| --- | ------------------------------------------------------ | +| `c` | Creates a backup. | +| `v` | Displays the name of the processed files. | +| `f` | Allows you to specify the name of the backup (medium). | + +!!! Tip The hyphen (`-`) in front of the `tar` keys is not necessary! + +##### Create a backup in absolute mode + +Creating a non-compressed backup explicitly in absolute mode is done with the `cvfP` keys: + +``` +$ tar c[vf]P [device] [file(s)] +``` + +Example: + +``` +[root]# tar cvfP /backups/home.133.P.tar /home/ +``` + +| Key | Description | +| --- | --------------------------------- | +| `P` | Create a backup in absolute mode. | + + +!!! Warning With the `P` key, the path of the files to be backed up must be entered as **absolute**. If the two conditions (key `P` and path **absolute**) are not indicated, the backup is in relative mode. + +##### Creating a compressed backup with `gzip` + +Creating a compressed backup with `gzip` is done with the `cvfz` keys: + +``` +$ tar cvzf backup.tar.gz dirname/ +``` + +| Key | Description | +| --- | -------------------------------- | +| `z` | Compresses the backup in _gzip_. | + + +!!! Note The `.tgz` extension is an equivalent extension to `.tar.gz`. + +!!! Note Keeping the `cvf` (`tvf` or `xvf`) keys unchanged for all backup operations and simply adding the compression key to the end of the keys makes the command easier to understand (e.g. `cvfz` or `cvfj`, etc.). + +##### Creating a compressed backup with `bzip` + +Creating a compressed backup with `bzip` is done with the keys `cvfj`: + +``` +$ tar cvfj backup.tar.bz2 dirname/ +``` + +| Key | Description | +| --- | --------------------------------- | +| `j` | Compresses the backup in _bzip2_. | + +!!! Note The `.tbz` and `.tb2` extensions are equivalent to `.tar.bz2` extensions. + +##### Compression `compress`, `gzip`, `bzip2`, `lzip` and `xz` + +Compression, and consequently decompression, will have an impact on resource consumption (time and CPU usage). + +Here is a ranking of the compression of a set of text files, from least to most efficient: + +- compress (`.tar.Z`) +- gzip (`.tar.gz`) +- bzip2 (`.tar.bz2`) +- lzip (`.tar.lz`) +- xz (`.tar.xz`) + +#### Add a file or directory to an existing backup + +It is possible to add one or more items to an existing backup. + +``` +tar {r|A}[key(s)] [device] [file(s)] +``` + +To add `/etc/passwd` to the backup `/backups/home.133.tar`: + +``` +[root]# tar rvf /backups/home.133.tar /etc/passwd +``` + +Adding a directory is similar. Here add `dirtoadd` to `backup_name.tar`: + +``` +$ tar rvf backup_name.tar dirtoadd +``` + +| Key | Description | +| --- | -------------------------------------------------------------------------------- | +| `r` | Adds one or more files at the end of a direct access media backup (hard disk). | +| `A` | Adds one or more files at the end of a backup on sequential access media (tape). | + +!!! Note It is not possible to add files or folders to a compressed backup. + + ``` + $ tar rvfz backup.tgz filetoadd + tar: Cannot update compressed archives + Try `tar --help' or `tar --usage' for more information. + ``` + +!!! Note If the backup was performed in relative mode, add files in relative mode. If the backup was done in absolute mode, add files in absolute mode. + + Mixing modes can cause problems when restoring. + +#### List the contents of a backup + +Viewing the contents of a backup without extracting it is possible. + +``` +tar t[key(s)] [device] +``` + +| Key | Description | +| --- | ----------------------------------------------------- | +| `t` | Displays the content of a backup (compressed or not). | + +Examples: + +``` +$ tar tvf backup.tar +$ tar tvfz backup.tar.gz +$ tar tvfj backup.tar.bz2 +``` + +When the number of files in a backup becomes large, it is possible to _pipe_ the result of the `tar` command to a _pager_ (`more`, `less`, `most`, etc.): + +``` +$ tar tvf backup.tar | less +``` + +!!! Tip To list or retrieve the contents of a backup, it is not necessary to mention the compression algorithm used when the backup was created. That is, a `tar tvf` is equivalent to `tar tvfj`, to read the contents, and a `tar xvf` is equivalent to `tar xvfj`, to extract. + +!!! Tip Always check the contents of a backup. + +#### Check the integrity of a backup + +The integrity of a backup can be tested with the `W` key at the time of its creation: + +``` +$ tar cvfW file_name.tar dir/ +``` + +The integrity of a backup can be tested with the key `d` after its creation: + +``` +$ tar vfd file_name.tar dir/ +``` + +!!! Tip By adding a second `v` to the previous key, you will get the list of archived files as well as the differences between the archived files and those present in the file system. + + ``` + $ 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 + […] + ``` + +The `W` key is also used to compare the content of an archive against the filesystem: + +``` +$ tar tvfW file_name.tar +Verify 1/file1 +1/file1: Mod time differs +1/file1: Size differs +Verify 1/file2 +Verify 1/file3 +``` + +The verification with the `W` key cannot be done with a compressed archive. The key `d` must be used: + +``` +$ tar dfz file_name.tgz +$ tar dfj file_name.tar.bz2 +``` + +#### Extract (_untar_) a backup + +Extract (_untar]_) a `*.tar` backup is done with the `xvf` keys: + +Extract the `etc/exports` file from the `/savings/etc.133.tar` backup into the `etc` directory of the active directory: + +``` +$ tar xvf /backups/etc.133.tar etc/exports +``` + +Extract all files from the compressed backup `/backups/home.133.tar.bz2` into the active directory: + +``` +[root]# tar xvfj /backups/home.133.tar.bz2 +``` + +Extract all files from the backup `/backups/etc.133.P.tar` to their original directory: + +``` +$ tar xvfP /backups/etc.133.P.tar +``` + +!!! Warning Go to the right place. + + Check the contents of the backup. + +| Key | Description | +| --- | ------------------------------------------------- | +| `x` | Extract files from the backup, compressed or not. | + + +Extracting a _tar-gzipped_ (`*.tar.gz`) backup is done with the `xvfz` keys: + +``` +$ tar xvfz backup.tar.gz +``` + +Extracting a _tar-bzipped_ (`*.tar.bz2`) backup is done with the `xvfj` keys: + +``` +$ tar xvfj backup.tar.bz2 +``` + +!!! Tip To extract or list the contents of a backup, it is not necessary to mention the compression algorithm used to create the backup. That is, a `tar xvf` is equivalent to `tar xvfj`, to extract the contents, and a `tar tvf` is equivalent to `tar tvfj`, to list. + +!!! Warning To restore the files in their original directory (key `P` of a `tar xvf`), you must have generated the backup with the absolute path. That is, with the `P` key of a `tar cvf`. + +##### Extract only a file from a _tar_ backup + +To extract a specific file from a _tar_ backup, specify the name of that file at the end of the `tar xvf` command. + +``` +$ tar xvf backup.tar /path/to/file +``` + +The previous command extracts only the `/path/to/file` file from the `backup.tar` backup. This file will be restored to the `/path/to/` directory created, or already present, in the active directory. + +``` +$ tar xvfz backup.tar.gz /path/to/file +$ tar xvfj backup.tar.bz2 /path/to/file +``` + +##### Extract a folder from a backup _tar_ + +To extract only one directory (including its subdirectories and files) from a backup, specify the directory name at the end of the `tar xvf` command. + +``` +$ tar xvf backup.tar /path/to/dir/ +``` + +To extract multiple directories, specify each of the names one after the other: + +``` +$ 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/ +``` + +##### Extract a group of files from a _tar_ backup using regular expressions (_regex_) + +Specify a _regex_ to extract the files matching the specified selection pattern. + +For example, to extract all files with the extension `.conf` : + +``` +$ tar xvf backup.tar --wildcards '*.conf' +``` + +keys : + + * **--wildcards *.conf** corresponds to files with the extension `.conf`. + +## _CoPy Input Output_ - `cpio` + +The `cpio` command allows saving on several successive media without specifying any options. + +It is possible to extract all or part of a backup. + +There is no option, unlike the `tar` command, to backup and compress at the same time. So it is done in two steps: backup and compression. + +To perform a backup with `cpio`, you have to specify a list of files to backup. + +This list is provided with the commands `find`, `ls` or `cat`. + +* `find` : browse a tree, recursive or not; +* `ls` : list a directory, recursive or not; +* `cat` : reads a file containing the trees or files to be saved. + +!!! Note `ls` cannot be used with `-l` (details) or `-R` (recursive). + + It requires a simple list of names. + +### Create a backup with `cpio` command + +Syntax of the `cpio` command: + +``` +[files command |] cpio {-o| --create} [-options] [device] +``` + +Example: + +With a redirection of the output of `cpio`: + +``` +$ find /etc | cpio -ov > /backups/etc.cpio +``` + +Using the name of a backup media : + +``` +$ find /etc | cpio -ovF /backups/etc.cpio +``` + +The result of the `find` command is sent as input to the `cpio` command via a _pipe_ (character `|`, AltGr + 6). + +Here, the `find /etc` command returns a list of files corresponding to the contents of the `/etc` directory (recursively) to the `cpio` command, which performs the backup. + +Do not forget the `>` sign when saving or the `F save_name_cpio`. + +| Options | Description | +| ------- | ---------------------------------------------- | +| `-o` | Creates a backup (_output_). | +| `-v` | Displays the name of the processed files. | +| `-F` | Designates the backup to be modified (medium). | + +Backup to a media : + +``` +$ find /etc | cpio -ov > /dev/rmt0 +``` + +The support can be of several types: + +* tape drive: `/dev/rmt0` ; +* a partition: `/dev/sda5`, `/dev/hda5`, etc. + +### Type of backup + +#### Backup with relative path + +``` +$ cd / +$ find etc | cpio -o > /backups/etc.cpio +``` + +#### Backup with absolute path + +``` +$ find /etc | cpio -o > /backups/etc.A.cpio +``` + +!!! Warning If the path specified in the `find` command is **absolute** then the backup will be performed in **absolute**. + + If the path indicated in the `find` command is **relative** then the backup will be done in **relative**. + +### Add to a backup + +``` +[files command |] cpio {-o| --create} -A [-options] [device} +``` + +Example: + +``` +$ find /etc/shadow | cpio -o -AF SystemFiles.A.cpio +``` + +Adding files is only possible on direct access media. + +| Option | Description | +| ------ | ------------------------------------------- | +| `-A` | Adds one or more files to a backup on disk. | +| `-F` | Designates the backup to be modified. | + +### Compressing a backup + +* Save **then** compress + +``` +$ find /etc | cpio –o > etc.A.cpio +$ gzip /backups/etc.A.cpio +$ ls /backups/etc.A.cpio* +/backups/etc.A.cpio.gz +``` + +* Save **and** compress + +``` +$ find /etc | cpio –o | gzip > /backups/etc.A.cpio.gz +``` + +There is no option, unlike the `tar` command, to save and compress at the same time. So it is done in two steps: saving and compressing. + +The syntax of the first method is easier to understand and remember, because it is done in two steps. + +For the first method, the backup file is automatically renamed by the `gzip` utility which adds `.gz` to the end of the file name. Similarly the `bzip2` utility automatically adds `.bz2`. + +### Read the contents of a backup + +Syntax of the `cpio` command to read the contents of a _cpio_ backup: + +``` +cpio -t [-options] [ tmp +cpio –iuE tmp -F etc.A.cpio +rm -f tmp +``` + +## Compression - decompression utilities + +Using compression at the time of a backup can have a number of drawbacks: + +* Lengthens the backup time as well as the restore time. +* It makes it impossible to add files to the backup. + +!!! Note It is therefore better to make a backup and compress it than to compress it during the backup. + +### Compressing with `gzip` + +The `gzip` command compresses data. + +Syntax of the `gzip` command: + +``` +gzip [options] [file ...] +``` + +Example: + +``` +$ gzip usr.tar +$ ls +usr.tar.gz +``` + +The file receives the extension `.gz`. + +It keeps the same rights and the same last access and modification dates. + +### Compressing with `bunzip2` + +The `bunzip2` command also compresses data. + +Syntax of the `bzip2` command: + +``` +bzip2 [options] [file ...] +``` + +Example: + +``` +$ bzip2 usr.cpio +$ ls +usr.cpio.bz2 +``` + +The file name is given the extension `.bz2`. + +Compression by `bzip2` is better than compression by `gzip` but it takes longer to execute. + +### Decompressing with `gunzip` + +The `gunzip` command decompresses compressed data. + +Syntax of the `gunzip` command: + +``` +gunzip [options] [file ...] +``` + +Example: + +``` +$ gunzip usr.tar.gz +$ ls +usr.tar +``` + +The file name is truncated by `gunzip` and the extension `.gz` is removed. + +`gunzip` also decompresses files with the following extensions: + +* `.z` ; +* `-z` ; +* `_z` . + +### Decompressing with `bunzip2` + +The `bunzip2` command decompresses compressed data. + +Syntax of the `bzip2` command: + +``` +bzip2 [options] [file ...] +``` + +Example: + +``` +$ bunzip2 usr.cpio.bz2 +$ ls +usr.cpio +``` + +The file name is truncated by `bunzip2` and the extension `.bz2` is removed. + +`bunzip2` also decompresses the file with the following extensions: + +* `-bz` ; +* `.tbz2` ; +* `tbz` . From c7226abf3f7408773b7c1919881d460cd08f68b8 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:45 -0500 Subject: [PATCH 08/37] New translations 10-boot.md (French) --- docs/books/admin_guide/10-boot.fr.md | 412 +++++++++++++++++++++++++++ 1 file changed, 412 insertions(+) create mode 100644 docs/books/admin_guide/10-boot.fr.md diff --git a/docs/books/admin_guide/10-boot.fr.md b/docs/books/admin_guide/10-boot.fr.md new file mode 100644 index 0000000000..1d4204a117 --- /dev/null +++ b/docs/books/admin_guide/10-boot.fr.md @@ -0,0 +1,412 @@ +--- +title: System Startup +--- + +# System Startup + +In this chapter you will learn how the system start. + +**** +**Objectives** : In this chapter, future Linux administrators will learn: + +:heavy_check_mark: The different stages of the booting process; +:heavy_check_mark: How Rocky Linux supports this boot via GRUB2 and systemd; +:heavy_check_mark: How to protect GRUB2 from an attack; +:heavy_check_mark: How to manage the services; +:heavy_check_mark: How to access to the logs from journald. + +:checkered_flag: **users** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: :star: + +**Temps de lecture : **20 minutes +**** + +## The boot process + +It is important to understand the boot process of Linux in order to be able to solve problems that may occur. + +The boot process includes: + +### The BIOS startup + +The **BIOS** (Basic Input/Output System) performs the **POST** (power on self test) to detect, test and initialize the system hardware components. + +It then loads the **MBR** (Master Boot Record). + +### The Master boot record (MBR) + +The Master Boot Record is the first 512 bytes of the boot disk. The MBR discovers the boot device and loads the bootloader **GRUB2** into memory and transfers control to it. + +The next 64 bytes contain the partition table of the disk. + +### The GRUB2 bootloader + +The default bootloader for the Rocky 8 distribution is **GRUB2** (GRand Unified Bootloader). GRUB2 replaces the old GRUB bootloader (also called GRUB legacy). + +The GRUB 2 configuration file is located under `/boot/grub2/grub.cfg` but this file should not be edited directly. + +The GRUB2 menu configuration settings are located under `/etc/default/grub` and are used to generate the `grub.cfg` file. + +``` +# 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" +``` + +If changes are made to one or more of these parameters, the `grub2-mkconfig` command must be run to regenerate the `/boot/grub2/grub.cfg` file. + +``` +[root] # grub2-mkconfig –o /boot/grub2/grub.cfg +``` + +* GRUB2 looks for the compressed kernel image (the `vmlinuz` file) in the `/boot` directory. +* GRUB2 loads the kernel image into memory and extracts the contents of the `initramfs` image file into a temporary folder in memory using the `tmpfs` file system. + +### The kernel + +The kernel starts the `systemd` process with PID 1. +``` +root 1 0 0 02:10 ? 00:00:02 /usr/lib/systemd/systemd --switched-root --system --deserialize 23 +``` + +### `systemd` + +Systemd is the parent of all system processes. It reads the target of the `/etc/systemd/system/default.target` link (e.g. `/usr/lib/systemd/system/multi-user.target`) to determine the default target of the system. The file defines the services to be started. + +Systemd then places the system in the target-defined state by performing the following initialization tasks: + +1. Set the machine name +2. Initialize the network +3. Initialize SELinux +4. Display the welcome banner +5. Initialize the hardware based on the arguments given to the kernel at boot time +6. Mount the file systems, including virtual file systems like /proc +7. Clean up directories in /var +8. Start the virtual memory (swap) + +## Protecting the GRUB2 bootloader + +Why protect the bootloader with a password? + +1. Prevent *Single* user mode access - If an attacker can boot into single user mode, he becomes the root user. +2. Prevent access to GRUB console - If an attacker manages to use GRUB console, he can change its configuration or collect information about the system by using the `cat` command. +3. Prevent access to insecure operating systems. If there is a dual boot on the system, an attacker can select an operating system like DOS at boot time that ignores access controls and file permissions. + +To password protect the GRUB2 bootloader: + +* Remove `-unrestricted` from the main `CLASS=` statement in the `/etc/grub.d/10_linux` file. + +* If a user has not yet been configured, use the `grub2-setpassword` command to provide a password for the root user: + +``` +# grub2-setpassword +``` + +A `/boot/grub2/user.cfg` file will be created if it was not already present. It contains the hashed password of the GRUB2. + +!!! Note This command only supports configurations with a single root user. + +``` +[root]# cat /boot/grub2/user.cfg +GRUB2_PASSWORD=grub.pbkdf2.sha512.10000.CC6F56....A21 +``` + +* Recreate the configuration file with the `grub2-mkconfig` command: + +``` +[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 +``` + +* Restart the server and check. + +All entries defined in the GRUB menu will now require a user and password to be entered at each boot. The system will not boot a kernel without direct user intervention from the console. + +* When the user is requested, enter `root`; +* When a password is requested, enter the password provided at the `grub2-setpassword` command. + +To protect only the editing of GRUB menu entries and access to the console, the execution of the `grub2-setpassword` command is sufficient. There may be cases where you have good reasons for doing only that. This might be particularly true in a remote data center where entering a password each time a server is rebooted is either difficult or impossible to do. + +## Systemd + +*Systemd* is a service manager for the Linux operating systems. + +It is developed to: + +* remain compatible with older SysV initialization scripts, +* provide many features, such as parallel start of system services at system startup, on-demand activation of daemons, support for snapshots, or management of dependencies between services. + +!!! Note Systemd is the default initialization system since RedHat/CentOS 7. + +Systemd introduces the concept of systemd units. + +| Type | File extension | Observation | +| ------------ | -------------- | ---------------------------------------- | +| Service unit | `.service` | System service | +| Target unit | `.target` | A group of systemd units | +| Mount unit | `.automount` | An automatic mount point for file system | + +!!! Note There are many types of units: Device unit, Mount unit, Path unit, Scope unit, Slice unit, Snapshot unit, Socket unit, Swap unit, Timer unit. + +* Systemd supports system state snapshots and restore. + +* Mount points can be configured as systemd targets. + +* At startup, systemd creates listening sockets for all system services that support this type of activation and passes these sockets to these services as soon as they are started. This makes it possible to restart a service without losing a single message sent to it by the network during its unavailability. The corresponding socket remains accessible and all messages are queued. + +* System services that use D-BUS for their inter-process communications can be started on demand the first time they are used by a client. + +* Systemd stops or restarts only running services. Previous versions (before RHEL7) attempted to stop services directly without checking their current status. + +* System services do not inherit any context (like HOME and PATH environment variables). Each service operates in its own execution context. + +All service unit operations are subject to a default timeout of 5 minutes to prevent a malfunctioning service from freezing the system. + +### Managing system services + +Service units end with the `.service` file extension and have a similar purpose to init scripts. The `systemctl` command is used to `display`, `start`, `stop`, `restart` a system service: + +| systemctl | Description | +| ----------------------------------------- | --------------------------------------- | +| systemctl start _name_.service | Start a service | +| systemctl stop _name_.service | Stops a service | +| systemctl restart _name_.service | Restart a service | +| systemctl reload _name_.service | Reload a configuration | +| systemctl status _name_.service | Checks if a service is running | +| systemctl try-restart _name_.service | Restart a service only if it is running | +| systemctl list-units --type service --all | Display the status of all services | + +The `systemctl` command is also used for the `enable` or `disable` of system a service and displaying associated services: + +| systemctl | Description | +| ---------------------------------------- | ------------------------------------------------------- | +| systemctl enable _name_.service | Activate a service | +| systemctl disable _name_.service | Disable a service | +| systemctl list-unit-files --type service | Lists all services and checks if they are running | +| systemctl list-dependencies --after | Lists the services that start before the specified unit | +| systemctl list-dependencies --before | Lists the services that start after the specified unit | + +Examples: + +``` +systemctl stop nfs-server.service +# or +systemctl stop nfs-server +``` + +To list all units currently loaded: + +``` +systemctl list-units --type service +``` + +To list all units to check if they are activated: + +``` +systemctl list-unit-files --type service +``` + +``` +systemctl enable httpd.service +systemctl disable bluetooth.service +``` + +### Example of a .service file for the postfix service + +``` +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 +``` + +### Using system targets + +On Rocky8/RHEL8, the concept of run levels has been replaced by Systemd targets. + +Systemd targets are represented by target units. Target units end with the `.target` file extension and their sole purpose is to group other Systemd units into a chain of dependencies. + +For example, the `graphical.target` unit, which is used to start a graphical session, starts system services such as the **GNOME display manager** (`gdm.service`) or the **accounts service** (`accounts-daemon.service`) and also activates the `multi-user.target` unit. + +Similarly, the `multi-user.target` unit starts other essential system services, such as **NetworkManager** (`NetworkManager.service`) or **D-Bus** (`dbus.service`) and activates another target unit named `basic.target`. + +| Target Units | Description | +| ----------------- | --------------------------------------------------------- | +| poweroff.target | Shuts down the system and turns it off | +| rescue.target | Activates a rescue shell | +| multi-user.target | Activates a multi-user system without graphical interface | +| graphical.target | Activates a multi-user system with graphical interface | +| reboot.target | Shuts down and restarts the system | + +#### The default target + +To determine which target is used by default: + +``` +systemctl get-default +``` + +This command searches for the target of the symbolic link located at `/etc/systemd/system/default.target` and displays the result. + +``` +$ systemctl get-default +graphical.target +``` + +The `systemctl` command can also provide a list of available targets: + +``` +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 +``` + +To configure the system to use a different default target: + +``` +systemctl set-default name.target +``` + +Example: + +``` +# 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' +``` + +To switch to a different target unit in the current session: + +``` +systemctl isolate name.target +``` + +The **Rescue mode** provides a simple environment to repair your system in cases where it is impossible to perform a normal boot process. + +In `rescue mode`, the system attempts to mount all local file systems and start several important system services, but does not enable a network interface or allow other users to connect to the system at the same time. + +On Rocky 8, the `rescue mode` is equivalent to the old `single user mode` and requires the root password. + +To change the current target and enter `rescue mode` in the current session: + +``` +systemctl rescue +``` + +**Emergency mode** provides the most minimalist environment possible and allows the system to be repaired even in situations where the system is unable to enter rescue mode. In the emergency mode, the system mounts the root file system only for reading. It will not attempt to mount any other local file system, will not activate any network interface, and will start some essential services. + +To change the current target and enter emergency mode in the current session: + +``` +systemctl emergency +``` + +#### Shutdown, suspension and hibernation + +The `systemctl` command replaces a number of power management commands used in previous versions: + +| Old command | New command | Description | +| ------------------- | ------------------------ | ----------------------------------- | +| `halt` | `systemctl halt` | Shuts down the system. | +| `poweroff` | `systemctl poweroff` | Turns off the system. | +| `reboot` | `systemctl reboot` | Restarts the system. | +| `pm-suspend` | `systemctl suspend` | Suspends the system. | +| `pm-hibernate` | `systemctl hibernate` | Hibernates the system. | +| `pm-suspend-hybrid` | `systemctl hybrid-sleep` | Hibernates and suspends the system. | + +### The `journald` process + +Log files can, in addition to `rsyslogd`, also be managed by the `journald` daemon which is a component of `systemd`. + +The `journald` daemon captures Syslog messages, kernel log messages, messages from the initial RAM disk and from the start of boot, as well as messages written to the standard output and the standard error output of all services, then indexes them and makes them available to the user. + +The format of the native log file, which is a structured and indexed binary file, improves searches and allows for faster operation, it also stores metadata information, such as timestamps or user IDs. + +### `journalctl` command + +The `journalctl` command displays the log files. + +``` +journalctl +``` + +The command lists all log files generated on the system. The structure of this output is similar to that used in `/var/log/messages/` but it offers some improvements: + +* the priority of entries is marked visually; +* timestamps are converted to the local time zone of your system; +* all logged data is displayed, including rotating logs; +* the beginning of a start is marked with a special line. + +#### Using continuous display + +With continuous display, log messages are displayed in real time. + +``` +journalctl -f +``` + +This command returns a list of the ten most recent log lines. The journalctl utility then continues to run and waits for new changes to occur before displaying them immediately. + +#### Filtering messages + +It is possible to use different filtering methods to extract information that fits different needs. Log messages are often used to track erroneous behavior on the system. To view entries with a selected or higher priority: + +``` +journalctl -p priority +``` + +You must replace priority with one of the following keywords (or a number): + +* debug (7), +* info (6), +* notice (5), +* warning (4), +* err (3), +* crit (2), +* alert (1), +* and emerg (0). From 1abe9b93a323f02a488ba54b16281fac747f73e5 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:45 -0500 Subject: [PATCH 09/37] New translations 10-boot.md (Italian) --- docs/books/admin_guide/10-boot.it.md | 412 +++++++++++++++++++++++++++ 1 file changed, 412 insertions(+) create mode 100644 docs/books/admin_guide/10-boot.it.md diff --git a/docs/books/admin_guide/10-boot.it.md b/docs/books/admin_guide/10-boot.it.md new file mode 100644 index 0000000000..fcfd64cfa8 --- /dev/null +++ b/docs/books/admin_guide/10-boot.it.md @@ -0,0 +1,412 @@ +--- +title: Avvio del sistema +--- + +# 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`. + +``` +# 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`. + +``` +[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. +``` +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: + +``` +# 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. + +``` +[root]# cat /boot/grub2/user.cfg +GRUB2_PASSWORD=grub.pbkdf2.sha512.10000.CC6F56....A21 +``` + +* Ricreare il file di configurazione con il comando `grub2-mkconfig`: + +``` +[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: + +``` +systemctl stop nfs-server.service +# or +systemctl stop nfs-server +``` + +Per elencare tutte le unità attualmente caricate: + +``` +systemctl list-units --type service +``` + +Per elencare tutte le unità e per verificare se sono attivate: + +``` +systemctl list-unit-files --type service +``` + +``` +systemctl enable httpd.service +systemctl disable bluetooth.service +``` + +### Esempio di un file .service per il servizio postfix + +``` +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: + +``` +systemctl get-default +``` + +Questo comando cerca l'obiettivo del collegamento simbolico situato in `/etc/systemd/system/default.target` e visualizza il risultato. + +``` +$ systemctl get-default +graphical.target +``` + +Il comando `systemctl` può anche fornire un elenco di obiettivi disponibili: + +``` +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: + +``` +systemctl set-default name.target +``` + +Esempio: + +``` +# 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: + +``` +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: + +``` +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: + +``` +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. + +``` +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. + +``` +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: + +``` +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). From 169c3a9f7e04c0534ea2b04502b812f0fd63dc5e Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:46 -0500 Subject: [PATCH 10/37] New translations 11-tasks.md (French) --- docs/books/admin_guide/11-tasks.fr.md | 250 ++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 docs/books/admin_guide/11-tasks.fr.md diff --git a/docs/books/admin_guide/11-tasks.fr.md b/docs/books/admin_guide/11-tasks.fr.md new file mode 100644 index 0000000000..e29a964249 --- /dev/null +++ b/docs/books/admin_guide/11-tasks.fr.md @@ -0,0 +1,250 @@ +--- +title: Task Management +--- + +# Task Management + +In this chapter you will learn how to manage scheduled tasks. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: Linux deals with the tasks scheduling; +:heavy_check_mark: restrict the use of **`cron`** to certain users; +:heavy_check_mark: schedule tasks. + +:checkered_flag: **crontab**, **crond**, **scheduling**, **linux** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**Temps de lecture : **15 minutes + +**** + +## Generalities + +The scheduling of tasks is managed with the `cron` utility. It allows the periodic execution of tasks. + +It is reserved to the administrator for system tasks but can be used by normal users for tasks or scripts that they have access to. To access the `cron` utility, we use: `crontab`. + +The `cron` service is used for: + +* Repetitive administration operations; +* Backups; +* Monitoring of system activity; +* Program execution. + +`crontab` is short for **cron table**, but can be thought of as a task scheduling table. + +!!! Warning To set up a schedule, the system must have the correct time set. + +## How the service works + +The `cron` service is run by a `crond` daemon present in memory. + +To check its status: + +``` +[root] # systemctl status crond +``` + +!!! Tip If the `crond` daemon is not running, you will have to initialize it manually and/or automatically at startup. Indeed, even if tasks are scheduled, they will not be launched. + +Initialization of the `crond` daemon in manual: + +``` +[root]# systemctl {status|start|restart|stop} crond +``` + +Initialization of the `crond` daemon at startup: + +``` +[root]# systemctl enable crond +``` + +## Security + +In order to implement a schedule, a user must have permission to use the `cron` service. + +This permission varies according to the information contained in the files below: + +* `/etc/cron.allow` +* `/etc/cron.deny` + +!!! Warning If neither file is present, all users can use `cron`. + +### The `cron.allow` and `cron.deny` Files + +File `/etc/cron.allow` + +Only users contained in this file are allowed to use `cron`. + +If it exists and is empty, no users can use `cron`. + +!!! Warning If `cron.allow` is present, `cron.deny` is **ignored**. + +File `/etc/cron.deny` + +Users in this file are not allowed to use `cron`. + +If it is empty, all users can use `cron`. + +By default, `/etc/cron.deny` exists and is empty and `/etc/cron.allow` does not exist. + +### Allowing a user + +Only **user1** will be able to use `cron`. + +``` +[root]# vi /etc/cron.allow +user1 +``` + +### Prohibit a user +Only **user2** will not be able to use `cron`. + +``` +[root]# vi /etc/cron.deny +user2 +``` + +`cron.allow` must not be present. + +## Scheduling tasks + +When a user schedules a task, a file with his name is created under `/var/spool/cron/`. + +This file contains all the information the `crond` needs to know regarding all tasks created by this user, the commands or programs to run, and when to run them (hour, minute, day ...). + +![Cron tree](images/tasks-001.png) + +### The `crontab` command + +The `crontab` command is used to manage the schedule file. + +``` +crontab [-u user] [-e | -l | -r] +``` + +Example: + +``` +[root]# crontab -u user1 -e +``` + +| Option | Description | +| ------ | --------------------------------------------------------- | +| `-e` | Edit the schedule file with vi | +| `-l` | Displays the contents of the schedule file | +| `-u` | Name of the user whose schedule file is to be manipulated | +| `-r` | Delete the schedule file | + +!!! Warning `crontab` without option deletes the old schedule file and waits for the user to enter new lines. You have to press ctrl + d to exit this editing mode. + + Only `root` can use the `-u user` option to manage another user's schedule file. + + The example above allows root to schedule a task for user1. + +### Uses of `crontab` + +The uses of `crontab` are many and include: + +* Modifications to the `crontab` files taken into account immediately; +* No need to restart. + +On the other hand, the following points must be taken into account: + +* The program must be autonomous; +* Provide redirections (stdin, stdout, stderr); +* It is not relevant to run commands that use input/output requests on a terminal. + +!!! Note It is important to understand that the purpose of scheduling is to perform tasks automatically, without the need for external intervention. + +## The `crontab` file + +The `crontab` file is structured according to the following rules. + +* Each line of this file corresponds to a schedule; +* Each line has six fields, 5 for the time and 1 for the order; +* Each field is separated by a space or a tab; +* Each line ends with a carriage return; +* A `#` at the beginning of the line comments it. + +``` +[root]# crontab –e +10 4 1 * * /root/scripts/backup.sh +1 2 3 4 5 6 +``` + +| Field | Description | Detail | +| ----- | ------------------- | ------------------------ | +| 1 | Minute(s) | From 0 to 59 | +| 2 | Hour(s) | From 0 to 23 | +| 3 | Day(s) of the month | From 1 to 31 | +| 4 | Month of the year | From 1 to 12 | +| 5 | Day(s) of the week | From 0 to 7 (0=7=sunday) | +| 6 | Task to execute | Full command or script | + +!!! Warning The tasks to be executed must use absolute paths and if possible use redirects. + +In order to simplify the notation for the definition of time, it is advisable to use special symbols. + +| Wildcards | Description | +| --------- | -------------------------------- | +| `*` | All possible values of the field | +| `-` | Indicates a range of values | +| `,` | Indicates a list of values | +| `/` | Defines a step | + +Examples: + +Script executed on April 15 at 10:25 am: + +``` +25 10 15 04 * /root/scripts/script > /log/… +``` + +Run at 11am and then at 4pm every day: + +``` +00 11,16 * * * /root/scripts/script > /log/… +``` + +Run every hour from 11am to 4pm every day: + +``` +00 11-16 * * * /root/scripts/script > /log/… +``` + +Run every 10 minutes during working hours: + +``` +*/10 8-17 * * 1-5 /root/scripts/script > /log/… +``` + +For the root user, `crontab` also has some special time settings: + +| Setting | Description | +| --------- | -------------------------------------------------------------- | +| @reboot | Run command on system reboot | +| @hourly | Run command every hour | +| @daily | Runs daily just after midnight | +| @weekly | Runs command every Sunday just after midnight | +| @monthly | Runs command on the first day of the month just after midnight | +| @annually | Runs January 1st just after midnight | + +### Task execution process + +A user, rockstar, wants to edit his `crontab` file: + +1) `crond` checks to see if he is allowed (`/etc/cron.allow` and `/etc/cron.deny`). + +2) If he is, he accesses his `crontab` file (`/var/spool/cron/rockstar`). + +Every minute `crond` reads the schedule files. + +3) It executes the scheduled tasks. + +4) It reports systematically in a log file (`/var/log/cron`). From 417daf2ecc50c509eb9e1b306a3c5bec60a480bb Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:47 -0500 Subject: [PATCH 11/37] New translations 07-file-systems.md (Chinese Simplified) --- docs/books/admin_guide/07-file-systems.zh.md | 1068 ++++++++++++++++++ 1 file changed, 1068 insertions(+) create mode 100644 docs/books/admin_guide/07-file-systems.zh.md diff --git a/docs/books/admin_guide/07-file-systems.zh.md b/docs/books/admin_guide/07-file-systems.zh.md new file mode 100644 index 0000000000..2d95248273 --- /dev/null +++ b/docs/books/admin_guide/07-file-systems.zh.md @@ -0,0 +1,1068 @@ +--- +title: File System +--- + +# File System + +In this chapter you will learn how to work with filesystems. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: manage partitions on disk; +:heavy_check_mark: use LVM for a better use of disk resources; +:heavy_check_mark: provide users with a filesystem and manage the access rights. + +and also discover: + +:heavy_check_mark: how the tree structure is organized in Linux; +:heavy_check_mark: the different types of files offered and how to work with them; + +:checkered_flag: **hardware**, **disk**, **partition**, **lvm**, **linux** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**阅读时间**: 20 分钟 + +**** + +## Partitioning + +Partitioning will allow the installation of several operating systems because it is impossible to have several of them cohabit on the same logical drive. Partitioning also allows the separation of data logically (security, access optimization, ...). + +The division of the physical disk into partitioned volumes is recorded in the partition table, stored in the first sector of the disk (MBR: _Master Boot Record_). + +The same physical disk can be divided into a maximum of 4 partitions: + +* *Primary* (or main) +* *Extended* + +!!! Warning There can be only one extended partition per physical disk. In order to benefit from additional drives, the extended partition can be split into logical partitions + +![Breakdown into only 4 primary partitions](images/07-file-systems-001.png) + +![Breakdown into 3 primary partitions and one extended](images/07-file-systems-002.png) + +The _devices_ are the files identifying the various hardware detected by the motherboard. These files are stored without `/dev`. The service which detects new devices and gives them names is called *udev*. + +They are identified by their type. + +Storage devices are named *hd* for IDE hard drives and *sd* for other media. Then comes a letter that starts with *a* for the first device, then *b*, *c*, ... + +Finally we will find a number that defines the partitioned volume: *1* for the first primary partition, ... + +!!! Warning Beware, the extended partition, which does not support a file system, still has a number. + +![Identification of partitions](images/07-file-systems-003.png) + +There are at least two commands for partitioning a disk: `fdisk` and `cfdisk`. Both commands have an interactive menu. `cfdisk` is more reliable and better optimized, so it is best to use it. + +The only reason to use `fdisk` is when you want to list all logical devices with the `-l` option. + +``` +sudo fdisk -l +sudo fdisk -l /dev/sdc +sudo fdisk -l /dev/sdc2 +``` + +### `parted` command + +The `parted` (_partition editor_) command is able to partition a disk. + +``` +parted [-l] [device] +``` + +It also has a recovery function capable of rewriting a deleted partition table. + +Under graphical interface, there is the very complete `gparted` tool: *G*nome *PAR*tition *ED*itor. + +The `gparted -l` command lists all logical devices on a computer. + +The `gparted` command alone will return to an interactive mode with its own internal options: + +* `help` or an incorrect command will display these options. +* `print all` in this mode will have the same result as `gparted -l` on the command line. +* `quit` to return to the prompt. + +### `cfdisk` command + +The `cfdisk` command is used to manage partitions. + +``` +cfdisk device +``` + +Example: + +``` +$ sudo cfdisk /dev/sda + Disk: /dev/sda + Size: 16 GiB, 17179869184 bytes, 33554432 sectors + Label: dos, identifier: 0xcf173747 + Device Boot Start End Sectors Size Id Type +>> /dev/sda1 * 2048 2099199 2097152 1G 83 Linux + /dev/sda2 2099200 33554431 31455232 15G 8e Linux LVM + lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk + x Partition type: Linux (83) x + x Attributes: 80 x + xFilesystem UUID: 54a1f5a7-b8fa-4747-a87c-2dd635914d60 x + x Filesystem: xfs x + x Mountpoint: /boot (mounted) x + mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj + [Bootable] [ Delete ] [ Resize ] [ Quit ] [ Type ] [ Help ] + [ Write ] [ Dump ] +``` + +The preparation, without _LVM_, of the physical media goes through five steps: + +* Setting up the physical disk; +* Partitioning of the volumes (geographical division of the disk, possibility of installing several systems, ...); +* Creation of the file systems (allows the operating system to manage the files, the tree structure, the rights, ...); +* Mounting of file systems (registration of the file system in the tree structure); +* Manage user access. + +## Logical Volume Manager (LVM) + +**L**ogical **V**olume **M**anager (*LVM]*) + +Volume management creates an abstract layer on top of physical storage, offering advantages over using physical storage directly: + +* More flexible disk capacity; +* Online data movement; +* Disks in _stripe_ mode; +* Mirrored volumes (recopy); +* Volume snapshots (_snapshot_). + +The disadvantage is that if one of the physical volumes becomes out of order, then all the logical volumes that use this physical volume are lost. You will have to use LVM on raid disks. + +LVM is available under Linux from kernel version 2.4. + +!!! Note LVM is only managed by the operating system. Therefore the _BIOS_ needs at least one partition without LVM to boot. + +### Volume groups + +The physical volumes *PV* _Physical Volumes_ (from partitions) are combined into volume groups *VG*. Each *VG* represents disk space that can be partitioned into *LV* _Logical Volumes_. *Extension* is the smallest unit of fixed-size space that can be allocated. + +* **PE** : _Physical Extension_ +* **LE** : _Logical Extension_ + +![Volume group, PE size equal to 4MB](images/07-file-systems-004.png) + +### Logical volumes + +A volume group, *VG*, is divided into logical volumes, *LV*, offering different operating modes: + +* Linear volumes; +* Volumes in _stripe_ mode; +* Mirrored volumes. + +![Linear volumes](images/07-file-systems-005.png) + +![Volumes in stripe mode](images/07-file-systems-006.png) + +!!! Tip Striping_ improves performance by writing data to a predetermined number of physical volumes with a _round-robin_ technique. + +![Mirrored volumes](images/07-file-systems-007.png) + +### LVM commands for volume management + +#### `pvcreate` command + +The `pvcreate` command is used to create physical volumes. It turns Linux partitions (or disks) into physical volumes. + +``` +pvcreate [-options] partition +``` + +Example: + +``` +[root]# pvcreate /dev/hdb1 +pvcreate -- physical volume « /dev/hdb1 » successfully created +``` + +You can also use a whole disk (which facilitates disk size increases in virtual environments for example). + +``` +[root]# pvcreate /dev/hdb +pvcreate -- physical volume « /dev/hdb » successfully created +``` + +| Option | Description | +| ------ | ---------------------------------------------------------------------------------- | +| `-f` | Forces the creation of the volume (disk already transformed into physical volume). | + +#### `vgcreate` command + +The `vgcreate` command is used to create volume groups. It groups one or more physical volumes into a volume group. + +``` +vgcreate volume physical_volume [PV...] +``` + +Example: + +``` +[root]# vgcreate volume1 /dev/hdb1 +… +vgcreate – volume group « volume1 » successfully created and activated +``` + +#### `lvcreate` command + +The `lvcreate` command creates logical volumes. The file system is then created on these logical volumes. + +``` +lvcreate -L size [-n name] VG_name +``` + +Example: + +``` +[root]# lvcreate –L 600M –n VolLog1 volume1 +lvcreate -- logical volume « /dev/volume1/VolLog1 » successfully created +``` + +| Option | Description | +| --------- | ------------------------------------------------------------------- | +| `-L size` | Logical volume size in K, M or G. | +| `-n name` | LV name. Special file created in `/dev/name_volume` with this name. | + +### LVM commands to view volume information + +#### `pvdisplay` command + +The `pvdisplay` command allows you to view information about the physical volumes. + +``` +pvdisplay /dev/PV_name +``` + +Example: + +``` +[root]# pvdisplay /dev/PV_name +``` + +#### `vgdisplay` command + +The `vgdisplay` command allows you to view information about volume groups. + +``` +vgdisplay VG_name +``` + +Example: + +``` +[root]# vgdisplay volume1 +``` + +#### `lvdisplay` command + +The `lvdisplay` command allows you to view information about the logical volumes. + +``` +lvdisplay /dev/VG_name/LV_name +``` + +Example: + +``` +[root]# lvdisplay /dev/volume1/VolLog1 +``` + +### Preparation of the physical media + +The preparation with LVM of the physical support is broken down as follows: + +* Setting up the physical disk +* Partitioning of the volumes +* **LVM physical volume** +* **LVM volume groups** +* **LVM logical volumes** +* Creating file systems +* Mounting file systems +* Manage user access + +## Structure of a file system + +A _file system_ **FS** is in charge of the following actions: + +* Securing access and modification rights to files; +* Manipulating files: create, read, modify and delete; +* Locating files on the disk; +* Managing partition space. + +The Linux operating system is able to use different file systems (ext2, ext3, ext4, FAT16, FAT32, NTFS, HFS, BtrFS, JFS, XFS, ...). + +### `mkfs` command + +The `mkfs` command allows you to create a Linux file system. + +``` +mkfs [-t fstype] filesys +``` + +Example: + +``` +[root]# mkfs -t ext4 /dev/sda1 +``` + +| Option | Description | +| ------ | ----------------------------------------- | +| `-t` | Indicates the type of file system to use. | + +!!! Warning Without a file system it is not possible to use the disk space. + +Each file system has a structure which is identical on each partition. A **boot block** and a **super block** initialized by the system and then an **inode table** and a **data area** initialized by the administrator. + +!!! Note The only exception is the **swap** partition. + +### Boot block + +The **boot block** occupies the first block on the disk and is present on all partitions. It contains the program that starts and initializes the system and is therefore only filled in for the boot partition. + +### Super block + +The size of the **super block** table is defined at creation. It is present on each partition and contains the elements necessary for its utilization. + +It describes the File System: + +* Name of the Logical Volume; +* Name of the File System; +* Type of the File System; +* File System Status; +* Size of the File System; +* Number of free blocks; +* Pointer to the beginning of the list of free blocks; +* Size of the inode list; +* Number and list of free inodes. + +A copy is loaded in the central memory as soon as the system is initialized. This copy is updated as soon as it is modified and the system saves it periodically (command `sync`). + +When the system stops, it also copies this table in memory to its block. + +### Table of inodes + +The size of the **inode table** is defined at its creation and is stored on the partition. It consists of records, called inodes, corresponding to the files created. Each record contains the addresses of the data blocks making up the file. + +!!! Note An inode number is unique within a file system. + +A copy is loaded in the central memory as soon as the system is initialized. This copy is updated as soon as it is modified and the system saves it periodically (command `sync`). + +When the system stops, it also copies this table in memory to its block. + +A file is managed by its inode number. + +!!! Note The size of the inode table determines the maximum number of files the FS can contain. + +Information present in the *inode table* : + +* Inode number; +* File type and access permissions; +* Owner identification number; +* Identification number of the owner group; +* Number of links on this file; +* Size of the file in bytes; +* Date the file was last accessed; +* Date the file was last modified; +* Date of the last modification of the inode (= creation); +* Table of several pointers (block table) to the logical blocks containing the pieces of the file. + +### Data area + +Its size corresponds to the rest of the available space of the partition. This area contains the catalogs corresponding to each directory and the data blocks corresponding to the contents of the files. + +**In order to guarantee the consistency of the file system**, an image of the superblock and the inode table is loaded into memory (RAM) when the operating system is loaded so that all I/O operations are done through these system tables. When the user creates or modifies files, this memory image is updated first. The operating system must therefore regularly update the superblock of the logical disk (`sync` command). + +These tables are written to the hard disk when the system is shut down. + +!!! Danger In the event of a sudden stop, the file system may lose its consistency and cause data loss. + +### Repairing the file system + +It is possible to check the consistency of a file system with the `fsck` command. + +In case of errors, solutions are proposed to repair the inconsistencies. After repair, files that remain without entries in the inode table are attached to the `/lost+found` folder of the logical drive. + +#### `fsck` command + +The `fsck` command is a console-mode integrity check and repair tool for Linux file systems. + +``` +fsck [-sACVRTNP] [ -t fstype ] filesys +``` + +Example: + +``` +[root]# fsck /dev/sda1 +``` + +To check the root partition, it is possible to create a `forcefsck` file and reboot or run `shutdown` with the `-F` option. + +``` +[root]# touch /forcefsck +[root]# reboot +or +[root]# shutdown –r -F now +``` + +!!! Warning The partition to be checked must be unmounted. + +## Organization of a file system + +By definition, a File System is a tree structure of directories built from a root directory (a logical device can only contain one file system). + +![Organization of a file system](images/07-file-systems-008.png) + +!!! Note In Linux everything is a file. + +Text document, directory, binary, partition, network resource, screen, keyboard, Unix kernel, user program, ... + +Linux meets the **FHS** (_Filesystems Hierarchy Standard_) (see `man hier`) which defines the names of folders and their roles. + +| Directory | Observation | Abbreviation of | +| ---------- | ------------------------------------------------------------- | ----------------------------- | +| `/` | Contains special directories | | +| `/boot` | Files related to system startup | | +| `/sbin` | Commands necessary for system startup and repair | _system binaries_ | +| `/bin` | Executables of basic system commands | _binaries_ | +| `/usr/bin` | System administration commands | | +| `/lib` | Shared libraries and kernel modules | _libraries_ | +| `/usr` | Everything that is not necessary for minimal system operation | _UNIX System Resources_ | +| `/mnt` | For mounting temporary SF | _mount_ | +| `/media` | For mounting removable media | | +| `/root` | Administrator's login directory | | +| `/home` | User data | | +| `/tmp` | Temporary files | _temporary_ | +| `/dev` | Special device files | _device_ | +| `/etc` | Configuration and script files | _editable text configuration_ | +| `/opt` | Specific to installed applications | _optional_ | +| `/proc` | Virtual file system representing different processes | _processes_ | +| `/var` | Miscellaneous variable files | _variables_ | + +* To perform a mount or unmount, at the tree level, you must not be under its mount point. +* Mounting on a non-empty directory does not delete the content. It is only hidden. +* Only the administrator can perform mounts. +* Mount points to be automatically mounted at boot time must be entered in `/etc/fstab`. + +### `/etc/fstab` file + +The `/etc/fstab` file is read at system startup and contains the mounts to be performed. Each file system to be mounted is described on a single line, the fields being separated by spaces or tabs. + +!!! Note Lines are read sequentially (`fsck`, `mount`, `umount`). + +``` +/dev/mapper/VolGroup-lv_root / ext4 defaults 1 1 +UUID=46….92 /boot ext4 defaults 1 2 +/dev/mapper/VolGroup-lv_swap swap swap defaults 0 0 +tmpfs /dev/shm tmpfs defaults 0 0 +devpts /dev/pts devpts gid=5,mode=620 0 0 +sysfs /sys sysfs defaults 0 0 +proc /proc proc defaults 0 0 + 1 2 3 4 5 6 +``` + +| Column | Description | +| ------ | ------------------------------------------------------------------------------------------------- | +| 1 | File system device (`/dev/sda1`, UUID=..., ...) | +| 2 | Mount point name, **absolute path** (except **swap**) | +| 3 | Filesystem type (ext4, swap, ...) | +| 4 | Special options for mounting (`defaults`, `ro`, ...) | +| 5 | Enable or disable backup management (0:not backed up, 1:backed up) | +| 6 | Check order when checking the SF with the `fsck` command (0:no check, 1:priority, 2:not priority) | + +The `mount -a` command allows new mounts to be taken into account without rebooting. They are then written to the `/etc/mtab` file which contains the current mounts. + +!!! Warning Only the mount points listed in `/etc/fstab` will be mounted on reboot. + +It is possible to make a copy of the `/etc/mtab` file or to copy its contents to `/etc/fstab`. + +### Mount management commands + +#### `mount` command + +The `mount` command allows you to mount and view the logical drives in the tree. + +``` +mount [-option] [device] [directory] +``` + +Example: + +``` +[root]# mount /dev/sda7 /home +``` + +| Option | Description | +| ------ | ------------------------------------------------------------------------------ | +| `-n` | Mount without writing to `/etc/mtab`. | +| `-t` | To indicate the type of file system to use. | +| `-a` | Mounts all filesystems mentioned in `/etc/fstab`. | +| `-r` | Mounts the file system read-only (equivalent to `-o ro`). | +| `-w` | Mounts the file system read/write, by default (equivalent `-o rw`). | +| `-o` | Argument followed by a comma-separated list of options (`remount`, `ro`, ...). | + +!!! Note The `mount` command alone displays all mounted file systems. + +#### `umount` command + +The `umount` command is used to unmount logical drives. + +``` +umount [-option] [device] [directory] +``` + +Example: + +``` +[root]# umount /home +[root]# umount /dev/sda7 +``` + +| Option | Description | +| ------ | -------------------------------------------------- | +| `-n` | Unmount without writing to `/etc/mtab`. | +| `-r` | If unmount fails, remount as read-only. | +| `-f` | Force unmount. | +| `-a` | Unmount all filesystems mentioned in `/etc/fstab`. | + +!!! Note When disassembling, you must not stay below the mounting point. Otherwise, the following error message is displayed: `device is busy`. + +## Types of files + +As in any system, in order to be able to find one's way through the tree structure and the file management, it is important to respect the file naming rules. + +* Files are coded on 255 characters; +* All ASCII characters can be used; +* Uppercase and lowercase letters are differentiated; +* No notion of extension. + +Groups of words separated by spaces must be enclosed in quotation marks: + +``` +[root]# mkdir "working dir" +``` + +!!! Note While there is nothing technically wrong with creating a file or directory with a space in it, it is generally a "best practice" to avoid this and replace any space with an underscore. + +!!! Note The **.** at the beginning of the file name only serves to hide it from a simple `ls`. + +!!! Warning Under Linux, the extension of a file is not a necessary reference to open or modify it. However, it can be useful for the user. + +Examples of extension agreements: + +* `.c` : source file in C language; +* `.h` : C and Fortran header file; +* `.o` : object file in C language; +* `.tar` : data file archived with the `tar` utility; +* `.cpio` : data file archived with the `cpio` utility; +* `.gz` : data file compressed with the `gzip` utility; +* `.tgz` : data file archived with the `tar` utility and compressed with the `gzip` utility; +* `.html` : web page. + +### Details of a file name + +``` +[root]# ls -liah /usr/bin/passwd +266037 -rwsr-xr-x 1 root root 59K mars 22 2019 /usr/bin/passwd +1 2 3 4 5 6 7 8 9 +``` + +| Row | Description | +| --- | ---------------------------------------------------------- | +| `1` | Inode number | +| `2` | File type (1st character of the block of 10) | +| `3` | Access rights (last 9 characters of the block of 10) | +| `4` | Number of links (ordinary) or subdirectories (directories) | +| `5` | Name of the owner | +| `6` | Name of the group | +| `7` | Size (byte, kilo, mega) | +| `8` | Date of last update | +| `9` | Name of the file | + +### Different types of files + +The following types of files can be found on a system: + +* Ordinary (text, binary, ...); +* Directories; +* Special (printers, screens, ...); +* Links; +* Communications (tubes and socket). + +#### Ordinary files + +These are text, program (source), executable (after compilation) or data (binary, ASCII) and multimedia files. + +``` +[root]# ls -l myfile +-rwxr-xr-x 1 root root 26 nov 31 15:21 myfile +``` + +The dash `-` at the beginning of the rights group (10-character block) indicates that it is an ordinary file type. + +#### Directory files + +Directory files contain references to other files. + +By default in each directory are present **.** and **..**. + +* The **.** represents the position in the tree. +* The **..** represents the father of the current position. + +``` +[root]# ls -l mydirectory +drwxr-xr-x 1 root root 26 nov 31 15:21 mydirectory +``` + +The letter `d` at the beginning of the rights group indicates that it is a directory type file. + +#### Special files + +In order to communicate with peripherals (hard disks, printers, ...), Linux uses interface files called special files (_device file_ or _special file_). They allow identification by the peripherals. + +These files are special because they do not contain data but specify the access mode to communicate with the device. + +They are defined in two modes: + +* **block** mode; +* **character** mode. + +##### Block mode + +The special **block mode** file allows, using the system buffers, to transfer data to the device. + +``` +[root]# ls -l /dev/sda +brw------- 1 root root 8, 0 jan 1 1970 /dev/sda +``` + +The letter `b` at the beginning of the rights group indicates that it is a special file **block**. + +##### Character mode + +The special *character mode* file is used to transfer data to the device as a stream of one character at a time without using a buffer. These are devices like printer, screen or DAT tapes, ... + +The standard output is the screen. + +``` +[root]# ls -l /dev/tty0 +crw------- 1 root root 8, 0 jan 1 1970 /dev/tty0 +``` + +The letter `c` at the beginning of the rights group indicates that it is a special character file. + +#### Communication files + +These are the pipe (_pipes_) and the _socket_ files. + +* **Pipe files** pass information between processes by FIFO (_First In, First Out_). One process writes transient information to a _pipe_ file and another reads it. After reading, the information is no longer accessible. + +* **Socket files** allow bidirectional inter-process communication (on local or remote systems). They use an _inode_ of the file system. + +#### Link files + +These files give the possibility to give several logical names to the same physical file. A new access point to the file is therefore created. + +There are two types of link files: + +* Physical links; +* Symbolic links. + +##### Physical link + +The link file and the source file have the same _inode_ number and the link counter is incremented. It is not possible to link different directories or files from different file systems. + +!!! Warning If the source file is destroyed, the counter is decremented and the link file still accesses the file. + +###### Command `ln` for a physical link + +The `ln` command allows you to create physical links. + +``` +[root]# ls –li letter +666 –rwxr--r-- 1 root root … letter +``` + +``` +[root]# ln /home/paul/letter /home/jack/read +``` + +``` +[root]# ls –li /home/*/* +666 –rwxr--r-- 2 root root … letter +666 –rwxr--r-- 2 root root … read +``` + +![Representation of a physical link](images/07-file-systems-009.png) + +##### Symbolic link + +Unlike the physical link, the symbolic link involves the creation of a new _inode_. At the symbolic link level, only a path is stored in the inode table. + +The file created contains only an indication of the path to the file. This notion no longer has the limitations of physical links and it is now possible to link directories and files belonging to different file systems. + +!!! Warning If the source file is destroyed, the link file can no longer access the file. + +###### `ln` command for a symbolic link + +The command `ln` with the argument `-s` allows to create symbolic links. + +``` +[root]# ls –li letter +666 -rwxr--r-- 1 root root … letter +``` + +``` +[root]# ln -s /home/paul/letter /tmp/read +``` + +``` +[root]# ls –li /home/paul/letter /tmp/read +666 -rwxr--r--- 1 root root … letter +678 lrwxrwxrwx 1 root root … read -> letter +``` + +![Representation of a symbolic link](images/07-file-systems-010.png) + +## File attributes + +Linux is a multi-user operating system where the control of access to files is essential. + +These controls are functions of: + +* file access permissions ; +* users (_ugo_ _Users Groups Others_). + +The command `ls -l` allows to display the attributes. + +There are 4 file access rights: + +* **r**ead; +* **w**rite; +* e**x**ecution; +* **-** no right. + +!!! Warning The rights associated with files differ from those associated with directories (see below). + +The user types associated with file access rights are: + +* **u**ser_ (owner) ; +* **g**roup_ (owner group); +* **o**thers (others users); + +In some commands it is possible to designate everyone with **a** (_all_). + +**a = ugo** + +### Rights associated with ordinary files + +* **r**ead: Allows reading a file (`cat`, `less`, ...) and copying a file (`cp`, ...). +* **w**rite: Allows modification of the file content (`cat`, `>>`, `vim`, ...). +* e**x**ecute: Considers the file as an e**X**ecutable (binary or script). +* **-**: No permissions. + +!!! Note Moving or renaming a file depends on the rights of the target directory. Deleting a file depends on the rights of the parent directory. + +### Rights associated with directories + +* **r**ead: Allows reading the contents of a directory (`ls -R`). +* **w**rite: Allows modification of the contents of a directory (`touch`) and allows creation and deletion of files if the **x** permission is enabled. +* e**x**ecute: Allows descending in the directory (`cd`). +* **-**: No rights. + +### Attribute management + +The display of rights is done with the command `ls -l`. It is the last 9 characters of the block of 10. More precisely 3 times 3 characters. + +``` +[root]# ls -l /tmp/myfile +-rwxrw-r-x 1 root sys ... /tmp/myfile + 1 2 3 4 5 +``` + +| Row | Description | +| --- | ------------------------------------------------- | +| 1 | Owner (**u**ser) permissions, here `rwx` | +| 2 | Owner group permissions (**g**roup), here `rw-` | +| 3 | Other users' permissions (**o**thers), here `r-x` | +| 4 | File owner | +| 5 | Group owner of the file | + +!!! Note Permissions apply to **u**ser, **g**roup and **o**ther (**ugo**) depending on the owner and group. + +By default, the _owner_ of a file is the one who creates it. The _group_ of the file is the group of the owner who created the file. The _others_ are those which are not concerned by the previous cases. + +The attributes are changed with the `chmod` command. + +Only the administrator and the owner of a file can change the rights of a file. + +#### `chmod` command + +The `chmod` command allows you to change the access permissions to a file. + +``` +chmod [option] mode file +``` + +The mode indication can be an octal representation (e.g. `744`) or a symbolic representation ([`ugoa`][`+=-`][`rwxst`]). + +Several symbolic operations can be separated by commas + +Example: + +``` +[root]# chmod -R u+rwx,g+wx,o-r /tmp/file1 +[root]# chmod g=x,o-r /tmp/file2 +[root]# chmod -R o=r /tmp/file3 +``` + +``` +[root]# ls -l /tmp/fic* +-rwxrwx--- 1 root root … /tmp/file1 +-rwx--x--- 1 root root … /tmp/file2 +-rwx--xr-- 1 root root … /tmp/file3 +``` + +``` +[root]# chmod 741 /tmp/file1 +[root]# chmod -R 744 /tmp/file2 +[root]# ls -l /tmp/fic* +-rwxr----x 1 root root … /tmp/file1 +-rwxr--r-- 1 root root … /tmp/file2 +``` + +| Option | Observation | +| ------ | --------------------------------------------------------------------- | +| `-R` | Recursively modify the permissions of directories and their contents. | + +There are two methods for making rights changes: + +* The **octal** method; +* The **symbolic** method. + +!!! Warning The rights of files and directories are not dissociated. For some operations, it will be necessary to know the rights of the directory containing the file. A write-protected file can be deleted by another user as long as the rights of the directory containing it allow this user to perform this operation. + +#### Principle of the octal method + +Each right has a value. + +![Octal method](images/07-file-systems-011.png) + +``` +[root]# ls -l /tmp/myfile +-rwxrwxrwx 1 root root ... /tmp/myfile +``` + +![Rights 777](images/07-file-systems-012.png) + +``` +[root]# chmod 741 /tmp/myfile +-rwxr----x 1 root root ... /tmp/myfile +``` + +![Rights 741](images/07-file-systems-013.png) + +#### Principle of the symbolic method + +This method can be considered as a "literal" association between a user type, an operator, and rights. + +![Symbolic method](images/07-file-systems-014.png) + +``` +[root]# chmod u+rwx,g+wx,o-r /tmp/myfile +[root]# chmod g=x,o-r /tmp/myfile +[root]# chmod o=r /tmp/myfile +``` + +``` +[root]# ls -l /tmp/myfile +r--r-- 1 root root … /tmp/myfile +``` + +``` +[root]# chmod u+rwx,g+wx,o-r /tmp/myfile +``` + +``` +[root]# ls -l /tmp/myfile +-rwxrwx--- 1 root root … /tmp/myfile +``` + +### Special rights + +In addition to the fundamental rights (`rwx`), there are the particular rights: + +* **set-user-ID** (_SUID]_) +* **set-group-ID** (_SGID]_) +* **sticky-bit** + +As with the fundamental rights, the particular rights each have a value. This value is placed before the `ugo` set of rights. + +![Special rights](images/07-file-systems-015.png) + +!!! Danger `S`, `S` and `T` in capital letters **if the right does not exist**. + +#### The sticky-bit + +One of the peculiarities of rights in Linux is that the right to write to a directory also allows deletion of *all* files, owner or not. + +The _sticky-bit_ set on the directory will only allow users to delete files they own. This is the basic case for the `/tmp` directory. + +The setting of the _sticky-bit_ can be done as follows: + +Octal method: +``` +[root]# chmod 1777 directory +``` + +Symbolic method: +``` +[root]# chmod o+t directory +``` + +Verification: +``` +[root]# ls -l +drwxrwxrwt … directory +``` + +#### SUID and SGID on a command + +These rights allow execution of a command according to the rights set on the command, and not according to the user's rights. + +The command is executed with the identity of the owner (_SUID_) or the group (_SGID_) of the command. + +!!! Note The identity of the user requesting the execution of the order is no longer taken into account. + + This is an additional possibility of access rights assigned to a user when it is necessary for them to have the same rights as the owner of a file or those of the group concerned. + +Indeed, a user may have to run a program (usually a system utility) but not have the necessary access rights. By setting the appropriate rights (**s** at the owner level and/or at the group level), the user of the program has, for the time of its execution, the identity of the owner (or that of the group) of the program. + +Example: + +The file `/usr/bin/passwd` is an executable file (a command) with a _SUID_. + +When the user _bob_ runs it, he will have to access the `/etc/shadow` file, but the permissions on this file do not allow _bob_ to access it. + +Having a _SUID_ this command, `/usr/bin/passwd`, will be executed with the _UID_ of root and the _GID_ of _root_. The latter being the owner of the `/etc/shadow` file, he will have read rights. + +![How the SUID works](images/07-file-systems-016.png) + +The setting of _SUID_ and _SGID_ can be done as below with the command `chmod`: + +Octal method: +``` +[root]# chmod 4777 command1 +[root]# chmod 2777 command2 +``` + +Symbolic method: +``` +[root]# chmod u+s command1 +[root]# chmod g+s command2 +``` + +Verification: +``` +[root]# ls -l +-rwsrwxrwx … command1 +-rwxrwsrwx … command2 +``` + +!!! Warning It is not possible to pass the _SUID_ or _SGID_ to a shell script. The system does not allow it because it is too dangerous for security! + +#### SGID on a file + +In a directory with the _SGID_ right, any file created will inherit the group that owns the directory instead of that of the creating user. + +Example: +``` +[rockstar] $ ls -ld /data/ +drwxrwsr-x 2 root users 4096 26 oct. 19:43 /data +``` + +``` +[rockstar] $ touch /data/test_sgid /tmp/fic_reference +``` + +``` +[rockstar] $ ls -ld /data/test_sgid /tmp/fic_reference +-rw-r--r--. 1 rockstar users 0 26 oct. 19:43 /data/test_sgid <1> +-rw-r--r--. 1 rockstar rockstar 0 26 oct. 19:43 /tmp/fic_ref +``` + +<1> The `test_sgid` file inherits the group owner of its `/data` folder (in this case `users`) whatever the main group of the `rockstar` user is. + +## Default rights and mask + +When a file or directory is created, it already has permissions. + +* For a directory: `rwxr-xr-x` or _755_. +* For a file: `rw-r-r-` or _644_. + +This behavior is defined by the **default mask**. + +The principle is to remove the value defined by the mask at maximum rights without the execution right. + +For a directory : + +![How the SUID works](images/07-file-systems-017.png) + +For a file, the execution rights are removed: + +![Default rights of a file](images/07-file-systems-018.png) + +### `umask` command + +The `umask` command allows you to display and modify the mask. + +``` +umask [option] [mode] +``` + +Example: +``` +$ umask 033 +$ umask +0033 +$ umask -S +u=rwx,g=r,o=r +$ touch umask_033 +$ ls -la umask_033 +-rw-r--r-- 1 rockstar rockstar 0 nov. 4 16:44 umask_033 +$ umask 025 +$ umask -S +u=rwx,g=rx,o=w +$ touch umask_025 +$ ls -la umask_025 +-rw-r---w- 1 rockstar rockstar 0 nov. 4 16:44 umask_025 +``` + +| Option | Description | +| ------ | -------------------------------- | +| `-S` | Symbolic display of file rights. | + +!!! Warning `umask` does not affect existing files. + +!!! Note `umask` modifies the mask until the disconnection. + +To keep the value, you have to modify the following profile files: For all users: + +* `/etc/profile` +* `/etc/bashrc` + +For a particular user: + +* `~/.bashrc` + +!!! Warning `umask -S` displays the file rights (without the execute right) of the files that will be created. So it is not the display of the mask used to subtract the maximum value. + +!!! Tip The `umask` command being a _bash_ command, (a `type umask` returns `umask is a shell primitive`) you have to search `umask` in `man bash`. From ab0aaca8f63a7ea6ad94868962fffac31d8571c6 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:48 -0500 Subject: [PATCH 12/37] New translations 11-tasks.md (Italian) --- docs/books/admin_guide/11-tasks.it.md | 250 ++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 docs/books/admin_guide/11-tasks.it.md diff --git a/docs/books/admin_guide/11-tasks.it.md b/docs/books/admin_guide/11-tasks.it.md new file mode 100644 index 0000000000..4f1d8430b9 --- /dev/null +++ b/docs/books/admin_guide/11-tasks.it.md @@ -0,0 +1,250 @@ +--- +title: Gestione dei compiti +--- + +# 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: + +``` +[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`: + +``` +[root]# systemctl {status|start|restart|stop} crond +``` + +Initializzazione del demone `crond` all'avvio del sistema: + +``` +[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`. + +``` +[root]# vi /etc/cron.allow +user1 +``` + +### Proibire ad un utente +Solo **user2** non sarà in grado di usare `cron`. + +``` +[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. + +``` +crontab [-u user] [-e | -l | -r] +``` + +Esempio: + +``` +[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. + +``` +[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: + +``` +25 10 15 04 * /root/scripts/script > /log/… +``` + +Esegui alle 11am e quindi alle 4pm di ogni giorno: + +``` +00 11,16 * * * /root/scripts/script > /log/… +``` + +Esegui ogni ora dalle 11am alle 4pm di ogni giorno: + +``` +00 11-16 * * * /root/scripts/script > /log/… +``` + +Esegui ogni 10 minuti durante l'orario di lavoro: + +``` +*/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`). From 13cdf718a2bbb8b1cfa44ef6de4531a9c58ee9a5 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:49 -0500 Subject: [PATCH 13/37] New translations 11-tasks.md (Chinese Simplified) --- docs/books/admin_guide/11-tasks.zh.md | 250 ++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 docs/books/admin_guide/11-tasks.zh.md diff --git a/docs/books/admin_guide/11-tasks.zh.md b/docs/books/admin_guide/11-tasks.zh.md new file mode 100644 index 0000000000..1b2f7c4912 --- /dev/null +++ b/docs/books/admin_guide/11-tasks.zh.md @@ -0,0 +1,250 @@ +--- +title: Task Management +--- + +# Task Management + +In this chapter you will learn how to manage scheduled tasks. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: Linux deals with the tasks scheduling; +:heavy_check_mark: restrict the use of **`cron`** to certain users; +:heavy_check_mark: schedule tasks. + +:checkered_flag: **crontab**, **crond**, **scheduling**, **linux** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**阅读时间**: 15 分钟 + +**** + +## 概论 + +The scheduling of tasks is managed with the `cron` utility. It allows the periodic execution of tasks. + +It is reserved to the administrator for system tasks but can be used by normal users for tasks or scripts that they have access to. To access the `cron` utility, we use: `crontab`. + +The `cron` service is used for: + +* Repetitive administration operations; +* Backups; +* Monitoring of system activity; +* Program execution. + +`crontab` is short for **cron table**, but can be thought of as a task scheduling table. + +!!! Warning To set up a schedule, the system must have the correct time set. + +## How the service works + +The `cron` service is run by a `crond` daemon present in memory. + +To check its status: + +``` +[root] # systemctl status crond +``` + +!!! Tip If the `crond` daemon is not running, you will have to initialize it manually and/or automatically at startup. Indeed, even if tasks are scheduled, they will not be launched. + +Initialization of the `crond` daemon in manual: + +``` +[root]# systemctl {status|start|restart|stop} crond +``` + +Initialization of the `crond` daemon at startup: + +``` +[root]# systemctl enable crond +``` + +## Security + +In order to implement a schedule, a user must have permission to use the `cron` service. + +This permission varies according to the information contained in the files below: + +* `/etc/cron.allow` +* `/etc/cron.deny` + +!!! Warning If neither file is present, all users can use `cron`. + +### The `cron.allow` and `cron.deny` Files + +File `/etc/cron.allow` + +Only users contained in this file are allowed to use `cron`. + +If it exists and is empty, no users can use `cron`. + +!!! Warning If `cron.allow` is present, `cron.deny` is **ignored**. + +File `/etc/cron.deny` + +Users in this file are not allowed to use `cron`. + +If it is empty, all users can use `cron`. + +By default, `/etc/cron.deny` exists and is empty and `/etc/cron.allow` does not exist. + +### Allowing a user + +Only **user1** will be able to use `cron`. + +``` +[root]# vi /etc/cron.allow +user1 +``` + +### Prohibit a user +Only **user2** will not be able to use `cron`. + +``` +[root]# vi /etc/cron.deny +user2 +``` + +`cron.allow` must not be present. + +## Scheduling tasks + +When a user schedules a task, a file with his name is created under `/var/spool/cron/`. + +This file contains all the information the `crond` needs to know regarding all tasks created by this user, the commands or programs to run, and when to run them (hour, minute, day ...). + +![Cron tree](images/tasks-001.png) + +### The `crontab` command + +The `crontab` command is used to manage the schedule file. + +``` +crontab [-u user] [-e | -l | -r] +``` + +Example: + +``` +[root]# crontab -u user1 -e +``` + +| Option | Description | +| ------ | --------------------------------------------------------- | +| `-e` | Edit the schedule file with vi | +| `-l` | Displays the contents of the schedule file | +| `-u` | Name of the user whose schedule file is to be manipulated | +| `-r` | Delete the schedule file | + +!!! Warning `crontab` without option deletes the old schedule file and waits for the user to enter new lines. You have to press ctrl + d to exit this editing mode. + + Only `root` can use the `-u user` option to manage another user's schedule file. + + The example above allows root to schedule a task for user1. + +### Uses of `crontab` + +The uses of `crontab` are many and include: + +* Modifications to the `crontab` files taken into account immediately; +* No need to restart. + +On the other hand, the following points must be taken into account: + +* The program must be autonomous; +* Provide redirections (stdin, stdout, stderr); +* It is not relevant to run commands that use input/output requests on a terminal. + +!!! Note It is important to understand that the purpose of scheduling is to perform tasks automatically, without the need for external intervention. + +## The `crontab` file + +The `crontab` file is structured according to the following rules. + +* Each line of this file corresponds to a schedule; +* Each line has six fields, 5 for the time and 1 for the order; +* Each field is separated by a space or a tab; +* Each line ends with a carriage return; +* A `#` at the beginning of the line comments it. + +``` +[root]# crontab –e +10 4 1 * * /root/scripts/backup.sh +1 2 3 4 5 6 +``` + +| Field | Description | Detail | +| ----- | ------------------- | ------------------------ | +| 1 | Minute(s) | From 0 to 59 | +| 2 | Hour(s) | From 0 to 23 | +| 3 | Day(s) of the month | From 1 to 31 | +| 4 | Month of the year | From 1 to 12 | +| 5 | Day(s) of the week | From 0 to 7 (0=7=sunday) | +| 6 | Task to execute | Full command or script | + +!!! Warning The tasks to be executed must use absolute paths and if possible use redirects. + +In order to simplify the notation for the definition of time, it is advisable to use special symbols. + +| Wildcards | Description | +| --------- | -------------------------------- | +| `*` | All possible values of the field | +| `-` | Indicates a range of values | +| `,` | Indicates a list of values | +| `/` | Defines a step | + +Examples: + +Script executed on April 15 at 10:25 am: + +``` +25 10 15 04 * /root/scripts/script > /log/… +``` + +Run at 11am and then at 4pm every day: + +``` +00 11,16 * * * /root/scripts/script > /log/… +``` + +Run every hour from 11am to 4pm every day: + +``` +00 11-16 * * * /root/scripts/script > /log/… +``` + +Run every 10 minutes during working hours: + +``` +*/10 8-17 * * 1-5 /root/scripts/script > /log/… +``` + +For the root user, `crontab` also has some special time settings: + +| Setting | Description | +| --------- | -------------------------------------------------------------- | +| @reboot | Run command on system reboot | +| @hourly | Run command every hour | +| @daily | Runs daily just after midnight | +| @weekly | Runs command every Sunday just after midnight | +| @monthly | Runs command on the first day of the month just after midnight | +| @annually | Runs January 1st just after midnight | + +### Task execution process + +A user, rockstar, wants to edit his `crontab` file: + +1) `crond` checks to see if he is allowed (`/etc/cron.allow` and `/etc/cron.deny`). + +2) If he is, he accesses his `crontab` file (`/var/spool/cron/rockstar`). + +Every minute `crond` reads the schedule files. + +3) It executes the scheduled tasks. + +4) It reports systematically in a log file (`/var/log/cron`). From f398e095a909f65b9696fb4c8a6ba258ffcbd99b Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:49 -0500 Subject: [PATCH 14/37] New translations 12-network.md (French) --- docs/books/admin_guide/12-network.fr.md | 719 ++++++++++++++++++++++++ 1 file changed, 719 insertions(+) create mode 100644 docs/books/admin_guide/12-network.fr.md diff --git a/docs/books/admin_guide/12-network.fr.md b/docs/books/admin_guide/12-network.fr.md new file mode 100644 index 0000000000..cda2f7f8a8 --- /dev/null +++ b/docs/books/admin_guide/12-network.fr.md @@ -0,0 +1,719 @@ +--- +title: Implementing the Network +--- + +# Implementing the Network + +In this chapter you will learn how to work with and manage the network. + +**** + +**Objectifs : **Dans ce chapitre, vous apprendrez à : + +:heavy_check_mark: Configure a workstation to use DHCP; +:heavy_check_mark: Configure a workstation to use a static configuration; +:heavy_check_mark: Configure a workstation to use a gateway; +:heavy_check_mark: Configure a workstation to use DNS servers; +:heavy_check_mark: Troubleshoot the network of a workstation. + +:checkered_flag: **network**, **linux**, **ip** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**Temps de lecture : **30 minutes + +**** + +## Generalities + +To illustrate this chapter, we will use the following architecture. + +![Illustration of our network architecture](images/network-001.png) + +It will allow us to consider : + +* integration in a LAN (local area network); +* the configuration of a gateway to reach a remote server; +* the configuration of a DNS server and the implementation of name resolution. + +The minimum parameters to be defined for the machine are: + +* the name of the machine ; +* the IP address; +* the subnet mask. + +Example: + +* `pc-rocky`; +* `192.168.1.10`; +* `255.255.255.0`. + +The notation called CIDR is more and more frequent: 192.168.1.10/24 + +IP addresses are used for the proper routing of messages (packets). They are divided into two parts: + +* the fixed part, identifying the network; +* the identifier of the host in the network. + +The subnet mask is a set of **4 bytes** intended to isolate: + +* the network address (**NetID** or **SubnetID**) by performing a bitwise logical AND between the IP address and the mask; +* the host address (**HostID**) by performing a bitwise logical AND between the IP address and the complement of the mask. + +There are also specific addresses within a network, which must be identified. The first address of a range as well as the last one have a particular role: + +* The first address of a range is the **network address**. It is used to identify networks and to route information from one network to another. + +* The last address of a range is the **broadcast address**. It is used to broadcast information to all the machines on the network. + +### MAC address / IP address + +A **MAC address** is a physical identifier written in the factory onto the device. This is sometimes referred to as the hardware address. It consists of 6 bytes often given in hexadecimal form (for example 5E:FF:56:A2:AF:15). It is composed of : 3 bytes of the manufacturer identifier and 3 bytes of the serial number. + +!!! Warning This last statement is nowadays a little less true with virtualization. There are also software solutions for changing the MAC address. + +An Internet Protocol (**IP**) address is an identification number permanently or temporarily assigned to each device connected to a computer network using the Internet Protocol. One part defines the network address (NetID or SubnetID as the case may be), the other part defines the address of the host in the network (HostID). The relative size of each part varies according to the network (sub)mask. + +An IPv4 address defines an address on 4 bytes. The number of available addresses being close to saturation a new standard was created, the IPv6 defined on 16 bytes. + +IPv6 is often represented by 8 groups of 2 bytes separated by a colon. Insignificant zeros can be omitted, one or more groups of 4 consecutive zeros can be replaced by a double colon. + +Subnet masks have from 0 to 128 bits. (for example 21ac:0000:0000:0611:21e0:00ba:321b:54da/64 or 21ac::611:21e0:ba:321b:54da/64) + +In a web address or URL (Uniform Resource Locator), an ip address can be followed by a colon and the port address (which indicates the application to which the data is destined). Also to avoid confusion in a URL, the IPv6 address is written in square brackets [ ], colon, port address. + +IP and MAC addresses must be unique on a network! + +### DNS Domain + +Client machines can be part of a DNS (**Domain Name System**, e.g. `mydomain.lan`) domain. + +The fully qualified machine name (**FQDN**) becomes `pc-rocky.mydomain.lan`. + +A set of computers can be grouped into a logical, name-resolving, set called a DNS domain. A DNS domain is not, of course, limited to a single physical network. + +In order for a computer to be part of a DNS domain, it must be given a DNS suffix (here `mydomain.lan`) as well as servers that it can query. + +### Reminder of the OSI model + +!!! Note "Memory aid" To remember the order of the layers of the OSI model, remember the following sentence: __Please Do Not Touch Steven's Pet Alligator__. + +| Layer | Protocoles | +| ---------------- | ------------------------------------------ | +| 7 - Application | POP, IMAP, SMTP, SSH, SNMP, HTTP, FTP, ... | +| 6 - Presentation | ASCII, MIME, ... | +| 5 - Session | TLS, SSL, NetBIOS, ... | +| 4 - Transport | TLS, SSL, TCP, UDP, ... | +| 3 - Network | IPv4, IPv6, ARP, ... | +| 2 - Data Link | Ethernet, WiFi, Token Ring, ... | +| 1 - Physical | Cables, optical fibers, radio waves, ... | + +**Layer 1** (Physical) supports transmission over a communication channel (Wifi, Optical fiber, RJ cable, etc.). Unit: the bit. + +**Layer 2** (Data Link) supports network topology (token-ring, star, bus, etc.), data splitting and transmission errors. Unit: the frame. + +**Layer 3** (Network) supports end-to-end data transmission (IP routing = Gateway). Unit: the packet. + +**Layer 4** (Transport) supports service type (connected or unconnected) encryption and flow control. Unit: the segment or the datagram. + +**Layer 5** (Session) supports the communication between two computers. + +**Layer 6** (Presentation) represents the area that is independent of data at the application layer. Essentially this layer translates from network format to the application format, or or from the application format to the network format. + +**Layer 7** (Application) represents the contact with the user. It provides the services offered by the network: http, dns, ftp, imap, pop, smtp, etc. + +## The naming of interfaces + +*lo* is the "**loopback**" interface which allows TCP/IP programs to communicate with each other without leaving the local machine. This enables testing if the **network module of the system is working properly** and also allows pinging the localhost. All packets that enter through localhost leave through localhost. The packets received are the packets sent. + +The Linux kernel assigns interface names with a specific prefix depending on the type. Traditionally, all **Ethernet** interfaces, for example, began with **eth**. The prefix was followed by a number, the first being 0 (eth0, eth1, eth2...). The wifi interfaces were given a wlan prefix. + +On Rocky8 Linux distributions, systemd will name interfaces with the new following policy where "X" represents a number: + +* `enoX`: on-board devices +* `ensX`: PCI Express hotplug slot +* `enpXsX`: physical/geographical location of the connector of the hardware +* ... + +## Using the `ip` command + +Forget the old `ifconfig` command! Think `ip`! + +!!! Note Comment for administrators of older Linux systems: + + The historical network management command is `ifconfig`. This command has been replaced by the `ip` command, which is already well known to network administrators. + + The `ip` command is the only command to manage **IP address, ARP, routing, etc.**. + + The `ifconfig` command is no longer installed by default in Rocky8. + + It is important to get into good habits now. + +## The hostname + +The `hostname` command displays or sets the host name of the system + +``` +hostname [-f] [hostname] +``` + +| Option | Description | +| ------ | ------------------------------ | +| `-f` | Display the FQDN | +| `-i` | Display the system IPs address | + +!!! Tip This command is used by various network programs to identify the machine. + +To assign a host name, it is possible to use the `hostname` command, but the changes will not be retained at the next boot. The command with no arguments displays the host name. + +To set the host name, the file `/etc/sysconfig/network` must be modified: + +``` +NETWORKING=yes +HOSTNAME=pc-rocky.mondomaine.lan +``` + +The RedHat boot script also consults the `/etc/hosts` file to resolve the host name of the system. + +When the system boots, Linux evaluates the `HOSTNAME` value in the `/etc/sysconfig/network` file. + +It then uses the `/etc/hosts` file to evaluate the main IP address of the server and its host name. It deduces the DNS domain name. + +It is therefore essential to fill in these two files before any configuration of network services. + +!!! Tip To know if this configuration is well done, the commands `hostname` and `hostname -f` must answer with the expected values. + +## /etc/hosts file + +The `/etc/hosts` file is a static host name mapping table, which follows the following format: + +``` +@IP [alias] [# comment] +``` + +Example of `/etc/hosts` file: + +``` +127.0.0.1 localhost localhost.localdomain +::1 localhost localhost.localdomain +192.168.1.10 rockstar.rockylinux.lan rockstar +``` + +The `/etc/hosts` file is still used by the system, especially at boot time when the system FQDN is determined. + +!!! Tip RedHat recommends that at least one line containing the system name be filled in. + +If the **DNS** service (**D**domain **N**ame **S**ervice) is not in place, you must fill in all the names in the hosts file for each of your machines. + +The `/etc/hosts` file contains one line per entry, with the IP address, the FQDN, then the host name (in that order) and a series of aliases (alias1 alias2 ...). The alias is an option. + +## `/etc/nsswitch.conf` file + +The **NSS** (**N**ame **S**ervice **S**witch) allows configuration files (e.g. `/etc/passwd`, `/etc/group`, `/etc/hosts`) to be substituted for one or more centralized databases. + +The `/etc/nsswitch.conf` file is used to configure the name service databases. + +``` +passwd: files +shadow: files +group: files + +hosts: files dns +``` + +In this case, Linux will first look for a host name match (`hosts:` line) in the `/etc/hosts` file (`files` value) before querying DNS (`dns` value)! This behavior can simply be changed by editing the `/etc/nsswitch.conf` file. + +Of course, it is possible to imagine querying an LDAP, MySQL or other server by configuring the name service to respond to system requests for hosts, users, groups, etc. + +The resolution of the name service can be tested with the `getent` command that we will see later in this course. + +## `/etc/resolv.conf` file + +The `/etc/resolv.conf` file contains the DNS name resolution configuration. + +``` +#Generated by NetworkManager +domain mondomaine.lan +search mondomaine.lan +nameserver 192.168.1.254 +``` + +!!! Tip This file is historical. It is no longer filled in directly! + +Newer generations of distributions have generally integrated the `NetworkManager` service. This service allows you to manage the configuration more efficiently, either in graphical or console mode. + +It allows for the addition of DNS servers from the configuration file of a network interface. It then dynamically populates the `/etc/resolv.conf` file which should never be edited directly, otherwise the configuration changes will be lost the next time the network service is started. + +## `ip` command + +The `ip` command from the `iproute2` package allows you to configure an interface and its routing table. + +Display interfaces : + +``` +[root]# ip link +``` + +Display interfaces information: + +``` +[root]# ip addr show +``` + +Display the information of an interface : + +``` +[root]# ip addr show eth0 +``` + +Display the ARP table: + +``` +[root]# ip neigh +``` + +All historical network management commands have been grouped under the `ip` command, which is well known to network administrators. + +## DHCP configuration + +The **DHCP** protocol (**D**ynamic **H**ost **C**Control **P**rotocol) allows you to obtain a complete IP configuration via the network. This is the default configuration mode of a network interface under Rocky Linux, which explains why a system connected to the network of an Internet router can function without additional configuration. + +The configuration of interfaces under Rocky Linux is done in the `/etc/sysconfig/network-scripts/` folder. + +For each Ethernet interface, a `ifcfg-ethX` file allows for the configuration of the associated interface. + +``` +DEVICE=eth0 +ONBOOT=yes +BOOTPROTO=dhcp +HWADDR=00:0c:29:96:32:e3 +``` + +* Interface name : (must be in the file name) + +``` +DEVICE=eth0 +``` + +* Automatically start the interface: + +``` +ONBOOT=yes +``` + +* Make a DHCP request when the interface starts up: + +``` +BOOTPROTO=dhcp +``` + +* Specify the MAC address (optional but useful when there are several interfaces) : + +``` +HWADDR=00:0c:29:96:32:e3 +``` + +!!! Tip If NetworkManager is installed, the changes are taken into account automatically. If not, you have to restart the network service. + +* Restart the network service: + +``` +[root]# systemctl restart NetworkManager +``` + +## Static configuration + +The static configuration requires at least: + +``` +DEVICE=eth0 +ONBOOT=yes +BOOTPROTO=none +IPADDR=192.168.1.10 +NETMASK=255.255.255.0 +``` + +* Here we are replacing "dhcp" with "none" which equals static configuration: + +``` +BOOTPROTO=none +``` + +* IP Address: + +``` +IPADDR=192.168.1.10 +``` + +* Subnet mask: + +``` +NETMASK=255.255.255.0 +``` + +* The mask can be specified with a prefix: + +``` +PREFIX=24 +``` + +!!! Warning You must use NETMASK OR PREFIX - Not both! + +## Routing + +![Network architecture with a gateway](images/network-002.png) + +``` +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 +``` + +The `ip route` command: + +``` +[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 +``` + +It is a good idea to know how to read a routing table, especially in an environment with multiple network interfaces. + +* In the example shown, the `192.168.1.0/24` network is reachable directly from the `eth0` device, so there is a metric at `1` (does not traverse a router). + +* All other networks than the previous one will be reachable, again from the `eth0` device, but this time the packets will be addressed to a `192.168.1.254` gateway. The routing protocol is a static protocol (although it is possible to add a route to a dynamically assigned address in Linux). + +## Name resolution + +A system needs to resolve: + +* FQDNs into IP addresses + +``` +www.free.fr = 212.27.48.10 +``` + +* IP addresses into names + +``` +212.27.48.10 = www.free.fr +``` + +* or to obtain information about an area: + +``` +MX de free.fr = 10 mx1.free.fr + 20 mx2.free.fr +``` + +``` +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 this case, to reach the DNS, you have to go through the gateway. + +``` + #Generated by NetworkManager + domain mondomaine.lan + search mondomaine.lan + nameserver 172.16.1.2 + nameserver 172.16.1.3 +``` + +The file has been updated by NetworkManager. + +## Troubleshooting + +The `ping` command sends datagrams to another machine and waits for a response. + +It is the basic command for testing the network because it checks the connectivity between your network interface and another. + +Syntax of the `ping` command: + +``` +ping [-c numerical] destination +``` + +The `-c` (count) option allows you to stop the command after the countdown in seconds. + +Example: + +``` +[root]# ping –c 4 localhost +``` + +!!! Tip Validate connectivity from near to far + +1) Validate the TCP/IP software layer + +``` +[root]# ping localhost +``` + +"Pinging" the inner loop does not detect a hardware failure on the network interface. It simply determines whether the IP software configuration is correct. + +2) Validate the network card + +``` +[root]# ping 192.168.1.10 +``` + +To determine that the network card is functional, we must now ping its IP address. The network card, if the network cable is not connected, should be in a "down" state. + +If the ping does not work, first check the network cable to your network switch and reassemble the interface (see the `if up` command), then check the interface itself. + +3) Validate the connectivity of the gateway + +``` +[root]# ping 192.168.1.254 +``` + +4) Validate the connectivity of a remote server + +``` +[root]# ping 172.16.1.2 +``` + +5) Validate the DNS service + +``` +[root]# ping www.free.fr +``` + +### `dig` command + +The `dig` command is used to query the DNS server. + +The `dig` command syntax: + +``` +dig [-t type] [+short] [name] +``` + +Examples: + +``` +[root]# dig +short rockylinux.org +76.223.126.88 +[root]# dig -t MX +short rockylinux.org  ✔ +5 alt1.aspmx.l.google.com. +... +``` + +The `dig` command is used to query DNS servers. It is very verbose by default, but this behavior can be changed with the `+short` option. + +It is also possible to specify a DNS **record type** to resolve, such as an MX **type** to get information about the mail exchangers for a domain. + +### `getent` command + +The `getent` (get entry) command is used to get an NSSwitch entry (`hosts` + `dns`) + +Syntax of the `getent` command: + + +``` +getent hosts name +``` + +Example: + +``` +[root]# getent hosts rockylinux.org + 76.223.126.88 rockylinux.org +``` + +Querying only a DNS server may return an erroneous result that does not take into account the contents of a `hosts` file, although this should be rare nowadays. + +To take the `/etc/hosts` file into account as well, the NSSwitch name service must be queried, which will take care of any DNS resolution. + +### `ipcalc` command + +The `ipcalc` (**ip calculation**) command is used to calculate the address of a network or broadcast from an IP address and a mask. + +Syntax of the `ipcalc` command: + +``` +ipcalc [options] IP +``` + +Example: + +``` +[root]# ipcalc –b 172.16.66.203 255.255.240.0 +BROADCAST=172.16.79.255 +``` + +!!! Tip This command is interesting followed by a redirection to automatically fill in the configuration files of your interfaces: + + ``` + [root]# ipcalc –b 172.16.66.203 255.255.240.0 >> /etc/sysconfig/network-scripts/ifcfg-eth0 + ``` + +| Option | Description | +| ------ | -------------------------------------- | +| `-b` | Displays the broadcast address. | +| `-n` | Displays the network address and mask. | + +`ipcalc` is a simple way to calculate the IP information of a host. The various options indicate what information `ipcalc` should display on the standard output. Multiple options can be specified. An IP address on which to operate must be specified. Most operations also require a network mask or CIDR prefix. + +| Option short | Option long | Description | +| ------------ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-b` | `--broadcast` | Displays the broadcast address of the given IP address and the network mask. | +| `-h` | `--hostname` | Displays the hostname of the IP address given via DNS. | +| `-n` | `--netmask` | Calculates the network mask for the given IP address. Assumes that the IP address is part of a complete class A, B, or C network. Many networks do not use default network masks, in which case an incorrect incorrect value will be returned. | +| `-p` | `--prefix` | Indicates the prefix of the mask/IP address. | +| `-n` | `--network` | Indicates the network address of the given IP address and mask. | +| `-s` | `--silent` | Never displays any error messages. | + +### `ss` command + +The `ss` (**socket statistics**) command displays the listening ports on the network. + +Syntax of the `ss` command: + +``` +ss [-tuna] +``` + +Example: + +``` +[root]# ss –tuna +tcp LISTEN 0 128 *:22 *:* +``` + +The commands `ss` and `netstat` (to follow) will be very important for the rest of your Linux life. + +When implementing network services, it is very common to check with one of these two commands that the service is listening on the expected ports. + +### `netstat` command + +!!! Warning The `netstat` command is now deprecated and is no-longer installed by default on Rocky Linux. You may still find some Linux versions that have it installed, but it is best to move on to using `ss` for everything that you would have used `netstat` for. + +The `netstat` command (**network statistics**) displays the listening ports on the network. + +Syntax of the `netstat` command: + +``` +netstat -tapn +``` + +Example: + +``` +[root]# netstat –tapn +tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 2161/sshd +``` + +### IP or MAC address conflicts + +A misconfiguration can cause multiple interfaces to use the same IP address. This can happen when a network has multiple DHCP servers or when the same IP address is manually assigned multiple times. + +When the network is malfunctioning, and when an IP address conflict could be the cause, it is possible to use the `arp-scan` software (requires the EPEL repository): + +``` +$ dnf install arp-scan +``` + +Example: + +``` +$ 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 As the above example shows, it is also possible to have MAC address conflicts! These problems are brought about by virtualization technologies and the copying of virtual machines. + +## Hot configuration + +The `ip` command can hot add an IP address to an interface + +``` +ip addr add @IP dev DEVICE +``` + +Example: + +``` +[root]# ip addr add 192.168.2.10 dev eth1 +``` + +The `ip` command allows for the activation or deactivation of an interface: + +``` +ip link set DEVICE up +ip link set DEVICE down +``` + +Example: + +``` +[root]# ip link set eth1 up +[root]# ip link set eth1 down +``` + +The `ip` command is used to add a route: + +``` +ip route add [default|netaddr] via @IP [dev device] +``` + +Example: + +``` +[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 summary + +The files used in this chapter are : + +![Synthesis of the files implemented in the network part](images/network-003.png) + +A complete interface configuration could be this (file `/etc/sysconfig/network-scripts/ifcfg-eth0`): + +``` + 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 +``` + +The troubleshooting method should go from closest to farthest: + +1. ping localhost (software test) +2. ping IP-address (hardware test) +3. ping gateway (connectivity test) +4. ping remote-server (routing test) +5. DNS query (dig or ping) + +![Method of troubleshooting or network validation](images/network-004.png) From 63d2f7a5e295ee72d064df51c2704dcda91efae5 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:50 -0500 Subject: [PATCH 15/37] New translations 12-network.md (Italian) --- docs/books/admin_guide/12-network.it.md | 719 ++++++++++++++++++++++++ 1 file changed, 719 insertions(+) create mode 100644 docs/books/admin_guide/12-network.it.md diff --git a/docs/books/admin_guide/12-network.it.md b/docs/books/admin_guide/12-network.it.md new file mode 100644 index 0000000000..d6c763b713 --- /dev/null +++ b/docs/books/admin_guide/12-network.it.md @@ -0,0 +1,719 @@ +--- +title: Implementazione della Rete +--- + +# 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 + +``` +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`: + +``` +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: + +``` +@IP [alias] [# comment] +``` + +Esempio di un file `/etc/hosts`: + +``` +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. + +``` +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. + +``` +#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 : + +``` +[root]# ip link +``` + +Mostra le informazioni sulle interfacce: + +``` +[root]# ip addr show +``` + +Mostra le informazioni su una interfaccia : + +``` +[root]# ip addr show eth0 +``` + +Mostra la tabella ARP: + +``` +[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. + +``` +DEVICE=eth0 +ONBOOT=yes +BOOTPROTO=dhcp +HWADDR=00:0c:29:96:32:e3 +``` + +* Nome dell'interfaccia : (deve essere nel nome del file) + +``` +DEVICE=eth0 +``` + +* Avvia automaticamente l'interfaccia: + +``` +ONBOOT=yes +``` + +* Effettuare una richiesta DHCP all'avvio dell'interfaccia: + +``` +BOOTPROTO=dhcp +``` + +* Specificare l'indirizzo MAC (opzionale ma utile quando ci sono diverse interfacce): + +``` +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: + +``` +[root]# systemctl restart NetworkManager +``` + +## Configurazione statica + +La configurazione statica richiede almeno: + +``` +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: + +``` +BOOTPROTO=none +``` + +* Indirizzo IP: + +``` +IPADDR=192.168.1.10 +``` + +* Subnet mask: + +``` +NETMASK=255.255.255.0 +``` + +* La maschera può essere specificata con un prefisso: + +``` +PREFIX=24 +``` + +!!! Warning "Avvertimento" È necessario utilizzare il NETMASK o il PREFISSO - Non entrambi! + +## Routing (Instradamento) + +![Network architecture with a gateway](images/network-002.png) + +``` +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`: + +``` +[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 + +``` +www.free.fr = 212.27.48.10 +``` + +* Indirizzi IP in nomi + +``` +212.27.48.10 = www.free.fr +``` + +* o per ottenere informazioni su un'area: + +``` +MX de free.fr = 10 mx1.free.fr + 20 mx2.free.fr +``` + +``` +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. + +``` + #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`: + +``` +ping [-c numerical] destination +``` + +L'opzione `-c` (conteggio) consente di interrompere il comando dopo il conto alla rovescia in secondi. + +Esempio: + +``` +[root]# ping –c 4 localhost +``` + +!!! Tip "Suggerimento" Convalida la connettività da vicino a lontano + +1) Convalidare il livello software TCP/IP + +``` +[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 + +``` +[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 + +``` +[root]# ping 192.168.1.254 +``` + +4) Convalidare la connettività di un server remoto + +``` +[root]# ping 172.16.1.2 +``` + +5) Convalidare il servizio DNS + +``` +[root]# ping www.free.fr +``` + +### comando `dig` + +Il comando `dig` viene utilizzato per interrogare il server DNS. + +La sintassi del comando `dig`: + +``` +dig [-t type] [+short] [name] +``` + +Esempi: + +``` +[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`: + + +``` +getent hosts name +``` + +Esempio: + +``` +[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`: + +``` +ipcalc [options] IP +``` + +Esempio: + +``` +[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: + + ``` + [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`: + +``` +ss [-tuna] +``` + +Esempio: + +``` +[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`: + +``` +netstat -tapn +``` + +Esempio: + +``` +[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): + +``` +$ dnf install arp-scan +``` + +Esempio: + +``` +$ 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 + +``` +ip addr add @IP dev DEVICE +``` + +Esempio: + +``` +[root]# ip addr add 192.168.2.10 dev eth1 +``` + +Il comando `ip` consente l'attivazione o la disattivazione di un'interfaccia: + +``` +ip link set DEVICE up +ip link set DEVICE down +``` + +Esempio: + +``` +[root]# ip link set eth1 up +[root]# ip link set eth1 down +``` + +Il comando `ip` viene utilizzato per aggiungere una route: + +``` +ip route add [default|netaddr] via @IP [dev device] +``` + +Esempio: + +``` +[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`): + +``` + 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) From 8935dd068c5eee328e0f2cf27e7d4c964b2ce558 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:50 -0500 Subject: [PATCH 16/37] New translations 12-network.md (Chinese Simplified) --- docs/books/admin_guide/12-network.zh.md | 719 ++++++++++++++++++++++++ 1 file changed, 719 insertions(+) create mode 100644 docs/books/admin_guide/12-network.zh.md diff --git a/docs/books/admin_guide/12-network.zh.md b/docs/books/admin_guide/12-network.zh.md new file mode 100644 index 0000000000..07c2ed26f6 --- /dev/null +++ b/docs/books/admin_guide/12-network.zh.md @@ -0,0 +1,719 @@ +--- +title: Implementing the Network +--- + +# Implementing the Network + +In this chapter you will learn how to work with and manage the network. + +**** + +**目标** : 本章将讲解以下内容: + +:heavy_check_mark: Configure a workstation to use DHCP; +:heavy_check_mark: Configure a workstation to use a static configuration; +:heavy_check_mark: Configure a workstation to use a gateway; +:heavy_check_mark: Configure a workstation to use DNS servers; +:heavy_check_mark: Troubleshoot the network of a workstation. + +:checkered_flag: **network**, **linux**, **ip** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**阅读时间**: 30 分钟 + +**** + +## 概论 + +To illustrate this chapter, we will use the following architecture. + +![Illustration of our network architecture](images/network-001.png) + +It will allow us to consider : + +* integration in a LAN (local area network); +* the configuration of a gateway to reach a remote server; +* the configuration of a DNS server and the implementation of name resolution. + +The minimum parameters to be defined for the machine are: + +* the name of the machine ; +* the IP address; +* the subnet mask. + +Example: + +* `pc-rocky`; +* `192.168.1.10`; +* `255.255.255.0`. + +The notation called CIDR is more and more frequent: 192.168.1.10/24 + +IP addresses are used for the proper routing of messages (packets). They are divided into two parts: + +* the fixed part, identifying the network; +* the identifier of the host in the network. + +The subnet mask is a set of **4 bytes** intended to isolate: + +* the network address (**NetID** or **SubnetID**) by performing a bitwise logical AND between the IP address and the mask; +* the host address (**HostID**) by performing a bitwise logical AND between the IP address and the complement of the mask. + +There are also specific addresses within a network, which must be identified. The first address of a range as well as the last one have a particular role: + +* The first address of a range is the **network address**. It is used to identify networks and to route information from one network to another. + +* The last address of a range is the **broadcast address**. It is used to broadcast information to all the machines on the network. + +### MAC address / IP address + +A **MAC address** is a physical identifier written in the factory onto the device. This is sometimes referred to as the hardware address. It consists of 6 bytes often given in hexadecimal form (for example 5E:FF:56:A2:AF:15). It is composed of : 3 bytes of the manufacturer identifier and 3 bytes of the serial number. + +!!! Warning This last statement is nowadays a little less true with virtualization. There are also software solutions for changing the MAC address. + +An Internet Protocol (**IP**) address is an identification number permanently or temporarily assigned to each device connected to a computer network using the Internet Protocol. One part defines the network address (NetID or SubnetID as the case may be), the other part defines the address of the host in the network (HostID). The relative size of each part varies according to the network (sub)mask. + +An IPv4 address defines an address on 4 bytes. The number of available addresses being close to saturation a new standard was created, the IPv6 defined on 16 bytes. + +IPv6 is often represented by 8 groups of 2 bytes separated by a colon. Insignificant zeros can be omitted, one or more groups of 4 consecutive zeros can be replaced by a double colon. + +Subnet masks have from 0 to 128 bits. (for example 21ac:0000:0000:0611:21e0:00ba:321b:54da/64 or 21ac::611:21e0:ba:321b:54da/64) + +In a web address or URL (Uniform Resource Locator), an ip address can be followed by a colon and the port address (which indicates the application to which the data is destined). Also to avoid confusion in a URL, the IPv6 address is written in square brackets [ ], colon, port address. + +IP and MAC addresses must be unique on a network! + +### DNS Domain + +Client machines can be part of a DNS (**Domain Name System**, e.g. `mydomain.lan`) domain. + +The fully qualified machine name (**FQDN**) becomes `pc-rocky.mydomain.lan`. + +A set of computers can be grouped into a logical, name-resolving, set called a DNS domain. A DNS domain is not, of course, limited to a single physical network. + +In order for a computer to be part of a DNS domain, it must be given a DNS suffix (here `mydomain.lan`) as well as servers that it can query. + +### Reminder of the OSI model + +!!! Note "Memory aid" To remember the order of the layers of the OSI model, remember the following sentence: __Please Do Not Touch Steven's Pet Alligator__. + +| Layer | Protocoles | +| ---------------- | ------------------------------------------ | +| 7 - Application | POP, IMAP, SMTP, SSH, SNMP, HTTP, FTP, ... | +| 6 - Presentation | ASCII, MIME, ... | +| 5 - Session | TLS, SSL, NetBIOS, ... | +| 4 - Transport | TLS, SSL, TCP, UDP, ... | +| 3 - Network | IPv4, IPv6, ARP, ... | +| 2 - Data Link | Ethernet, WiFi, Token Ring, ... | +| 1 - Physical | Cables, optical fibers, radio waves, ... | + +**Layer 1** (Physical) supports transmission over a communication channel (Wifi, Optical fiber, RJ cable, etc.). Unit: the bit. + +**Layer 2** (Data Link) supports network topology (token-ring, star, bus, etc.), data splitting and transmission errors. Unit: the frame. + +**Layer 3** (Network) supports end-to-end data transmission (IP routing = Gateway). Unit: the packet. + +**Layer 4** (Transport) supports service type (connected or unconnected) encryption and flow control. Unit: the segment or the datagram. + +**Layer 5** (Session) supports the communication between two computers. + +**Layer 6** (Presentation) represents the area that is independent of data at the application layer. Essentially this layer translates from network format to the application format, or or from the application format to the network format. + +**Layer 7** (Application) represents the contact with the user. It provides the services offered by the network: http, dns, ftp, imap, pop, smtp, etc. + +## The naming of interfaces + +*lo* is the "**loopback**" interface which allows TCP/IP programs to communicate with each other without leaving the local machine. This enables testing if the **network module of the system is working properly** and also allows pinging the localhost. All packets that enter through localhost leave through localhost. The packets received are the packets sent. + +The Linux kernel assigns interface names with a specific prefix depending on the type. Traditionally, all **Ethernet** interfaces, for example, began with **eth**. The prefix was followed by a number, the first being 0 (eth0, eth1, eth2...). The wifi interfaces were given a wlan prefix. + +On Rocky8 Linux distributions, systemd will name interfaces with the new following policy where "X" represents a number: + +* `enoX`: on-board devices +* `ensX`: PCI Express hotplug slot +* `enpXsX`: physical/geographical location of the connector of the hardware +* ... + +## Using the `ip` command + +Forget the old `ifconfig` command! Think `ip`! + +!!! Note Comment for administrators of older Linux systems: + + The historical network management command is `ifconfig`. This command has been replaced by the `ip` command, which is already well known to network administrators. + + The `ip` command is the only command to manage **IP address, ARP, routing, etc.**. + + The `ifconfig` command is no longer installed by default in Rocky8. + + It is important to get into good habits now. + +## The hostname + +The `hostname` command displays or sets the host name of the system + +``` +hostname [-f] [hostname] +``` + +| Option | Description | +| ------ | ------------------------------ | +| `-f` | Display the FQDN | +| `-i` | Display the system IPs address | + +!!! Tip This command is used by various network programs to identify the machine. + +To assign a host name, it is possible to use the `hostname` command, but the changes will not be retained at the next boot. The command with no arguments displays the host name. + +To set the host name, the file `/etc/sysconfig/network` must be modified: + +``` +NETWORKING=yes +HOSTNAME=pc-rocky.mondomaine.lan +``` + +The RedHat boot script also consults the `/etc/hosts` file to resolve the host name of the system. + +When the system boots, Linux evaluates the `HOSTNAME` value in the `/etc/sysconfig/network` file. + +It then uses the `/etc/hosts` file to evaluate the main IP address of the server and its host name. It deduces the DNS domain name. + +It is therefore essential to fill in these two files before any configuration of network services. + +!!! Tip To know if this configuration is well done, the commands `hostname` and `hostname -f` must answer with the expected values. + +## /etc/hosts file + +The `/etc/hosts` file is a static host name mapping table, which follows the following format: + +``` +@IP [alias] [# comment] +``` + +Example of `/etc/hosts` file: + +``` +127.0.0.1 localhost localhost.localdomain +::1 localhost localhost.localdomain +192.168.1.10 rockstar.rockylinux.lan rockstar +``` + +The `/etc/hosts` file is still used by the system, especially at boot time when the system FQDN is determined. + +!!! Tip RedHat recommends that at least one line containing the system name be filled in. + +If the **DNS** service (**D**domain **N**ame **S**ervice) is not in place, you must fill in all the names in the hosts file for each of your machines. + +The `/etc/hosts` file contains one line per entry, with the IP address, the FQDN, then the host name (in that order) and a series of aliases (alias1 alias2 ...). The alias is an option. + +## `/etc/nsswitch.conf` file + +The **NSS** (**N**ame **S**ervice **S**witch) allows configuration files (e.g. `/etc/passwd`, `/etc/group`, `/etc/hosts`) to be substituted for one or more centralized databases. + +The `/etc/nsswitch.conf` file is used to configure the name service databases. + +``` +passwd: files +shadow: files +group: files + +hosts: files dns +``` + +In this case, Linux will first look for a host name match (`hosts:` line) in the `/etc/hosts` file (`files` value) before querying DNS (`dns` value)! This behavior can simply be changed by editing the `/etc/nsswitch.conf` file. + +Of course, it is possible to imagine querying an LDAP, MySQL or other server by configuring the name service to respond to system requests for hosts, users, groups, etc. + +The resolution of the name service can be tested with the `getent` command that we will see later in this course. + +## `/etc/resolv.conf` file + +The `/etc/resolv.conf` file contains the DNS name resolution configuration. + +``` +#Generated by NetworkManager +domain mondomaine.lan +search mondomaine.lan +nameserver 192.168.1.254 +``` + +!!! Tip This file is historical. It is no longer filled in directly! + +Newer generations of distributions have generally integrated the `NetworkManager` service. This service allows you to manage the configuration more efficiently, either in graphical or console mode. + +It allows for the addition of DNS servers from the configuration file of a network interface. It then dynamically populates the `/etc/resolv.conf` file which should never be edited directly, otherwise the configuration changes will be lost the next time the network service is started. + +## `ip` command + +The `ip` command from the `iproute2` package allows you to configure an interface and its routing table. + +Display interfaces : + +``` +[root]# ip link +``` + +Display interfaces information: + +``` +[root]# ip addr show +``` + +Display the information of an interface : + +``` +[root]# ip addr show eth0 +``` + +Display the ARP table: + +``` +[root]# ip neigh +``` + +All historical network management commands have been grouped under the `ip` command, which is well known to network administrators. + +## DHCP configuration + +The **DHCP** protocol (**D**ynamic **H**ost **C**Control **P**rotocol) allows you to obtain a complete IP configuration via the network. This is the default configuration mode of a network interface under Rocky Linux, which explains why a system connected to the network of an Internet router can function without additional configuration. + +The configuration of interfaces under Rocky Linux is done in the `/etc/sysconfig/network-scripts/` folder. + +For each Ethernet interface, a `ifcfg-ethX` file allows for the configuration of the associated interface. + +``` +DEVICE=eth0 +ONBOOT=yes +BOOTPROTO=dhcp +HWADDR=00:0c:29:96:32:e3 +``` + +* Interface name : (must be in the file name) + +``` +DEVICE=eth0 +``` + +* Automatically start the interface: + +``` +ONBOOT=yes +``` + +* Make a DHCP request when the interface starts up: + +``` +BOOTPROTO=dhcp +``` + +* Specify the MAC address (optional but useful when there are several interfaces) : + +``` +HWADDR=00:0c:29:96:32:e3 +``` + +!!! Tip If NetworkManager is installed, the changes are taken into account automatically. If not, you have to restart the network service. + +* Restart the network service: + +``` +[root]# systemctl restart NetworkManager +``` + +## Static configuration + +The static configuration requires at least: + +``` +DEVICE=eth0 +ONBOOT=yes +BOOTPROTO=none +IPADDR=192.168.1.10 +NETMASK=255.255.255.0 +``` + +* Here we are replacing "dhcp" with "none" which equals static configuration: + +``` +BOOTPROTO=none +``` + +* IP Address: + +``` +IPADDR=192.168.1.10 +``` + +* Subnet mask: + +``` +NETMASK=255.255.255.0 +``` + +* The mask can be specified with a prefix: + +``` +PREFIX=24 +``` + +!!! Warning You must use NETMASK OR PREFIX - Not both! + +## Routing + +![Network architecture with a gateway](images/network-002.png) + +``` +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 +``` + +The `ip route` command: + +``` +[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 +``` + +It is a good idea to know how to read a routing table, especially in an environment with multiple network interfaces. + +* In the example shown, the `192.168.1.0/24` network is reachable directly from the `eth0` device, so there is a metric at `1` (does not traverse a router). + +* All other networks than the previous one will be reachable, again from the `eth0` device, but this time the packets will be addressed to a `192.168.1.254` gateway. The routing protocol is a static protocol (although it is possible to add a route to a dynamically assigned address in Linux). + +## Name resolution + +A system needs to resolve: + +* FQDNs into IP addresses + +``` +www.free.fr = 212.27.48.10 +``` + +* IP addresses into names + +``` +212.27.48.10 = www.free.fr +``` + +* or to obtain information about an area: + +``` +MX de free.fr = 10 mx1.free.fr + 20 mx2.free.fr +``` + +``` +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 this case, to reach the DNS, you have to go through the gateway. + +``` + #Generated by NetworkManager + domain mondomaine.lan + search mondomaine.lan + nameserver 172.16.1.2 + nameserver 172.16.1.3 +``` + +The file has been updated by NetworkManager. + +## Troubleshooting + +The `ping` command sends datagrams to another machine and waits for a response. + +It is the basic command for testing the network because it checks the connectivity between your network interface and another. + +Syntax of the `ping` command: + +``` +ping [-c numerical] destination +``` + +The `-c` (count) option allows you to stop the command after the countdown in seconds. + +Example: + +``` +[root]# ping –c 4 localhost +``` + +!!! Tip Validate connectivity from near to far + +1) Validate the TCP/IP software layer + +``` +[root]# ping localhost +``` + +"Pinging" the inner loop does not detect a hardware failure on the network interface. It simply determines whether the IP software configuration is correct. + +2) Validate the network card + +``` +[root]# ping 192.168.1.10 +``` + +To determine that the network card is functional, we must now ping its IP address. The network card, if the network cable is not connected, should be in a "down" state. + +If the ping does not work, first check the network cable to your network switch and reassemble the interface (see the `if up` command), then check the interface itself. + +3) Validate the connectivity of the gateway + +``` +[root]# ping 192.168.1.254 +``` + +4) Validate the connectivity of a remote server + +``` +[root]# ping 172.16.1.2 +``` + +5) Validate the DNS service + +``` +[root]# ping www.free.fr +``` + +### `dig` command + +The `dig` command is used to query the DNS server. + +The `dig` command syntax: + +``` +dig [-t type] [+short] [name] +``` + +Examples: + +``` +[root]# dig +short rockylinux.org +76.223.126.88 +[root]# dig -t MX +short rockylinux.org  ✔ +5 alt1.aspmx.l.google.com. +... +``` + +The `dig` command is used to query DNS servers. It is very verbose by default, but this behavior can be changed with the `+short` option. + +It is also possible to specify a DNS **record type** to resolve, such as an MX **type** to get information about the mail exchangers for a domain. + +### `getent` command + +The `getent` (get entry) command is used to get an NSSwitch entry (`hosts` + `dns`) + +Syntax of the `getent` command: + + +``` +getent hosts name +``` + +Example: + +``` +[root]# getent hosts rockylinux.org + 76.223.126.88 rockylinux.org +``` + +Querying only a DNS server may return an erroneous result that does not take into account the contents of a `hosts` file, although this should be rare nowadays. + +To take the `/etc/hosts` file into account as well, the NSSwitch name service must be queried, which will take care of any DNS resolution. + +### `ipcalc` command + +The `ipcalc` (**ip calculation**) command is used to calculate the address of a network or broadcast from an IP address and a mask. + +Syntax of the `ipcalc` command: + +``` +ipcalc [options] IP +``` + +Example: + +``` +[root]# ipcalc –b 172.16.66.203 255.255.240.0 +BROADCAST=172.16.79.255 +``` + +!!! Tip This command is interesting followed by a redirection to automatically fill in the configuration files of your interfaces: + + ``` + [root]# ipcalc –b 172.16.66.203 255.255.240.0 >> /etc/sysconfig/network-scripts/ifcfg-eth0 + ``` + +| Option | Description | +| ------ | -------------------------------------- | +| `-b` | Displays the broadcast address. | +| `-n` | Displays the network address and mask. | + +`ipcalc` is a simple way to calculate the IP information of a host. The various options indicate what information `ipcalc` should display on the standard output. Multiple options can be specified. An IP address on which to operate must be specified. Most operations also require a network mask or CIDR prefix. + +| Option short | Option long | Description | +| ------------ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-b` | `--broadcast` | Displays the broadcast address of the given IP address and the network mask. | +| `-h` | `--hostname` | Displays the hostname of the IP address given via DNS. | +| `-n` | `--netmask` | Calculates the network mask for the given IP address. Assumes that the IP address is part of a complete class A, B, or C network. Many networks do not use default network masks, in which case an incorrect incorrect value will be returned. | +| `-p` | `--prefix` | Indicates the prefix of the mask/IP address. | +| `-n` | `--network` | Indicates the network address of the given IP address and mask. | +| `-s` | `--silent` | Never displays any error messages. | + +### `ss` command + +The `ss` (**socket statistics**) command displays the listening ports on the network. + +Syntax of the `ss` command: + +``` +ss [-tuna] +``` + +Example: + +``` +[root]# ss –tuna +tcp LISTEN 0 128 *:22 *:* +``` + +The commands `ss` and `netstat` (to follow) will be very important for the rest of your Linux life. + +When implementing network services, it is very common to check with one of these two commands that the service is listening on the expected ports. + +### `netstat` command + +!!! Warning The `netstat` command is now deprecated and is no-longer installed by default on Rocky Linux. You may still find some Linux versions that have it installed, but it is best to move on to using `ss` for everything that you would have used `netstat` for. + +The `netstat` command (**network statistics**) displays the listening ports on the network. + +Syntax of the `netstat` command: + +``` +netstat -tapn +``` + +Example: + +``` +[root]# netstat –tapn +tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 2161/sshd +``` + +### IP or MAC address conflicts + +A misconfiguration can cause multiple interfaces to use the same IP address. This can happen when a network has multiple DHCP servers or when the same IP address is manually assigned multiple times. + +When the network is malfunctioning, and when an IP address conflict could be the cause, it is possible to use the `arp-scan` software (requires the EPEL repository): + +``` +$ dnf install arp-scan +``` + +Example: + +``` +$ 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 As the above example shows, it is also possible to have MAC address conflicts! These problems are brought about by virtualization technologies and the copying of virtual machines. + +## Hot configuration + +The `ip` command can hot add an IP address to an interface + +``` +ip addr add @IP dev DEVICE +``` + +Example: + +``` +[root]# ip addr add 192.168.2.10 dev eth1 +``` + +The `ip` command allows for the activation or deactivation of an interface: + +``` +ip link set DEVICE up +ip link set DEVICE down +``` + +Example: + +``` +[root]# ip link set eth1 up +[root]# ip link set eth1 down +``` + +The `ip` command is used to add a route: + +``` +ip route add [default|netaddr] via @IP [dev device] +``` + +Example: + +``` +[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 summary + +The files used in this chapter are : + +![Synthesis of the files implemented in the network part](images/network-003.png) + +A complete interface configuration could be this (file `/etc/sysconfig/network-scripts/ifcfg-eth0`): + +``` + 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 +``` + +The troubleshooting method should go from closest to farthest: + +1. ping localhost (software test) +2. ping IP-address (hardware test) +3. ping gateway (connectivity test) +4. ping remote-server (routing test) +5. DNS query (dig or ping) + +![Method of troubleshooting or network validation](images/network-004.png) From 36fea070f6d33b109887c02d8c505a4309ad6843 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:51 -0500 Subject: [PATCH 17/37] New translations 13-softwares.md (French) --- docs/books/admin_guide/13-softwares.fr.md | 217 ++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 docs/books/admin_guide/13-softwares.fr.md diff --git a/docs/books/admin_guide/13-softwares.fr.md b/docs/books/admin_guide/13-softwares.fr.md new file mode 100644 index 0000000000..b377459dea --- /dev/null +++ b/docs/books/admin_guide/13-softwares.fr.md @@ -0,0 +1,217 @@ +--- +title: Software Management +--- + +# Software Management + +## Generalities + +On a Linux system, it is possible to install software in two ways: + +* Using an installation package; +* Compiling from source files. + +!!! Note Installing from source is not covered here. As a rule, you should use the package method unless the software you want is not available via the package manager. The reason for this is that dependencies are generally managed by the package system, whereas with source, you need to manage the dependencies manually. + +**The package**: This is a single file containing all the data needed to install the program. It can be executed directly on the system from a software repository. + +**The source files** : Some software is not provided in packages ready to be installed, but via an archive containing the source files. It is up to the administrator to prepare these files and compile them to install the program. + +## RPM : RedHat Package Manager + +**RPM** (RedHat Package Manager) is a software management system. It is possible to install, uninstall, update or check software contained in packages. + +**RPM** is the format used by all RedHat based distributions (RockyLinux, Fedora, CentOS, SuSe, Mandriva, ...). Its equivalent in the Debian world is DPKG (Debian Package). + +The name of an RPM package follows a specific nomenclature: + +![Illustration of a package name](images/software-001.png) + +### `rpm` command + +The rpm command allows you to install a package. + +``` +rpm [-i][-U] package.rpm [-e] package +``` + +Example (for a package named 'package'): + +``` +[root]# rpm -ivh package.rpm +``` + +| Option | Description | +| ---------------- | -------------------------------------------- | +| `-i package.rpm` | Installs the package. | +| `-U package.rpm` | Updates an already installed package. | +| `-e package.rpm` | Uninstalls the package. | +| `-h` | Displays a progress bar. | +| `-v` | Informs about the progress of the operation. | +| `--test` | Tests the command without executing it. | + +The `rpm` command also allows you to query the system package database by adding the `-q` option. + +It is possible to execute several types of queries to obtain different information about the installed packages. The RPM database is located in the directory `/var/lib/rpm`. + +Example: + +``` +[root]# rpm -qa +``` + +This command queries all the packages installed on the system. + +``` +rpm -q [-a][-i][-l] package [-f] file +``` + +Example: + +``` +[root]# rpm -qil package +[root]# rpm -qf /path/to/file +``` + +| Option | Description | +| ---------------- | ---------------------------------------------------------------------------------------------- | +| `-a` | Lists all packages installed on the system. | +| `-i __package__` | Displays the package information. | +| `-l __package__` | Lists the files contained in the package. | +| `-f` | Shows the name of the package containing the specified file. | +| `--last` | The list of packages is given by installation date (the last installed packages appear first). | + +!!! Warning After the `-q` option, the package name must be exact. Metacharacters (wildcards) are not supported. + +!!! Tip However, it is possible to list all installed packages and filter with the `grep` command. + +Example: list the last installed packages: + +``` +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 +``` + +Example: list the installation history of the kernel: + +``` +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 +``` + +Example: list all installed packages with a specific name using `grep`: + +``` +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**) is a software package manager, successor of **YUM** (**Yellow dog **U**pdater **M**odified). It works with **RPM** packages grouped in a local or remote repository (a directory for storing packages). For the most common commands, its usage is identical to that of `yum`. + +The `dnf` command allows the management of packages by comparing those installed on the system with those in the repositories defined on the server. It also automatically installs dependencies, if they are also present in the repositories. + +`dnf` is the manager used by many RedHat based distributions (RockyLinux, Fedora, CentOS, ...). Its equivalent in the Debian world is **APT** (**A**dvanced **P**ackaging **T**ool). + +### `dnf` command + +The dnf command allows you to install a package by specifying only the short name. + +``` +dnf [install][remove][list all][search][info] package +``` + +Example: + +``` +[root]# dnf install tree +``` + +Only the short name of the package is required. + +| Option | Description | +| ------------------------- | --------------------------------------------- | +| `install` | Installs the package. | +| `remove` | Uninstall the package. | +| `list all` | Lists the packages already in the repository. | +| `search` | Search for a package in the repository. | +| `provides */command_name` | Search for a command. | +| `info` | Displays the package information. | + +The `dnf list` command lists all the packages installed on the system and present in the repository. It accepts several parameters: + +| Parameter | Description | +| ----------- | -------------------------------------------------------------------------- | +| `all` | Lists the installed packages and then those available on the repositories. | +| `available` | Lists only the packages available for installation. | +| `updates` | Lists packages that can be upgraded. | +| `obsoletes` | Lists the packages made obsolete by higher versions available. | +| `recent` | Lists the latest packages added to the repository. | + +Example of a search for the `semanage` command: + +``` +[root]# dnf provides */semanage +``` + +### How DNF works + +The DNF manager relies on one or more configuration files to target the repositories containing the RPM packages. + +These files are located in `/etc/yum.repos.d/` and must end with `.repo` in order to be used by DNF. + +Example: + +``` +/etc/yum.repos.d/Rocky-BaseOS.repo +``` + +Each `.repo` file consists of at least the following information, one directive per line. + +Example: + +``` +[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 +``` + +By default, the `enabled` directive is absent which means that the repository is enabled. To disable a repository, you must specify the `enabled=0` directive. + +## The EPEL repository + +**EPEL** (**E**xtra **P**ackages for **E**nterprise **L**inux) is a repository containing additional software packages for Enterprise Linux, which includes RedHat Enterprise Linux (RHEL), RockyLinux, CentOS, etc. + +### Installation + +Download and install the rpm from the repository: + +If you are behind an internet proxy: + +``` +[root]# export http_proxy=http://172.16.1.10:8080 +``` + +Then: + +``` +[root]# dnf install epel-release +``` From 29dd9e53d1983e04e7494f899959dd724f09cbeb Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:52 -0500 Subject: [PATCH 18/37] New translations 13-softwares.md (Italian) --- docs/books/admin_guide/13-softwares.it.md | 217 ++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 docs/books/admin_guide/13-softwares.it.md diff --git a/docs/books/admin_guide/13-softwares.it.md b/docs/books/admin_guide/13-softwares.it.md new file mode 100644 index 0000000000..ef192b9cac --- /dev/null +++ b/docs/books/admin_guide/13-softwares.it.md @@ -0,0 +1,217 @@ +--- +title: Gestione del software +--- + +# 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. + +``` +rpm [-i][-U] package.rpm [-e] package +``` + +Esempio (per un pacchetto denominato 'package'): + +``` +[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: + +``` +[root]# rpm -qa +``` + +Questo comando esegue una ricerca su tutti i pacchetti installati nel sistema. + +``` +rpm -q [-a][-i][-l] package [-f] file +``` + +Esempio: + +``` +[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: + +``` +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: + +``` +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': + +``` +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. + +``` +dnf [install][remove][list all][search][info] package +``` + +Esempio: + +``` +[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`: + +``` +[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: + +``` +/etc/yum.repos.d/Rocky-BaseOS.repo +``` + +Ogni file `.repo` è costituito da almeno le seguenti informazioni, una direttiva per riga. + +Esempio: + +``` +[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: + +``` +[root]# export http_proxy=http://172.16.1.10:8080 +``` + +Quindi: + +``` +[root]# dnf install epel-release +``` From 266ad0314fe0b75009d8428dc33b9e318ed9be62 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:53 -0500 Subject: [PATCH 19/37] New translations 08-process.md (French) --- docs/books/admin_guide/08-process.fr.md | 374 ++++++++++++++++++++++++ 1 file changed, 374 insertions(+) create mode 100644 docs/books/admin_guide/08-process.fr.md diff --git a/docs/books/admin_guide/08-process.fr.md b/docs/books/admin_guide/08-process.fr.md new file mode 100644 index 0000000000..7235f3aa5c --- /dev/null +++ b/docs/books/admin_guide/08-process.fr.md @@ -0,0 +1,374 @@ +--- +title: Process Management +--- + +# Process Management + +In this chapter you will learn how to work with processes. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: Recognize the `PID` and `PPID` of a process; +:heavy_check_mark: View and search for processes; +:heavy_check_mark: Manage processes. + +:checkered_flag: **process**, **linux** + +**Knowledge**: :star: :star: +**Complexity**: :star: + +**Temps de lecture : **20 minutes + +**** + +## Generalities + +An operating system consists of processes. These processes are executed in a specific order and are related to each other. There are two categories of processes, those focused on the user environment and those focused on the hardware environment. + +When a program runs, the system will create a process by placing the program data and code in memory and creating a **runtime stack**. A process is therefore an instance of a program with an associated processor environment (ordinal counter, registers, etc...) and memory environment. + +Each process has: + +* a _PID_ : _**P**rocess **ID**entifier_, a unique process identifier; +* a _PPID_ : _**P**arent **P**rocess **ID**entifier_, unique identifier of parent process. + +By successive filiations, the `init` process is the father of all processes. + +* A process is always created by a parent process; +* A parent process can have multiple child processes. + +There is a parent/child relationship between processes. A child process is the result of the parent process calling the _fork()_ primitive and duplicating its own code to create a child. The _PID_ of the child is returned to the parent process so that it can talk to it. Each child has its parent's identifier, the _PPID_. + +The _PID_ number represents the process at the time of execution. When the process finishes, the number is available again for another process. Running the same command several times will produce a different _PID_ each time.!!! Note Processes are not to be confused with _threads_. Each process has its own memory context (resources and address space), while _threads_ from the same process share this same context. + +## Viewing processes + +The `ps` command displays the status of running processes. +``` +ps [-e] [-f] [-u login] +``` + +Example: +``` +# ps -fu root +``` + +| Option | Description | +| ---------- | -------------------------------- | +| `-e` | Displays all processes. | +| `-f` | Displays additional information. | +| `-u` login | Displays the user's processes. | + +Some additional options: + +| Option | Description | +| --------------------- | ------------------------------------------------- | +| `-g` | Displays the processes in the group. | +| `-t tty` | Displays the processes running from the terminal. | +| `-p PID` | Displays the process information. | +| `-H` | Displays the information in a tree structure. | +| `-I` | Displays additional information. | +| `--sort COL` | Sort the result according to a column. | +| `--headers` | Displays the header on each page of the terminal. | +| `--format "%a %b %c"` | Customize the output display format. | + +Without an option specified, the `ps` command only displays processes running from the current terminal. + +The result is displayed in columns: + +``` +# ps -ef +UID PID PPID C STIME TTY TIME CMD +root 1 0 0 Jan01 ? 00:00/03 /sbin/init +``` + +| Column | Description | +| ------- | --------------------------- | +| `UID` | Owner user. | +| `PID` | Process identifier. | +| `PPID` | Parent process identifier. | +| `C` | Priority of the process. | +| `STIME` | Date and time of execution. | +| `TTY` | Execution terminal. | +| `TIME` | Processing duration. | +| `CMD` | Command executed. | + +The behaviour of the control can be fully customized: + +``` +# 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 +``` + +## Types of processes + +The user process: + +* is started from a terminal associated with a user; +* accesses resources via requests or daemons. + +The system process (_demon_): + +* is started by the system; +* is not associated with any terminal, and is owned by a system user (often `root`); +* is loaded at boot time, resides in memory, and is waiting for a call; +* is usually identified by the letter `d` associated with the process name. + +System processes are therefore called daemons (_**D**isk **A**nd **E**xecution **MON**itor_). + +## Permissions and rights + +When a command is executed, the user's credentials are passed to the created process. + +By default, the actual `UID` and `GID` (of the process) are therefore identical to the **actual** `UID` and `GID` (the `UID` and `GID` of the user who executed the command). + +When a `SUID` (and/or `SGID`) is set on a command, the actual `UID` (and/or `GID`) becomes that of the owner (and/or owner group) of the command and no longer that of the user or user group that issued the command. Effective and real **UIDs** are therefore **different**. + +Each time a file is accessed, the system checks the rights of the process according to its effective identifiers. + +## Process management + +A process cannot be run indefinitely, as this would be to the detriment of other running processes and would prevent multitasking. + +The total processing time available is therefore divided into small ranges, and each process (with a priority) accesses the processor in a sequenced manner. The process will take several states during its life among the states: + +* ready: waiting for the availability of the process; +* in execution: accesses the processor; +* suspended: waiting for an I/O (input/output); +* stopped: waiting for a signal from another process; +* zombie: request for destruction; +* dead: the father of the process kills his son. + +The end of process sequencing is as follows: + +1. Closing of the open files; +2. Release of the used memory; +3. Sending a signal to the parent and child processes. + +When a parent process dies, its children are said to be orphans. They are then adopted by the `init` process which will destroy them. + +### The priority of a process + +The processor works in time sharing with each process occupying a quantity of processor time. + +The processes are classified by priority whose value varies from **-20** (the highest priority) to **+19** (the lowest priority). + +The default priority of a process is **0**. + +### Modes of operation + +Processes can run in two ways: + +* **synchronous**: the user loses access to the shell during command execution. The command prompt reappears at the end of the process execution. +* **asynchronous**: the process is processed in the background. The command prompt is displayed again immediately. + +The constraints of the asynchronous mode: + +* the command or script must not wait for keyboard input; +* the command or script must not return any result on the screen; +* quitting the shell ends the process. + +## Process management controls + +### `kill` command + +The `kill` command sends a stop signal to a process. + +``` +kill [-signal] PID +``` + +Example: +``` +$ kill -9 1664 +``` + +| Code | Signal | Description | +| ---- | --------- | ------------------------------------ | +| `2` | _SIGINT_ | Immediate termination of the process | +| `9` | _SIGKILL_ | Interrompre le processus (CTRL+D) | +| `15` | _SIGTERM_ | Clean termination of the process | +| `18` | _SIGCONT_ | Resume the process | +| `19` | _SIGSTOP_ | Suspend the process | + +Signals are the means of communication between processes. The `kill` command sends a signal to a process. + +!!! Tip The complete list of signals taken into account by the `kill` command is available by typing the command : +``` +$ man 7 signal +``` + +### `nohup` command + +`nohup` allows the launching of a process independently of a connection. + +``` +nohup command +``` + +Example: +``` +$ nohup myprogram.sh 0CTRL + Z keys simultaneously, the synchronous process is temporarily suspended. Access to the prompt is restored after displaying the number of the process that has just been suspended. + +### `&` instruction + +The `&` statement executes the command asynchronously (the command is then called _job_) and displays the number of _job_. Access to the prompt is then returned. + +Example: +``` +$ time ls -lR / > list.ls 2> /dev/null & +[1] 15430 +$ +``` + +The _job_ number is obtained during background processing and is displayed in square brackets, followed by the `PID` number. + +### `fg` and `bg` commands + +The `fg` command puts the process in the foreground: + +``` +$ time ls -lR / > list.ls 2>/dev/null & +$ fg 1 +time ls -lR / > list.ls 2/dev/null +``` + +while the command `bg` places it in the background: + +``` +[CTRL]+[Z] +^Z +[1]+ Stopped +$ bg 1 +[1] 15430 +$ +``` + +Whether it was put in the background when it was created with the `&` argument or later with the CTRL +Z keys, a process can be brought back to the foreground with the `fg` command and its job number. + +### `jobs` command + +The `jobs` command displays the list of processes running in the background and specifies their job number. + +Example: +``` +$ jobs +[1]- Running sleep 1000 +[2]+ Running find / > arbo.txt +``` + +The columns represent: + +1. job number; +2. the order in which the processes run +- a `+` : this process is the next process to run by default with `fg` or `bg` ; +- a `-` : this process is the next process to take the `+` ; +3. _Running_ (running process) or _Stopped_ (suspended process). +4. the command + +### `nice` and `renice` commands + +The command `nice` allows the execution of a command by specifying its priority. + +``` +nice priority command +``` + +Example: +``` +$ nice -n+15 find / -name "file" +``` + +Unlike `root`, a standard user can only reduce the priority of a process. Only values between +0 and +19 will be accepted. + +!!! Tip This last limitation can be lifted on a per-user or per-group basis by modifying the `/etc/security/limits.conf` file. + +The `renice` command allows you to change the priority of a running process. + +``` +renice priority [-g GID] [-p PID] [-u UID] +``` + +Example: +``` +$ renice +15 -p 1664 +``` +| Option | Description | +| ------ | --------------------------------- | +| `-g` | `GID` of the process owner group. | +| `-p` | `PID` of the process. | +| `-u` | `UID` of the process owner. | + +The `renice` command acts on processes already running. It is therefore possible to change the priority of a specific process, but also of several processes belonging to a user or a group. + +!!! Tip The `pidof` command, coupled with the `xargs` command (see the Advanced Commands course), allows a new priority to be applied in a single command: +``` +$ pidof sleep | xargs renice 20 +``` + +### `top` command + +The `top` command displays the processes and their resource consumption. + +``` +$ top +PID USER PR NI ... %CPU %MEM TIME+ COMMAND +2514 root 20 0 15 5.5 0:01.14 top +``` + +| Column | Description | +| --------- | --------------------- | +| `PID` | Process identifier. | +| `USER` | Owner user. | +| `PR` | Process priority. | +| `NI` | Nice value. | +| `%CPU` | Processor load. | +| `%MEM` | Memory load. | +| `TIME+` | Processor usage time. | +| `COMMAND` | Command executed. | + +The `top` command allows control of the processes in real time and in interactive mode. + +### `pgrep` and `pkill` commands + +The `pgrep` command searches the running processes for a process name and displays the _PID_ matching the selection criteria on the standard output. + +The `pkill` command will send the specified signal (by default _SIGTERM_) to each process. + +``` +pgrep process +pkill [-signal] process +``` + +Examples: + +* Get the process number from `sshd`: + +``` +$ pgrep -u root sshd +``` + +* Kill all `tomcat` processes: + +``` +$ pkill tomcat +``` From 86245cf0efd4eb985775bb2978ac7e4dd8844fdd Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:55 -0500 Subject: [PATCH 20/37] New translations 07-file-systems.md (Italian) --- docs/books/admin_guide/07-file-systems.it.md | 292 +++++++++---------- 1 file changed, 137 insertions(+), 155 deletions(-) diff --git a/docs/books/admin_guide/07-file-systems.it.md b/docs/books/admin_guide/07-file-systems.it.md index 2b03350218..20578e8b39 100644 --- a/docs/books/admin_guide/07-file-systems.it.md +++ b/docs/books/admin_guide/07-file-systems.it.md @@ -2,11 +2,11 @@ title: File System --- -# File system +# File System In questo capitolo imparerai come lavorare con il filesystem. ---- +**** **Obiettivi** : In questo capitolo, futuri amministratori Linux impareranno come: @@ -17,7 +17,7 @@ In questo capitolo imparerai come lavorare con il filesystem. e anche scoprire: :heavy_check_mark: come è organizzata la struttura ad albero in Linux; -:heavy_check_mark: i diversi tipi di file offerti e come lavorare con loro; +:heavy_check_mark: i diversi tipi di file offerti e come lavorare con loro; :checkered_flag: **hardware**, **disco**, **partizioni**, **lvm**, **linux** @@ -26,7 +26,7 @@ e anche scoprire: **Tempo di lettura**: 20 minuti ---- +**** ## Partizionamento @@ -39,8 +39,7 @@ Lo stesso disco fisico può essere diviso in un massimo di 4 partizioni: * *Primary* (o main) * *Extended* -!!! Warning "Avvertimento" - Ci può essere solo una partizione estesa per disco fisico. Al fine di beneficiare di ulteriori unità, la partizione estesa può essere suddivisa in partizioni logiche +!!! Warning "Avvertimento" Ci può essere solo una partizione estesa per disco fisico. Al fine di beneficiare di ulteriori unità, la partizione estesa può essere suddivisa in partizioni logiche ![Breakdown into only 4 primary partitions](images/07-file-systems-001.png) @@ -55,7 +54,7 @@ I dispositivi di archiviazione sono denominati *hd* per i dischi rigidi IDE e *s Finalmente troveremo un numero che definisce il volume partizionato: *1* per la prima partizione primaria, ... !!! Warning "Avvertimento" - Attenzione, la partizione estesa, che non supporta un file system, ha ancora un numero. +Attenzione, la partizione estesa, che non supporta un file system, ha ancora un numero. ![Identification of partitions](images/07-file-systems-003.png) @@ -63,7 +62,7 @@ Ci sono almeno due comandi per il partizionamento di un disco: `fdisk` e `cfdisk L'unico motivo per usare `fdisk` è quando vuoi elencare tutti i dispositivi logici con l'opzione `-l`. -```bash +``` sudo fdisk -l sudo fdisk -l /dev/sdc sudo fdisk -l /dev/sdc2 @@ -73,7 +72,7 @@ sudo fdisk -l /dev/sdc2 Il comando `parted` (_partition editor_) è in grado di partizionare un disco. -```bash +``` parted [-l] [device] ``` @@ -93,13 +92,13 @@ Il comando `gparted` da solo tornerà a una modalità interattiva con le propri Il comando `cfdisk` è usato per gestire le partizioni. -```bash +``` cfdisk device ``` Esempio: -```bash +``` $ sudo cfdisk /dev/sda Disk: /dev/sda Size: 16 GiB, 17179869184 bytes, 33554432 sectors @@ -143,13 +142,11 @@ Lo svantaggio è che se uno dei volumi fisici va fuori servizio, allora tutti i LVM è disponibile in Linux dalla versione del kernel 2.4. !!! Note "Nota" - LVM è gestito solo dal sistema operativo. Quindi, il _BIOS_ ha bisogno di almeno una partizione senza LVM per avviarsi. +LVM è gestito solo dal sistema operativo. Quindi, il _BIOS_ ha bisogno di almeno una partizione senza LVM per avviarsi. ### Gruppi di volumi -I volumi fisici *PV* _Physical Volumes_ (dalle partizioni) sono combinati in gruppi di volumi *VG*. -Ogni *VG* rappresenta lo spazio su disco che può essere partizionato in *LV* _Logical Volumes_. -*Extension* è la più piccola unità di spazio a dimensione fissa che può essere assegnata. +I volumi fisici *PV* _Physical Volumes_ (dalle partizioni) sono combinati in gruppi di volumi *VG*. Ogni *VG* rappresenta lo spazio su disco che può essere partizionato in *LV* _Logical Volumes_. *Extension* è la più piccola unità di spazio a dimensione fissa che può essere assegnata. * **PE** : _Physical Extension_ * **LE** : _Logical Extension_ @@ -168,8 +165,7 @@ Un gruppo di volumi, *VG*, è diviso in volumi logici, *LV*, offrendo diverse mo ![Volumes in stripe mode](images/07-file-systems-006.png) -!!! Tip "Suggerimento" - _Striping_ migliora le prestazioni scrivendo i dati a un numero predeterminato di volumi fisici con una tecnica _round-robin_. +!!! Tip "Suggerimento" _Striping_ migliora le prestazioni scrivendo i dati a un numero predeterminato di volumi fisici con una tecnica _round-robin_. ![Mirrored volumes](images/07-file-systems-007.png) @@ -179,39 +175,39 @@ Un gruppo di volumi, *VG*, è diviso in volumi logici, *LV*, offrendo diverse mo Il comando `pvcreate` è usato per creare volumi fisici. Comprende partizioni Linux (o dischi) in volumi fisici. -```bash +``` pvcreate [-options] partition ``` Esempio: -```bash +``` [root]# pvcreate /dev/hdb1 pvcreate -- physical volume « /dev/hdb1 » successfully created ``` Puoi anche usare un disco intero (che facilita l'aumento della dimensione del disco in ambienti virtuali per esempio). -```bash +``` [root]# pvcreate /dev/hdb pvcreate -- physical volume « /dev/hdb » successfully created ``` -| Opzione | Descrizione | -| ------- | ----------------------------------------------------- ---------------------- | -| `-f` | Costringe la creazione del volume (disco già trasformato in volume fisico). | +| Opzione | Descrizione | +| ------- | --------------------------------------------------------------------------- | +| `-f` | Costringe la creazione del volume (disco già trasformato in volume fisico). | #### comando `vgcreate` Il comando `vgcreate` è usato per creare gruppi di volumi. Raggruppa uno o più volumi fisici in un gruppo di volumi. -```bash +``` vgcreate volume physical_volume [PV...] ``` Esempio: -```bash +``` [root]# vgcreate volume1 /dev/hdb1 … vgcreate – volume group « volume1 » successfully created and activated @@ -221,13 +217,13 @@ vgcreate – volume group « volume1 » successfully created and activated Il comando `lvcreate` crea volumi logici. Il file system viene quindi creato su questi volumi logici. -```bash +``` lvcreate -L size [-n name] VG_name ``` Esempio: -```bash +``` [root]# lvcreate –L 600M –n VolLog1 volume1 lvcreate -- logical volume « /dev/volume1/VolLog1 » successfully created ``` @@ -243,13 +239,13 @@ lvcreate -- logical volume « /dev/volume1/VolLog1 » successfully created Il comando `pvdisplay` consente di visualizzare informazioni sui volumi fisici. -```bash +``` pvdisplay /dev/PV_name ``` Esempio: -```bash +``` [root]# pvdisplay /dev/PV_name ``` @@ -257,13 +253,13 @@ Esempio: Il comando `vgdisplay` ti consente di visualizzare informazioni sui gruppi di volumi. -```bash +``` vgdisplay VG_name ``` Esempio: -```bash +``` [root]# vgdisplay volume1 ``` @@ -271,13 +267,13 @@ Esempio: Il comando `lvdisplay` ti permette di visualizzare le informazioni sui volumi logici. -```bash +``` lvdisplay /dev/VG_name/LV_name ``` Esempio: -```bash +``` [root]# lvdisplay /dev/volume1/VolLog1 ``` @@ -309,13 +305,13 @@ Il sistema operativo Linux è in grado di utilizzare diversi file system (ext2, Il comando `mkfs` consente di creare un file system Linux. -```bash +``` mkfs [-t fstype] filesys ``` Esempio: -```bash +``` [root]# mkfs -t ext4 /dev/sda1 ``` @@ -324,12 +320,12 @@ Esempio: | `-t` | Indica il tipo di file system da utilizzare. | !!! Warning "Avvertimento" - Senza un file system non è possibile utilizzare lo spazio su disco. +Senza un file system non è possibile utilizzare lo spazio su disco. Ogni file system ha una struttura identica su ciascuna partizione. Un **boot block** e **super block** inizializzato dal sistema e poi un **inode table** e una **data area** inizializzata dall'amministratore. !!! Note "Nota" - L'unica eccezione è la partizione **swap**. +L'unica eccezione è la partizione **swap**. ### Blocco di avvio @@ -360,7 +356,7 @@ Quando il sistema viene fermato, viene copiata anche questa tabella sull'hard di La dimensione della **tabella inode** è definito alla sua creazione ed è memorizzato sulla partizione. Consiste di record, chiamati inodes, corrispondenti ai file creati. Ogni record contiene gli indirizzi dei blocchi di dati che costituiscono il file. !!! Note "Nota" - Un numero inode è unico all'interno di un file system. +Un numero inode è unico all'interno di un file system. Una copia viene caricata nella memoria centrale non appena il sistema è inizializzato. Questa copia viene aggiornata non appena viene modificata e il sistema la salva periodicamente (comando `sync`). @@ -369,7 +365,7 @@ Quando il sistema viene fermato, viene copiata anche questa tabella sull'hard di Un file è gestito dal suo numero di inode. !!! Note "Nota" - La dimensione della tabella di inode determina il numero massimo di file che il file system può contenere. +La dimensione della tabella di inode determina il numero massimo di file che il file system può contenere. Informazioni presenti nella *tabella inode* : @@ -393,7 +389,7 @@ La sua dimensione corrisponde al resto dello spazio disponibile nella partizione Quando il sistema viene fermato, viene copiata anche questa tabella sull'hard disk !!! Danger "Pericolo" - In caso di fermata improvvisa, il file system potrebbe perdere la sua coerenza e causare la perdita di dati. +In caso di fermata improvvisa, il file system potrebbe perdere la sua coerenza e causare la perdita di dati. ### Riparazione del file system @@ -405,19 +401,19 @@ In caso di errori, vengono proposte le soluzioni per riparare le incoerenze. Dop Il comando `fsck` è uno strumento di controllo e riparazione di integrità in modalità console per i file system Linux. -```bash +``` fsck [-sACVRTNP] [ -t fstype ] filesys ``` Esempio: -```bash +``` [root]# fsck /dev/sda1 ``` Per controllare la partizione root, è possibile creare un file `forcefsck` e riavviare o eseguire `shutdown` con l'opzione `-F`. -```bash +``` [root]# touch /forcefsck [root]# reboot or @@ -425,7 +421,7 @@ or ``` !!! Warning "Avvertimento" - La partizione da controllare deve essere smontata. +La partizione da controllare deve essere smontata. ## Organizzazione di un file system @@ -433,32 +429,31 @@ Per definizione, un file system è una struttura ad albero delle directory creat ![Organization of a file system](images/07-file-systems-008.png) -!!! Note "Nota" - In Linux tutto è un file. +!!! Nota In Linux tutto è un file. Documento di testo, directory, file binario, partizione, risorse di rete, schermo, tastiera, Unix kernel, programma utente, ... Linux segue il **FHS** (_Filesystems Hierarchy Standard_) (vedi `man hier`) che definisce i nomi delle cartelle e dei loro ruoli. -| Directory | Osservazione | Abbreviazione di | -| ---------- | ------------------------------------------------------------------------ | ----------------------------- | -| `/` | Contiene directory speciali | | -| `/boot` | File relativi all'avvio del sistema | | -| `/sbin` | Comandi necessari per l'avvio e la riparazione del sistema | _system binaries_ | -| `/bin` | Eseguibili dei comandi di base del sistema | _binaries_ | -| `/usr/bin` | Comandi di amministrazione del sistema | | -| `/lib` | Librerie condivise e moduli del kernel | _libraries_ | -| `/usr` | Tutto ciò che non è necessario per il funzionamento minimo del sistema | _UNIX System Resources_ | -| `/mnt` | Per il montaggio temporaneo dei file system | _mount_ | -| `/media` | Per il montaggio dei supporti rimovibili | | -| `/root` | Directory di accesso dell'amministratore | | -| `/home` | Dati utente | | -| `/tmp` | File temporanei | _temporary_ | -| `/dev` | File di dispositivo speciali | _device_ | -| `/etc` | File di configurazione e script | _editable text configuration_ | -| `/opt` | Specifica per applicazioni installate | _optional_ | -| `/proc` | Sistema virtuale che rappresenta processi diversi | _processes_ | -| `/var` | File di vario genere variabili. | _variables_ | +| Directory | Osservazione | Abbreviazione di | +| ---------- | ---------------------------------------------------------------------- | ----------------------------- | +| `/` | Contiene directory speciali | | +| `/boot` | File relativi all'avvio del sistema | | +| `/sbin` | Comandi necessari per l'avvio e la riparazione del sistema | _system binaries_ | +| `/bin` | Eseguibili dei comandi di base del sistema | _binaries_ | +| `/usr/bin` | Comandi di amministrazione del sistema | | +| `/lib` | Librerie condivise e moduli del kernel | _libraries_ | +| `/usr` | Tutto ciò che non è necessario per il funzionamento minimo del sistema | _UNIX System Resources_ | +| `/mnt` | Per il montaggio temporaneo dei file system | _mount_ | +| `/media` | Per il montaggio dei supporti rimovibili | | +| `/root` | Directory di accesso dell'amministratore | | +| `/home` | Dati utente | | +| `/tmp` | File temporanei | _temporary_ | +| `/dev` | File di dispositivo speciali | _device_ | +| `/etc` | File di configurazione e script | _editable text configuration_ | +| `/opt` | Specifica per applicazioni installate | _optional_ | +| `/proc` | Sistema virtuale che rappresenta processi diversi | _processes_ | +| `/var` | File di vario genere variabili. | _variables_ | * Per montare o smontare, a livello dell'albero, non devi essere sotto il suo punto di montaggio. * Il montaggio su una directory non vuota non elimina il contenuto. Viene solamente nascosto. @@ -469,10 +464,9 @@ Linux segue il **FHS** (_Filesystems Hierarchy Standard_) (vedi `man hier`) che Il file `/etc/fstab` viene letto all'avvio del sistema e contiene i supporti da montare. Ogni file system da montare è descritto su una singola riga, I campi sono separati da spazi o tabulazioni. -!!! Note "Nota" - Le linee sono lette in sequenza (`fsck`, `mount`, `umount`). +!!! Nota Le linee sono lette sequenzialmente (`fsck`, `mount`, `umount`). -```bash +``` /dev/mapper/VolGroup-lv_root / ext4 defaults 1 1 UUID=46….92 /boot ext4 defaults 1 2 /dev/mapper/VolGroup-lv_swap swap swap defaults 0 0 @@ -483,20 +477,19 @@ proc /proc proc defaults 0 0 1 2 3 4 5 6 ``` -| Colonna | Descrizione | -| ------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| 1 | Dispositivo di file system. (`/dev/sda1`, UUID=..., ...) | -| 2 | Nome del punto di montaggio, **absolute path** (tranne **swap**) | -| 3 | Tipo di filesystem. (ext4, swap, ...) | -| 4 | Opzioni speciali per il montaggio (`defaults`, `ro`, ...) | -| 5 | Abilita o disabilita la gestione del backup (0:niente backup, 1:backup) | -| 6 | Controllare l'ordine quando si controlla il file system con il comando`fsck` (0:nessun controllo, 1:priorità, 2:nessuna priorità) | +| Colonna | Descrizione | +| ------- | --------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Dispositivo di file system. (`/dev/sda1`, UUID=..., ...) | +| 2 | Nome del punto di montaggio, **absolute path** (tranne **swap**) | +| 3 | Tipo di filesystem. (ext4, swap, ...) | +| 4 | Opzioni speciali per il montaggio (`defaults`, `ro`, ...) | +| 5 | Abilita o disabilita la gestione del backup (0:niente backup, 1:backup) | +| 6 | Controllare l'ordine quando si controlla il file system con il comando`fsck` (0:nessun controllo, 1:priorità, 2:nessuna priorità) | -Il comando `mount -a` consente di montare i nuovi punti di montaggio senza riavvio. -Vengono quindi scritti nel file `/etc/mtab` che contiene i supporti correnti. +Il comando `mount -a` consente di montare i nuovi punti di montaggio senza riavvio. Vengono quindi scritti nel file `/etc/mtab` che contiene i supporti correnti. !!! Warning "Avvertimento" - Solo i punti di montaggio elencati in `/etc/fstab` saranno montati al riavvio. +Solo i punti di montaggio elencati in `/etc/fstab` saranno montati al riavvio. È possibile fare una copia del file `/etc/mtab` o copiare il suo contenuto in `/etc/fstab`. @@ -506,13 +499,13 @@ Vengono quindi scritti nel file `/etc/mtab` che contiene i supporti correnti. Il comando `mount` permette di montare e visualizzare le unità logiche nell'albero. -```bash +``` mount [-option] [device] [directory] ``` Esempio: -```bash +``` [root]# mount /dev/sda7 /home ``` @@ -526,19 +519,19 @@ Esempio: | `-o` | Argomento seguito da un elenco di opzioni separate da virgole (`remount`, `ro`, ...). | !!! Note "Nota" - Il comando `mount` da solo visualizza tutti i file system montati. +Il comando `mount` da solo visualizza tutti i file system montati. #### comando `umount` Il comando `umount` è usato per smontare le unità logiche. -```bash +``` umount [-option] [device] [directory] ``` Esempio: -```bash +``` [root]# umount /home [root]# umount /dev/sda7 ``` @@ -551,7 +544,7 @@ Esempio: | `-a` | Smontare tutti i filesystem menzionati in`/etc/fstab`. | !!! Note "Nota" - Quando si smontano, non devi essere posizionato al di sotto del punto di montaggio. Altrimenti, viene visualizzato il seguente messaggio di errore: `device is busy`. +Quando si smontano, non devi essere posizionato al di sotto del punto di montaggio. Altrimenti, viene visualizzato il seguente messaggio di errore: `device is busy`. ## Tipi di file @@ -564,18 +557,18 @@ Come in qualsiasi sistema, è importante rispettare le regole di denominazione d I gruppi di parole separati da spazi devono essere racchiusi tra virgolette: -```bash +``` [root]# mkdir "working dir" ``` !!! Note "Nota" - Anche se non c'è nulla di tecnicamente sbagliato nel creare un file o una directory con uno spazio in esso, generalmente è una "_pratica migliore_" evitarlo e sostituire qualsiasi spazio con una sottolineatura. +Anche se non c'è nulla di tecnicamente sbagliato nel creare un file o una directory con uno spazio in esso, generalmente è una "_pratica migliore_" evitarlo e sostituire qualsiasi spazio con una sottolineatura. !!! Note "Nota" - Il **.** all'inizio del nome del file serve solo a nasconderlo da un semplice `ls`. +Il **.** all'inizio del nome del file serve solo a nasconderlo da un semplice `ls`. !!! Warning "Avvertimento" - In Linux, l'estensione di un file non è un riferimento necessario per aprirlo o modificarlo. Tuttavia, può essere utile per l'utente. +In Linux, l'estensione di un file non è un riferimento necessario per aprirlo o modificarlo. Tuttavia, può essere utile per l'utente. Esempi di estensioni comuni: @@ -590,7 +583,7 @@ Esempi di estensioni comuni: ### Dettagli di un nome del file -```bash +``` [root]# ls -liah /usr/bin/passwd 266037 -rwsr-xr-x 1 root root 59K mars 22 2019 /usr/bin/passwd 1 2 3 4 5 6 7 8 9 @@ -622,7 +615,7 @@ I seguenti tipi di file possono essere trovati su un sistema: Questi sono testo, programmmi (sorgente), eseguibile (dopo la compilazione) o dati (binari, ASCII) e file multimediali. -```bash +``` [root]# ls -l myfile -rwxr-xr-x 1 root root 26 nov 31 15:21 myfile ``` @@ -638,7 +631,7 @@ Per impostazione predefinita in ogni directory sono presenti **.** e **..**. * IL **.** rappresenta la posizione nell'albero. * Il **..** rappresenta il padre della posizione corrente. -```bash +``` [root]# ls -l mydirectory drwxr-xr-x 1 root root 26 nov 31 15:21 mydirectory ``` @@ -660,7 +653,7 @@ Sono definiti in due modalità: Il file speciale **modo block** consente, utilizzando i buffer di sistema, di trasferire i dati sul dispositivo. -```bash +``` [root]# ls -l /dev/sda brw------- 1 root root 8, 0 jan 1 1970 /dev/sda ``` @@ -673,7 +666,7 @@ Il file speciale *character mode* viene utilizzato per trasferire i dati sul dis L'output standard è lo screen. -```bash +``` [root]# ls -l /dev/tty0 crw------- 1 root root 8, 0 jan 1 1970 /dev/tty0 ``` @@ -684,8 +677,8 @@ La lettera `c` all'inizio del gruppo dei permessi indica che è un file speciale Questi sono le pipe (_pipes_) e i file _socket_ . -* I **files Pipe** passano le informazioni tra i processi con FIFO (_First In, First Out_). - Un processo scrive informazioni transitorie nel file di _pipe_ e un altro lo legge. Dopo averlo letto, le informazioni non sono più accessibili. +* I **files Pipe** passano le informazioni tra i processi con FIFO (_First In, First Out_). Un processo scrive informazioni transitorie nel file di _pipe_ e un altro lo legge. Dopo averlo letto, le informazioni non sono più accessibili. + * **Socket files** consentono la comunicazione bidirezionale intertrattativa (sui sistemi locali o remoti). Usano un _inode_ del file system. #### Files di Link @@ -702,22 +695,22 @@ Esistono due tipi di file link: Il file di collegamento e il file di origine hanno lo stesso numero di _inode_ e il contatore dei collegamenti viene incrementato. Non è possibile collegare diverse directory o files da file system diversi. !!! Warning "Avvertimento" - Se il file sorgente viene distrutto, il contatore viene decrementato e il file di collegamento accede ancora al file. +Se il file sorgente viene distrutto, il contatore viene decrementato e il file di collegamento accede ancora al file. ###### Commando `ln` per un link fisico Il comando `ln` permette di creare i collegamenti fisici. -```bash +``` [root]# ls –li letter 666 –rwxr--r-- 1 root root … letter ``` -```bash +``` [root]# ln /home/paul/letter /home/jack/read ``` -```bash +``` [root]# ls –li /home/*/* 666 –rwxr--r-- 2 root root … letter 666 –rwxr--r-- 2 root root … read @@ -732,22 +725,22 @@ A differenza del collegamento fisico, il link simbolico coinvolge la creazione d Il file creato contiene solo un'indicazione del percorso verso il file. Questa nozione non ha più le limitazioni dei collegamenti fisici ed è ora possibile collegare directory e file appartenenti a diversi file system. !!! Warning "Avvertimento" - Se il file sorgente viene distrutto, il file di link non può più accedere al file. +Se il file sorgente viene distrutto, il file di link non può più accedere al file. ###### comando `ln` per un link simbolico Il comando `ln` con l'argomento `-s` permette di creare collegamenti simbolici. -```bash +``` [root]# ls –li letter 666 -rwxr--r-- 1 root root … letter ``` -```bash +``` [root]# ln -s /home/paul/letter /tmp/read ``` -```bash +``` [root]# ls –li /home/paul/letter /tmp/read 666 -rwxr--r--- 1 root root … letter 678 lrwxrwxrwx 1 root root … read -> letter @@ -774,7 +767,7 @@ Ci sono 4 diritti di accesso ai file: * **-** no right. (nessun diritto) !!! Warning "Avvertimento" - I diritti associati ai file differiscono da quelli associati alle directory (vedi sotto). +I diritti associati ai file differiscono da quelli associati alle directory (vedi sotto). I tipi di utente associati ai diritti di accesso ai file sono: @@ -794,7 +787,7 @@ In alcuni comandi è possibile designare tutti con **a** (_all_). * **-**: Nessuna autorizzazione. !!! Note "Nota" - Spostare o rinominare un file dipende dai permessi della directory di destinazione. Eliminazione di un file dipende dai permessi della directory principale. +Spostare o rinominare un file dipende dai permessi della directory di destinazione. Eliminazione di un file dipende dai permessi della directory principale. ### Permessi associati alle directory @@ -807,7 +800,7 @@ In alcuni comandi è possibile designare tutti con **a** (_all_). La visualizzazione dei permessi viene eseguita con il comando `ls -l`. Sono gli ultimi 9 caratteri del blocco di 10. Più precisamente 3 volte 3 caratteri. -```bash +``` [root]# ls -l /tmp/myfile -rwxrw-r-x 1 root sys ... /tmp/myfile 1 2 3 4 5 @@ -822,7 +815,7 @@ La visualizzazione dei permessi viene eseguita con il comando `ls -l`. Sono gli | 5 | Proprietario del gruppo del file | !!! Note "Nota" - Le autorizzazioni si applicano a **u**ser, **g**roup e **o**ther (**ugo**) a seconda del proprietario e del gruppo. +Le autorizzazioni si applicano a **u**ser, **g**roup e **o**ther (**ugo**) a seconda del proprietario e del gruppo. Per impostazione predefinita, il _proprietario_ di un file è quello che lo crea. IL _gruppo_ del file è il gruppo del proprietario che ha creato il file. Gli _others_ sono quelli che non sono interessati dai casi precedenti. @@ -834,7 +827,7 @@ Solo l'amministratore e il proprietario di un file possono modificare i permessi Il comando `chmod` consente di modificare le autorizzazioni di accesso a un file. -```bash +``` chmod [option] mode file ``` @@ -844,20 +837,20 @@ Diverse operazioni simboliche possono essere separate da virgole Esempio: -```bash +``` [root]# chmod -R u+rwx,g+wx,o-r /tmp/file1 [root]# chmod g=x,o-r /tmp/file2 [root]# chmod -R o=r /tmp/file3 ``` -```bash +``` [root]# ls -l /tmp/fic* -rwxrwx--- 1 root root … /tmp/file1 -rwx--x--- 1 root root … /tmp/file2 -rwx--xr-- 1 root root … /tmp/file3 ``` -```bash +``` [root]# chmod 741 /tmp/file1 [root]# chmod -R 744 /tmp/file2 [root]# ls -l /tmp/fic* @@ -875,7 +868,7 @@ Ci sono due metodi per la realizzazione dei cambiamenti dei permessi: * Il metodo **simbolico**. !!! Warning "Avvertimento" - I permessi dei file e delle directory non sono dissociati. Per alcune operazioni, Sarà necessario conoscere i permessi della directory contenente il file. Un file protetto da scrittura può essere cancellato da un altro utente purché i permessi della directory che lo contengono consentono a questo utente di eseguire questa operazione. +I permessi dei file e delle directory non sono dissociati. Per alcune operazioni, Sarà necessario conoscere i permessi della directory contenente il file. Un file protetto da scrittura può essere cancellato da un altro utente purché i permessi della directory che lo contengono consentono a questo utente di eseguire questa operazione. #### Principio del metodo ottale @@ -883,14 +876,14 @@ Ogni permesso ha un valore. ![Octal method](images/07-file-systems-011.png) -```bash +``` [root]# ls -l /tmp/myfile -rwxrwxrwx 1 root root ... /tmp/myfile ``` ![Rights 777](images/07-file-systems-012.png) -```bash +``` [root]# chmod 741 /tmp/myfile -rwxr----x 1 root root ... /tmp/myfile ``` @@ -903,22 +896,22 @@ Questo metodo può essere considerato come un'associazione "letterale" tra un ti ![Symbolic method](images/07-file-systems-014.png) -```bash +``` [root]# chmod u+rwx,g+wx,o-r /tmp/myfile [root]# chmod g=x,o-r /tmp/myfile [root]# chmod o=r /tmp/myfile ``` -```bash +``` [root]# ls -l /tmp/myfile r--r-- 1 root root … /tmp/myfile ``` -```bash +``` [root]# chmod u+rwx,g+wx,o-r /tmp/myfile ``` -```bash +``` [root]# ls -l /tmp/myfile -rwxrwx--- 1 root root … /tmp/myfile ``` @@ -936,7 +929,7 @@ Come con i permessi fondamentali, i permessi particolari hanno ciascuno un valor ![Special rights](images/07-file-systems-015.png) !!! Danger "Pericolo" - `S`, `S` e `T` in maiuscolo **se il diritto non esiste**. +`S`, `S` e `T` in maiuscolo **se il diritto non esiste**. #### Il sticky-bit @@ -947,20 +940,17 @@ IL _sticky-bit_ impostato sulla directory consentirà agli utenti di eliminare s L'impostazione del _sticky-bit_ può essere fatto come segue: Metodo ottale: - -```bash +``` [root]# chmod 1777 directory ``` Metodo simbolico: - -```bash +``` [root]# chmod o+t directory ``` Verifica: - -```bash +``` [root]# ls -l drwxrwxrwt … directory ``` @@ -972,9 +962,10 @@ Questi permessi consentono l'esecuzione di un comando in base ai permessi impost Il comando viene eseguito con l'identità del proprietario (_SUID_) o del gruppo (_SGID_) del comando. !!! Note "Nota" - L'identità dell'utente che richiede l'esecuzione dell'ordine non è più presa in considerazione. +L'identità dell'utente che richiede l'esecuzione dell'ordine non è più presa in considerazione. + + Questa è una possibilità aggiuntiva dei permessi di accesso assegnata a un utente quando è necessario per loro avere gli stessi permessi del proprietario di un file o di quelli del gruppo in questione. -Questa è una possibilità aggiuntiva dei permessi di accesso assegnata a un utente quando è necessario per loro avere gli stessi permessi del proprietario di un file o di quelli del gruppo in questione. Infatti, un utente potrebbe deve eseguire un programma (di solito un'utilità di sistema) ma non ha i permessi di accesso necessari. Impostando i permessi appropriati (**s** a livello proprietario e/o a livello di gruppo), l'utente del programma ha, per il tempo della sua esecuzione, l'identità del proprietario (o quella del gruppo) del programma. Esempio: @@ -990,47 +981,42 @@ Avere un _suid_ su questo comando, `/usr/bin/passwd`, sarà eseguito con il _UID L'impostazione di _SUID_ e _SGID_ può essere fatto come sotto con il comando `chmod`: Metodo ottale: - -```bash +``` [root]# chmod 4777 command1 [root]# chmod 2777 command2 ``` Metodo simbolico: - -```bash +``` [root]# chmod u+s command1 [root]# chmod g+s command2 ``` Verifica: - -```bash +``` [root]# ls -l -rwsrwxrwx … command1 -rwxrwsrwx … command2 ``` !!! Warning "Avvertimento" - Non è possibile passare il _SUID_ o _SGID_ a una shell script. -Il sistema non lo consente perché è troppo pericoloso per la sicurezza! +Non è possibile passare il _SUID_ o _SGID_ a una shell script. Il sistema non lo consente perché è troppo pericoloso per la sicurezza! #### SGID su un file In una directory con il permesso _SGID_, qualsiasi file creato erediterà il gruppo che possiede la directory anziché quella dell'utente di creazione. Esempio: - -```bash +``` [rockstar] $ ls -ld /data/ drwxrwsr-x 2 root users 4096 26 oct. 19:43 /data ``` -```bash +``` [rockstar] $ touch /data/test_sgid /tmp/fic_reference ``` -```bash +``` [rockstar] $ ls -ld /data/test_sgid /tmp/fic_reference -rw-r--r--. 1 rockstar users 0 26 oct. 19:43 /data/test_sgid <1> -rw-r--r--. 1 rockstar rockstar 0 26 oct. 19:43 /tmp/fic_ref @@ -1049,7 +1035,7 @@ Questo comportamento è definito dalla **maschera predefinita**. Il principio è rimuovere il valore definito dalla maschera ai massimi permessi senza i permessi di esecuzione. -Per una directory. : +Per una directory : ![How the SUID works](images/07-file-systems-017.png) @@ -1061,13 +1047,12 @@ Per un file, i diritti di esecuzione vengono rimossi: Il comando `umask` ti consente di visualizzare e modificare la maschera. -```bash +``` umask [option] [mode] ``` -Example: - -```bash +Esempio: +``` $ umask 033 $ umask 0033 @@ -1088,14 +1073,11 @@ $ ls -la umask_025 | ------- | ------------------------------------------------ | | `-S` | Visualizzazione simbolica dei permessi dei file. | -!!! Warning "Avvertimento" - `umask` non influisce sui file esistenti. +!!! Warning "Avvertimento" `umask` non influisce sui file esistenti. -!!! Note "Nota" - `umask` modifica la maschera fino alla disconnessione. +!!! Note "Nota" `umask` modifica la maschera fino alla disconnessione. -Per mantenere il valore, devi modificare i seguenti file del profilo: -Per tutti gli utenti: +Per mantenere il valore, devi modificare i seguenti file del profilo: Per tutti gli utenti: * `/etc/profile` * `/etc/bashrc` @@ -1104,8 +1086,8 @@ Per un determinato utente: * `~/.bashrc` -!!! Warning "Avvertimento" - `umask -S` visualizza i permessi dei file (senza i permessi di esecuzione) dei file che verranno creati. Quindi non è il display della maschera utilizzata per sottrarre il valore massimo. +!!! Warning "Avvertimento" +`umask -S` visualizza i permessi dei file (senza i permessi di esecuzione) dei file che verranno creati. Quindi non è il display della maschera utilizzata per sottrarre il valore massimo. -!!! Tip "Suggerimento" - Il comando `umask` è un comando _bash_, (un `type umask` ritorna `umask is a shell primitive`) devi cercare `umask` in `man bash`. +!!! Tip "Suggerimento" +Il comando `umask` è un comando _bash_, (un `type umask` ritorna `umask is a shell primitive`) devi cercare `umask` in `man bash`. From 5883163d9791706f0271704cea50daee90d20327 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:56 -0500 Subject: [PATCH 21/37] New translations 00-toc.md (Italian) --- docs/books/admin_guide/00-toc.it.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/books/admin_guide/00-toc.it.md b/docs/books/admin_guide/00-toc.it.md index a9f3491cc4..3f32697761 100644 --- a/docs/books/admin_guide/00-toc.it.md +++ b/docs/books/admin_guide/00-toc.it.md @@ -18,10 +18,10 @@ Possiamo quindi entrare nel profondo del funzionamento di Linux per scoprire com * file systems. * processi. -Successivamente, tratteremo un argomento essenziale per l'amministratore di sistema: il processo di backup. -Molte soluzioni software vengono fornite con Linux per migliorare i backup (rsnapshot, lsyncd, ecc.) È bene conoscere i componenti essenziali del backup che si trovano all'interno del sistema operativo. In questo capitolo esamineremo due strumenti: `tar` e il meno diffuso `cpio`. +Successivamente, tratteremo un argomento essenziale per l'amministratore di sistema: il processo di backup. Molte soluzioni software vengono fornite con Linux per migliorare i backup (rsnapshot, lsyncd, ecc.) È bene conoscere i componenti essenziali del backup che si trovano all'interno del sistema operativo. In questo capitolo esamineremo due strumenti: `tar` e il meno diffuso `cpio`. Per quanto riguarda la gestione del sistema durante il processo di avvio, si è evoluta enormemente negli ultimi anni dall'arrivo di systemd. Concluderemo esaminando la gestione delle attività, l'implementazione della rete e l'installazione del software. + From 51674f269a9ae5cd33eb5a191f25c9f8a85df5cb Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:58 -0500 Subject: [PATCH 22/37] New translations 00-toc.md (Chinese Simplified) --- docs/books/admin_guide/00-toc.zh.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 docs/books/admin_guide/00-toc.zh.md diff --git a/docs/books/admin_guide/00-toc.zh.md b/docs/books/admin_guide/00-toc.zh.md new file mode 100644 index 0000000000..ffec45f059 --- /dev/null +++ b/docs/books/admin_guide/00-toc.zh.md @@ -0,0 +1,27 @@ +--- +title: 使用 Rocky 学习 Linux +--- + +# 使用 Rocky 学习 Linux + +《管理指南》是侧重于系统管理员的教育类文档合集。 它们可以被想要快速入门的未来系统管理员使用,也可以被想要复习的现有系统管理员使用,或者被任何想要学习更多关于Linux环境、命令、进程等等的Linux用户使用。 与所有此类型的文档一样,它将随着时间的推移不断发展与更新。 + +首先,我们将探讨Linux、发行版以及围绕我们操作系统的整个生态系统。 + +然后,我们将了解掌握Linux所必需的用户命令。 经验更丰富的用户还应查阅专门介绍更"高级"的"命令"章节 + +接下来是关于 VI 编辑器的章节。. 虽然Linux附带了许多编辑器,但VI是最强大的编辑器之一。 其他命令有时使用与VI相同的语法(想起了`sed`)。 因此,了解一些关于VI的知识,或者至少了解其基本功能(如何打开文件、保存、退出或不保存而退出),是非常重要的。 用户在使用编辑器的过程中,会对VI的其他功能更加熟悉。 另一种选择是使用默认安装在Rocky Linux中的nano, 虽然功能不多,但它使用简单、直观,并且能完成工作。 + +接着,我们可以深入了解Linux的深层功能,以了解系统是如何管理的: + +* 用户 +* 文件系统 +* 进程 + +接下来,我们将介绍对系统管理员来说一个极其重要的课程: 备份进程。 Linux附带了许多软件解决方案来加强备份(rsnapshot、lsyncd等),了解操作系统中这些备份的重要组件是有好处的。 在本章中,我们将研究两个工具: `tar` 和不太常用的 `cpio` + +自从systemd出现后,系统在引导过程中的管理在最近几年已经有了很大的发展。 + + +最后,我们将研究任务的管理、网络的实现和软件的安装。 + From 3798b3d7c8e5e6d9f2c562736eef27f7dc4c3924 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:29:59 -0500 Subject: [PATCH 23/37] New translations 01-presentation.md (Italian) --- docs/books/admin_guide/01-presentation.it.md | 31 ++++++++++++-------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/docs/books/admin_guide/01-presentation.it.md b/docs/books/admin_guide/01-presentation.it.md index 273a8296d5..f2a0e7999a 100644 --- a/docs/books/admin_guide/01-presentation.it.md +++ b/docs/books/admin_guide/01-presentation.it.md @@ -1,11 +1,12 @@ --- title: Introduzione a Linux --- + # Introduzione al sistema operativo Linux In questo capitolo impareremo a conoscere le distribuzioni GNU/Linux. ---- +**** **Obiettivi** : In questo capitolo imparerai a: @@ -13,33 +14,31 @@ In questo capitolo impareremo a conoscere le distribuzioni GNU/Linux. :heavy_check_mark: Raccontare la storia di UNIX e GNU/Linux :heavy_check_mark: Scegliere la distribuzione Linux giusta per le tue esigenze :heavy_check_mark: Spiegare la filosofia del software libero e opensource -:heavy_check_mark: Scoprire l'utilità della SHELL. +:heavy_check_mark: Scoprire l'utilità della SHELL. :checkered_flag: **generalità**, **linux**, **distribuzioni** **Conoscenza**: :star: -**Complessità**: :star: +**Complessità**: :star: **Tempo di lettura**: 10 minuti ---- +**** ## Che cos'è un sistema operativo? Linux, UNIX, BSD, Windows e MacOS sono tutti **sistemi operativi**. !!! abstract "astratto" - Un sistema operativo è un **insieme di programmi che gestisce le risorse disponibili di un computer**. +Un sistema operativo è un **insieme di programmi che gestisce le risorse disponibili di un computer**. Nella gestione di queste risorse, il sistema operativo deve: * Gestire la memoria fisica o virtuale. * La **memoria fisica** è costituita dalla RAM e dalla memoria cache del processore, che viene utilizzata per l'esecuzione dei programmi. * La **memoria virtuale** è una locazione sull'hard disk (la partizione di swap) che permette lo scarico della memoria fisica e il salvataggio dello stato attuale del sistema durante lo spegnimento elettrico del computer. -* Intercettare **l'accesso alle periferiche**. - Raramente al software è consentito accedere direttamente all'hardware (ad eccezione delle schede grafiche per esigenze molto specifiche). -* Fornire alle applicazioni una corretta **gestione delle attività**. - Il sistema operativo è responsabile della pianificazione dei processi che occupano il processore. +* Intercettare **l'accesso alle periferiche**. Raramente al software è consentito accedere direttamente all'hardware (ad eccezione delle schede grafiche per esigenze molto specifiche). +* Fornire alle applicazioni una corretta **gestione delle attività**. Il sistema operativo è responsabile della pianificazione dei processi che occupano il processore. * **Protezione dei file** da accessi non autorizzati. * **Raccolta di informazioni** sui programmi in uso o in esecuzione. @@ -52,6 +51,7 @@ Nella gestione di queste risorse, il sistema operativo deve: #### UNIX * Dal **1964** al **1968**: MULTICS (MULTiplexed Information and Computing Service) è sviluppato per MIT, Bell Labs (AT&T) e General Electric. + * **1969**: Dopo il ritiro della Bell (1969) e poi della General Electric dal progetto, due sviluppatori (Ken Thompson e Dennis Ritchie), affiancati in seguito da Brian Kernighan, giudicando MULTICS troppo complesso, lanciano lo sviluppo di UNIX (UNiplexed Information and Computing Service). Originariamente sviluppato in assembler, i progettisti di UNIX hanno sviluppato il linguaggio B e poi il linguaggio C (1971) e hanno completamente riscritto UNIX. Essendo stato sviluppato nel 1970, la data di riferimento dei sistemi UNIX/Linux è ancora fissata al 1° gennaio 1970. Il linguaggio C è ancora oggi uno dei linguaggi di programmazione più popolari! Linguaggio di basso livello, vicino all'hardware, consente l'adattamento del sistema operativo a qualsiasi architettura di macchina dotata di compilatore C. @@ -67,12 +67,19 @@ UNIX è ancora rilevante oggi (HP-UX, AIX, Solaris, etc.) #### Linux * **1991**: Uno studente finlandese, **Linus Torvalds** , crea un sistema operativo dedicato al suo personal computer e lo chiama Linux. Pubblica la sua prima versione 0.02, sul forum di discussione Usenet e altri sviluppatori iniziano a contribuire al miglioramento del suo sistema. Il termine Linux è un gioco di parole tra il nome del fondatore, Linus, e UNIX. + * **1993**: Viene creata la distribuzione Debian. Debian è una distribuzione non commerciale, basata sulla comunità. Sviluppato originariamente per essere utilizzato su server, è particolarmente adatto a questo ruolo, ma è pensato per essere un sistema universale e quindi utilizzabile anche su un personal computer. Debian è usata come base per molte altre distribuzioni, come Mint o Ubuntu. + * **1994**: La distribuzione commerciale RedHat viene creata dalla società RedHat, che è oggi il principale distributore del sistema operativo GNU/Linux. RedHat supporta la versione community Fedora e recentemente la distribuzione gratuita CentOS. + * **1997**: Viene creato l'ambiente desktop KDE. Si basa sulla libreria di componenti Qt e sul linguaggio di sviluppo C++. + * **1999**: Viene creato l'ambiente desktop Gnome. Questo si basa sulla libreria di componenti GTK+. -* **2002**: Viene creata la distribuzione Arch. La sua particolarità è quella di essere rilasciato in Rolling Release (aggiornamento continuo). + +* **2002**: Viene creata la distribuzione Arch. La sua particolarità deve essere rilasciata in Rolling Release (aggiornamento continuo). + * **2004**: Ubuntu viene creato dalla società Canonical (Mark Shuttleworth). È basato su Debian, che include software gratuito e proprietario. + * **2021**: Nascita di Rocky Linux, basato sulla distribuzione RedHat. ### Quota di mercato @@ -139,7 +146,7 @@ Linux è basato su standard riconosciuti [posix](http://fr.wikipedia.org/wiki/PO * Tutto è un file. * Portabilità. * Fai solo una cosa e falla bene. -* KISS: Mantienilo semplice stupido. (Keep It Simple Stupid) +* KISS: Mantienilo semplice stupido (Keep It Simple Stupid). * "UNIX è fondamentalmente un sistema operativo semplice, Ma devi essere un genio per capirne la semplicità." (__Dennis Ritchie__) * "Unix è facile da usare. Solamente che non è chiaro con quali utenti sia amichevole." (__Steven King__) @@ -294,4 +301,4 @@ Esistono diversi tipi di shell disponibili e configurabili su una piattaforma o - [ ] Jason-Bourne shell (jbsh) - [ ] Bourne-Again shell (bash) - [ ] C shell (csh) -- [ ] Korn shell (ksh) +- [ ] Korn shell (ksh) From cbdc38a4c9a6e4a61db559139c1a810879016627 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:00 -0500 Subject: [PATCH 24/37] New translations 01-presentation.md (Chinese Simplified) --- docs/books/admin_guide/01-presentation.zh.md | 89 +++++++++----------- 1 file changed, 41 insertions(+), 48 deletions(-) diff --git a/docs/books/admin_guide/01-presentation.zh.md b/docs/books/admin_guide/01-presentation.zh.md index 257b431be4..3f8d9de224 100644 --- a/docs/books/admin_guide/01-presentation.zh.md +++ b/docs/books/admin_guide/01-presentation.zh.md @@ -10,16 +10,11 @@ title: Linux 简介 **目标** : 本章将讲解以下内容: -:heavy_check_mark: 操作系统的特性和可能的架构; \ -:heavy_check_mark: UNIX 和 GNU/Linux 的历史; \ -:heavy_check_mark: 根据需求选择合适的 Linux 发行版; \ -:heavy_check_mark: 自由和开源软件的哲学; \ -:heavy_check_mark: 了解 SHELL 的用处。 +:heavy_check_mark: 操作系统的特性和可能的架构; \ :heavy_check_mark: UNIX 和 GNU/Linux 的历史; \ :heavy_check_mark: 根据需求选择合适的 Linux 发行版; \ :heavy_check_mark: 自由和开源软件的哲学; \ :heavy_check_mark: 了解 SHELL 的用处。 :checkered_flag: **概述**, **linux**, **发行版** -**知识掌握程度**: :star: \ -**知识复杂程度**: :star: +**知识掌握程度**: :star: \ **知识复杂程度**: :star: **阅读时间**: 10 分钟 @@ -29,18 +24,17 @@ title: Linux 简介 Linux、UNIX、BSD、Windows 和 MacOS 都是**操作系统**。 -:clipboard: 操作系统是**一组管理计算机可用资源的程序**。 +!!! abstract An operating system is a **set of programs that manages the available resources of a computer**. 在这些资源管理中,操作系统必须: * 管理物理或虚拟内存。 * **物理内存**由 RAM 条和处理器缓存组成,用于执行程序。 - * **虚拟内存**是位于硬盘上(交换分区),它允许在计算机断电期间卸载物理内存并保存系统的当前状态。 - 拦截对外围设备的访问。通常不允许软件直接访问硬件(除了用于非常特殊需求的显卡)。 -* 为应用程序提供适当的**任务管理**。 - 操作系统负责调度进程以充分使用处理器。 + * **收集**有关正在使用或正在进行的程序的**信息**。 +* Intercept **access to peripherals**. 通常不允许软件直接访问硬件(除了用于非常特殊需求的显卡)。 +* 为应用程序提供适当的**任务管理**。 操作系统负责调度进程以充分使用处理器。 * **保护文件**不受未经授权的访问。 -* **收集**有关正在使用或正在进行的程序的**信息**。 +* **内核**是第一个软件组件。 ![Operation of an operating system](images/operating_system.png) @@ -50,12 +44,11 @@ Linux、UNIX、BSD、Windows 和 MacOS 都是**操作系统**。 #### UNIX -* **1964 至 1968**: - MIT、贝尔实验室(AT&T)和通用电气公司共同研发了 MULTICS(多功能信息和计算服务)。 +* **1964 至 1968**: MIT、贝尔实验室(AT&T)和通用电气公司共同研发了 MULTICS(多功能信息和计算服务)。 -* **1969**: 在贝尔(1969)和通用电气退出该项目后,两位开发人员(肯·汤普森和丹尼斯·里奇)以及后来的布赖恩·克尼根(Brian Kernighan)认为 MULTICS 过于复杂,便启动开发 UNIX(UNiplexed Information and Computing Service)。UNIX 的设计者最初是使用汇编语言开发的,后来开发了 B 语言和 C 语言(1971年),并完全重写了 UNIX。UNIX/Linux 系统自 1970 年开发以来,其参考日期依旧为 1970 年 1 月 1 日。 +* **1969**: 在贝尔(1969)和通用电气退出该项目后,两位开发人员(肯·汤普森和丹尼斯·里奇)以及后来的布赖恩·克尼根(Brian Kernighan)认为 MULTICS 过于复杂,便启动开发 UNIX(UNiplexed Information and Computing Service)。 UNIX 的设计者最初是使用汇编语言开发的,后来开发了 B 语言和 C 语言(1971年),并完全重写了 UNIX。 UNIX/Linux 系统自 1970 年开发以来,其参考日期依旧为 1970 年 1 月 1 日。 -C 语言仍然是当今流行的编程语言之一!一种接近硬件的低级语言,它允许操作系统适配任何具有 C 编译器的机器架构。 +C 语言仍然是当今流行的编程语言之一! 一种接近硬件的低级语言,它允许操作系统适配任何具有 C 编译器的机器架构。 UNIX 是一种开放且不断发展的操作系统,在计算历史上发挥了重要作用。 它已成为许多其他系统的基础:Linux、BSD、Mac OSX 等。 @@ -63,23 +56,23 @@ UNIX 在今天仍然很重要(HP-UX、AIX、Solaris等)。 #### Minix -* **1987**: A.S. Tanenbaum 开发了 MINIX(一种简化的 UNIX)以一种简单的方式教授操作系统课程。Tanenbaum 先生将他的操作系统源代码开放。 +* **1987**: A.S. **1987**: A.S. Tanenbaum 开发了 MINIX(一种简化的 UNIX)以一种简单的方式教授操作系统课程。 Tanenbaum 先生将他的操作系统源代码开放。 #### Linux -* **1991**: 芬兰学生 **Linus Torvalds** 为他的个人计算机创建了一个操作系统,并将其命名为 Linux。他在 Usenet 论坛上发布了他的第一个版本 0.02,其他开发者也来帮助他改进他的系统。术语 Linux 是来自创始人的名字 Linus 和 UNIX 两者的组合。 +* **1991**: 芬兰学生 **Linus Torvalds** 为他的个人计算机创建了一个操作系统,并将其命名为 Linux。 他在 Usenet 论坛上发布了他的第一个版本 0.02,其他开发者也来帮助他改进他的系统。 术语 Linux 是来自创始人的名字 Linus 和 UNIX 两者的组合。 -* **1993**: 创建 Debian 发行版。Debian 是一个基于社区的非商业发行版。它最初是为在服务器上使用而开发的,特别适合于服务器,但它是一个通用系统,因此也可以在个人计算机上使用。Debian 是许多其他发行版的基础,例如 Mint 或 Ubuntu。 +* **1993**: 创建 Debian 发行版。 Debian 是一个基于社区的非商业发行版。 它最初是为在服务器上使用而开发的,特别适合于服务器,但它是一个通用系统,因此也可以在个人计算机上使用。 Debian 是许多其他发行版的基础,例如 Mint 或 Ubuntu。 -* **1994**: 商业发行版 RedHat 由 RedHat 公司创建,该公司目前是 GNU/Linux 操作系统的领先发行商。RedHat 支持社区版 Fedora 和自由发行版 CentOS。 +* **1994**: 商业发行版 RedHat 由 RedHat 公司创建,该公司目前是 GNU/Linux 操作系统的领先发行商。 RedHat 支持社区版 Fedora 和自由发行版 CentOS。 -* **1997**: 创建 KDE 桌面环境。它基于 QT 组件库和 C++ 开发语言。 +* **1997**: 创建 KDE 桌面环境。 它基于 QT 组件库和 C++ 开发语言。 -* **1999**: 创建 Gnome 桌面环境。它基于 GTK+ 组件库。 +* **1999**: 创建 Gnome 桌面环境。 它基于 GTK+ 组件库。 -* **2002**: 创建 Arch 发行版。其特殊性在于滚动发行(持续更新)。 +* **2002**: 创建 Arch 发行版。 其特殊性在于滚动发行(持续更新)。 -* **2004**: Canonical 公司(Mark Shuttleworth)创建 Ubuntu。它基于 Debian,但包括自由和专有软件。 +* **2004**: Canonical 公司(Mark Shuttleworth)创建 Ubuntu。 它基于 Debian,但包括自由和专有软件。 * **2021**: Rocky Linux 诞生,基于 RedHat 发行版。 @@ -89,21 +82,21 @@ UNIX 在今天仍然很重要(HP-UX、AIX、Solaris等)。 TODO: graphics with market share for servers and pc. --> -人们经常使用 Linux,但它仍然不为公众所熟知。事实上,在**智能手机**、**电视**、**网盒**等中均有 Linux 的身影。世界上几乎 70% 的网页都由 Linux 或 UNIX 服务器提供服务! +人们经常使用 Linux,但它仍然不为公众所熟知。 事实上,在**智能手机**、**电视**、**网盒**等中均有 Linux 的身影。 世界上几乎 70% 的网页都由 Linux 或 UNIX 服务器提供服务! -略多于 **3% 的个人电脑**配置了 Linux,超过 **82% 的智能手机**配置了 Linux。Android 是以 Linux 为内核的操作系统。 +略多于 **3% 的个人电脑**配置了 Linux,超过 **82% 的智能手机**配置了 Linux。 Android 是以 Linux 为内核的操作系统。 -自 2018 年以来,500 台超级计算机全部配备了 Linux。超级计算机是一种在设计时利用已知的技术实现尽可能高性能的计算机,尤其是在计算速度方面。 +自 2018 年以来,500 台超级计算机全部配备了 Linux。 超级计算机是一种在设计时利用已知的技术实现尽可能高性能的计算机,尤其是在计算速度方面。 ### 架构设计 -* **内核**是第一个软件组件。 +* **shell** 是一个实用程序,用于解释用户命令并确保其执行。 * 它是 Linux 系统的核心。 * 它管理系统的硬件资源。 * 其他软件组件必须通过它才能访问硬件。 -* **shell** 是一个实用程序,用于解释用户命令并确保其执行。 +* The **shell** is a utility that interprets user commands and ensures their execution. * 主要 shell:Bourne shell、C shell、Korn shell 和 Bourne-Again shell (bash)。 * 应用程序是用户程序,例如: * 网页浏览器; @@ -112,7 +105,7 @@ TODO: graphics with market share for servers and pc. #### 多任务 -Linux 属于分时操作系统家族。它在多个程序之间共享处理时间,以对用户透明的方式从一个程序切换到另一个程序。这意味着: +Linux 属于分时操作系统家族。 它在多个程序之间共享处理时间,以对用户透明的方式从一个程序切换到另一个程序。 这意味着: * 同时执行多个程序; * 调度程序分配 CPU 时间; @@ -121,7 +114,7 @@ Linux 属于分时操作系统家族。它在多个程序之间共享处理时 #### 多用户 -Multics 的目的是允许多个用户在一台计算机上(当时非常昂贵)通过多个终端(屏幕和键盘)工作。Linux 受这种操作系统的启发,保持了与多个用户同时独立工作的能力,每个用户都有自己的用户帐户、内存空间以及对文件和软件的访问权限。 +Multics 的目的是允许多个用户在一台计算机上(当时非常昂贵)通过多个终端(屏幕和键盘)工作。 Linux 受这种操作系统的启发,保持了与多个用户同时独立工作的能力,每个用户都有自己的用户帐户、内存空间以及对文件和软件的访问权限。 #### 多处理器 @@ -129,7 +122,7 @@ Linux 能够与多处理器计算机或多核处理器一起工作。 #### 多平台 -Linux 是用高级语言编写的,在编译过程中可以适应不同类型的平台。因此,它运行于: +Linux 是用高级语言编写的,在编译过程中可以适应不同类型的平台。 因此,它运行于: * 家用电脑(个人电脑或笔记本电脑); * 服务器(数据、应用程序等); @@ -148,26 +141,26 @@ Linux 基于 [posix](http://fr.wikipedia.org/wiki/POSIX)、TCP/IP、NFS、Samba * 可移植性。 * 让每一个程序只做好一件事情。 * KISS 原则: 保持简单化和傻瓜化。 -* "UNIX 基本上是一个简单的操作系统,但你必须是一个天才才能理解它的简单性。" (__Dennis Ritchie__) -* "Unix 肯定是用户友好的,只不过它在对哪个用户友好的问题上,用情比较专一而已。" (__Steven King__) +* "UNIX 基本上是一个简单的操作系统,但你必须是一个天才才能理解它的简单性。" (__Dennis Ritchie__) (__Dennis Ritchie__) +* "Unix is user-friendly. It just isn't promiscuous about which users it's friendly with." "Unix 肯定是用户友好的,只不过它在对哪个用户友好的问题上,用情比较专一而已。" (__Steven King__) ## GNU/LINUX 发行版 -Linux 发行版是围绕 Linux 内核组装的一组稳定的软件,可以与管理(安装、删除、配置)此软件的必要组件一起安装。有联合或社区发行版(Debian、Rocky)或商业发行版(RedHat、Ubuntu)。 +Linux 发行版是围绕 Linux 内核组装的一组稳定的软件,可以与管理(安装、删除、配置)此软件的必要组件一起安装。 有联合或社区发行版(Debian、Rocky)或商业发行版(RedHat、Ubuntu)。 -每个发行版提供一个或多个桌面环境,提供一组预装软件和一个额外软件库。配置选项(例如内核或服务选项)特定于每个选项。 +每个发行版提供一个或多个桌面环境,提供一组预装软件和一个额外软件库。 配置选项(例如内核或服务选项)特定于每个选项。 这一原则允许您拥有面向初学者的发行版(Ubuntu、Linux Mint等),拥有更复杂的发行版(Gentoo、Arch),拥有更专注于服务器的发行版(Debian、Redhat),或者拥有专注于工作站的发行版。 ### 桌面环境 -有许多图形环境:**Gnom**e、**KDE**、**LXDE**、**XFCE** 等。有些环境是人人通用的,与微软或苹果系统相比,它们的人机形态并不可耻! +有许多图形环境:**Gnom**e、**KDE**、**LXDE**、**XFCE** 等。 有些环境是人人通用的,与微软或苹果系统相比,它们的人机形态并不可耻! -那么,为什么在 Linux 系统没有(或者几乎没有)病毒的情况下,人们对 Linux 的热情如此之低呢?也许是因为所有编辑器 (Adobe) 或制造商 (NVidia) 都不玩免费游戏,也不提供适用于 GNU/Linux 的软件版本或驱动程序?害怕改变?很难找到售卖 Linux 电脑的商家?Linux 下发行的游戏太少(但时间不长)?随着运行在 Linux 上的 Steam-box 游戏机的到来,情况会改变吗? +那么,为什么在 Linux 系统没有(或者几乎没有)病毒的情况下,人们对 Linux 的热情如此之低呢? 也许是因为所有编辑器 (Adobe) 或制造商 (NVidia) 都不玩免费游戏,也不提供适用于 GNU/Linux 的软件版本或驱动程序? 害怕改变? 很难找到售卖 Linux 电脑的商家? Linux 下发行的游戏太少(但时间不长)? 随着运行在 Linux 上的 Steam-box 游戏机的到来,情况会改变吗? ![Gnome Desktop](images/01-presentation-gnome.png) -**Gnome 3** 桌面环境不再使用桌面的概念,而是使用 Gnome Shell 的概念(不要与命令行 shell 混淆)。它充当桌面、仪表板、通知区域和窗口选择器。Gnome 桌面环境基于 GTK+ 组件库。 +**Gnome 3** 桌面环境不再使用桌面的概念,而是使用 Gnome Shell 的概念(不要与命令行 shell 混淆)。 它充当桌面、仪表板、通知区域和窗口选择器。 Gnome 桌面环境基于 GTK+ 组件库。 ![KDE Desktop](images/01-presentation-kde.png) @@ -179,7 +172,7 @@ Linux 发行版是围绕 Linux 内核组装的一组稳定的软件,可以与 ### 自由 / 开源 -Microsoft 或 Mac 操作系统的用户必须购买许可证才能使用其操作系统。这个许可证是有成本的,它的价格包含在计算机的价格中。 +Microsoft 或 Mac 操作系统的用户必须购买许可证才能使用其操作系统。 这个许可证是有成本的,它的价格包含在计算机的价格中。 在 **GNU/Linux** 世界中,自由软件运动主要提供自由发行版。 @@ -191,7 +184,7 @@ Microsoft 或 Mac 操作系统的用户必须购买许可证才能使用其操 #### GPL 许可证(通用公共许可证) -**GPL 许可证**向软件作者保证其知识产权,但允许第三方修改、重新分发或转售软件,前提是源代码与软件一起提供。GPL 是来自 **GNU**(GNU is Not UNIX)项目的许可证,该项目在创建 Linux 时起到了重要作用。 +**GPL 许可证**向软件作者保证其知识产权,但允许第三方修改、重新分发或转售软件,前提是源代码与软件一起提供。 GPL 是来自 **GNU**(GNU is Not UNIX)项目的许可证,该项目在创建 Linux 时起到了重要作用。 这暗示着: @@ -200,7 +193,7 @@ Microsoft 或 Mac 操作系统的用户必须购买许可证才能使用其操 * 重新分发复制品的自由; * 为了整个社区的利益,有改进计划和发表改进意见的自由。 -另一方面,即使是在 GPL 许可下的产品也可以付费。并不是为产品本身付费,而是保证开发人员团队将继续致力于使其发展并解决错误,甚至为用户提供支持。 +另一方面,即使是在 GPL 许可下的产品也可以付费。 并不是为产品本身付费,而是保证开发人员团队将继续致力于使其发展并解决错误,甚至为用户提供支持。 ## 使用领域 @@ -211,22 +204,22 @@ Linux 发行版在以下方面表现出色 : * **中央计算机**: 银行、保险、工业等。 * **嵌入式系统**: 路由器、网盒、智能电视等。 -Linux 是托管数据库或网站,或者作为邮件服务器、DNS 或防火墙的合适选择。简而言之,Linux 几乎可以做任何事情,这就解释了特定发行版的份额。 +Linux 是托管数据库或网站,或者作为邮件服务器、DNS 或防火墙的合适选择。 简而言之,Linux 几乎可以做任何事情,这就解释了特定发行版的份额。 ## Shell ### 概论 -**shell** 称为命令接口,允许用户向操作系统发送命令。由于图形界面的实现,它在如今不太明显,但在 Linux 系统上仍然是一种特权手段,Linux 系统并非都具有图形界面,并且其服务并不总是存在设置界面。 +**shell** 称为命令接口,允许用户向操作系统发送命令。 由于图形界面的实现,它在如今不太明显,但在 Linux 系统上仍然是一种特权手段,Linux 系统并非都具有图形界面,并且其服务并不总是存在设置界面。 -它提供了一种真正的编程语言,包括经典的结构:循环、选择,以及共同的组成部分:变量、参数传递和子程序。它允许创建脚本以自动执行某些操作(备份、创建用户、系统监控等)。 +它提供了一种真正的编程语言,包括经典的结构:循环、选择,以及共同的组成部分:变量、参数传递和子程序。 它允许创建脚本以自动执行某些操作(备份、创建用户、系统监控等)。 根据用户的喜好,平台上有几种类型的 shell 可供使用和配置: * sh, POSIX 标准 shell; * csh, C 中面向命令的 shell; * bash, Bourne-Again Shell, Linux shell。 -* ... +* etc, ... ## 功能 @@ -302,4 +295,4 @@ Linux 是托管数据库或网站,或者作为邮件服务器、DNS 或防火 - [ ] Jason-Bourne shell (jbsh) - [ ] Bourne-Again shell (bash) - [ ] C shell (csh) -- [ ] Korn shell (ksh) \ No newline at end of file +- [ ] Korn shell (ksh) From 298af2aa4c00724e92939acc07644e31e8910990 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:01 -0500 Subject: [PATCH 25/37] New translations 03-commands.md (French) --- docs/books/admin_guide/03-commands.fr.md | 1563 ++++++++++++++++++++++ 1 file changed, 1563 insertions(+) create mode 100644 docs/books/admin_guide/03-commands.fr.md diff --git a/docs/books/admin_guide/03-commands.fr.md b/docs/books/admin_guide/03-commands.fr.md new file mode 100644 index 0000000000..0d8031e56f --- /dev/null +++ b/docs/books/admin_guide/03-commands.fr.md @@ -0,0 +1,1563 @@ +--- +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` From db0c3bbc21e82eb251d640e9544256bbdcb44f72 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:02 -0500 Subject: [PATCH 26/37] New translations 03-commands.md (Italian) --- docs/books/admin_guide/03-commands.it.md | 349 +++++++++++------------ 1 file changed, 173 insertions(+), 176 deletions(-) diff --git a/docs/books/admin_guide/03-commands.it.md b/docs/books/admin_guide/03-commands.it.md index 00ed90b18c..035762b8f1 100644 --- a/docs/books/admin_guide/03-commands.it.md +++ b/docs/books/admin_guide/03-commands.it.md @@ -9,22 +9,22 @@ update: 11-10-2021 In questo capitolo imparerai come lavorare con Linux e con i comandi. ---- +**** **Obiettivi** : In questo capitolo, futuri amministratori Linux impareranno come fare per: :heavy_check_mark: **spostarsi** nell'albero di sistema; :heavy_check_mark: **creare** un file di testo, **visualizzare** il suo contenuto e **modificarlo**; -:heavy_check_mark: utilizzare i comandi Linux più utili. +:heavy_check_mark: utilizzare i comandi Linux più utili. :checkered_flag: **comandi utente**, **linux** **Conoscenza**: :star: -**Complessità**: :star: +**Complessità**: :star: **Tempo di lettura**: 40 minuti ---- +**** ## Generalità @@ -85,8 +85,7 @@ Il nome del comando è **spesso in minuscolo**. Uno spazio separa ogni oggetto. -Le **opzioni** abbreviate iniziano con un trattino (`-l`), mentre le **opzioni lunghe** iniziano con due trattini (`--list`). -Un doppio trattino (`--`) indica la fine dell'elenco delle opzioni. +Le **opzioni** abbreviate iniziano con un trattino (`-l`), mentre le **opzioni lunghe** iniziano con due trattini (`--list`). Un doppio trattino (`--`) indica la fine dell'elenco delle opzioni. È possibile raggruppare alcune opzioni brevi insieme: @@ -118,10 +117,10 @@ In letteratura, il termine "opzione" è equivalente al termine "parametro," che Il comando `apropos` ti consente di cercare per parola chiave all'interno di queste pagine manuali: -| Opzioni | Osservazioni | -| -------------------------------------------- | -------------------------------------------------- | -| `-s`, `--sections list` o `--section list` | Limitato alle sezioni manuali. | -| `-a` o `--and` | Visualizza solo la voce corrispondente a tutte le parole chiave fornite. | +| Opzioni | Osservazioni | +| ------------------------------------------ | ------------------------------------------------------------------------ | +| `-s`, `--sections list` o `--section list` | Limitato alle sezioni manuali. | +| `-a` o `--and` | Visualizza solo la voce corrispondente a tutte le parole chiave fornite. | Esempio: @@ -168,8 +167,7 @@ clear (1) - clear the terminal screen #### comando `man` -Una volta trovato con `apropos` o `whatis`, il manuale è letto da `man` ("Man è tuo amico"). -Questo set di manuali è diviso in 8 sezioni, raggruppando le informazioni per argomento, la sezione predefinita è la 1: +Una volta trovato con `apropos` o `whatis`, il manuale è letto da `man` ("Man è tuo amico"). Questo set di manuali è diviso in 8 sezioni, raggruppando le informazioni per argomento, la sezione predefinita è la 1: 1. Comandi utente; 2. Chiamate di sistema; @@ -178,8 +176,7 @@ Questo set di manuali è diviso in 8 sezioni, raggruppando le informazioni per a 5. Formati di file ; 6. Giochi; 7. Varie; -8. Strumenti e demoni dell'amministrazione del sistema. - È possibile accedere alle informazioni su ciascuna sezione digitando `man x intro`, dove `x` è il numero della sezione. +8. Strumenti e demoni dell'amministrazione del sistema. È possibile accedere alle informazioni su ciascuna sezione digitando `man x intro`, dove `x` è il numero della sezione. Il comando: @@ -220,15 +217,14 @@ Esempi: Opzioni : -| Opzioni | Osservazioni | -| --------- | ---------------------------------- | -| `-h` | Spegne il sistema elettricamente | -| `-r` | Riavvia il sistema | +| Opzioni | Osservazioni | +| ------- | -------------------------------- | +| `-h` | Spegne il sistema elettricamente | +| `-r` | Riavvia il sistema | ### comando `history` -Il comando `history` visualizza la cronologia dei comandi che sono stati inseriti dall'utente. -I comandi sono memorizzati nel file `.bash_history` nella directory di accesso dell'utente. +Il comando `history` visualizza la cronologia dei comandi che sono stati inseriti dall'utente. I comandi sono memorizzati nel file `.bash_history` nella directory di accesso dell'utente. Esempio di un comando history @@ -238,22 +234,22 @@ $ history 148 man history ``` -| Opzioni | Commenti | -| ------- | ----------------------------------------------------------------------------------- | -| `-w` | L'opzione`-w` copierà la cronologia della sessione corrente nel file. | +| Opzioni | Commenti | +| ------- | ------------------------------------------------------------------------------------------------------------- | +| `-w` | L'opzione`-w` copierà la cronologia della sessione corrente nel file. | | `-c` | L'opzione`-c` eliminerà la cronologia della sessione corrente (ma non il contenuto del file `.bash_history`). | * Manipolazione della history: Per manipolare la history, i seguenti comandi immessi dal prompt dei comandi permetteranno di: -| Chiavi | Funzione | -| ------------------ | ------------------------------------------------------------- | -| !! | Richiama l'ultimo comando eseguito. | -| !n | Richiama il comando per il suo numero nell'elenco. | -| !string | Richiama il comando più recente che inizia con la stringa. | -| | Richiama il comando più recente che inizia con la stringa. | -| | Richiama il comando più recente che inizia con la stringa. | +| Chiavi | Funzione | +| ------------------ | ---------------------------------------------------------- | +| !! | Richiama l'ultimo comando eseguito. | +| !n | Richiama il comando per il suo numero nell'elenco. | +| !string | Richiama il comando più recente che inizia con la stringa. | +| | Richiama il comando più recente che inizia con la stringa. | +| | Richiama il comando più recente che inizia con la stringa. | ### Il completamento automatico @@ -273,8 +269,7 @@ Il comando `clear` cancella il contenuto della schermata del terminale. Infatti, In un terminale, il display sarà permanentemente nascosto, mentre nell'interfaccia grafica, una barra di scorrimento ti permetterà sempre di scorrere la cronologia del terminale virtuale. -!!! Tip "Suggerimento" - CTRL + L avrà lo stesso effetto del comando `clear` +!!! Tip "Suggerimento" CTRL + L avrà lo stesso effetto del comando `clear` ### comando `echo` @@ -288,13 +283,13 @@ Per vari motivi, allo sviluppatore dello script potrebbe essere necessario utili Tra le sequenze usate frequentemente, possiamo menzionare : -| Sequenza | Risultato | -| ---------- | ---------------------------------- | -| `\a` | Invia un bip sonoro | -| `\b` | Indietro | -| `\n` | Aggiunge una interruzione di linea | -| `\t` | Aggiunge un tab orizzontale | -| `\v` | Aggiunge tab verticale | +| Sequenza | Risultato | +| -------- | ---------------------------------- | +| `\a` | Invia un bip sonoro | +| `\b` | Indietro | +| `\n` | Aggiunge una interruzione di linea | +| `\t` | Aggiunge un tab orizzontale | +| `\v` | Aggiunge tab verticale | ### comando `date` @@ -315,29 +310,28 @@ $ date -d 20210517 +%j In questo ultimo esempio, l'opzione `d` visualizza una data fornita. L'opzione `+%J` formatta questa data per mostrare solo il giorno dell'anno. -!!! Warning "Avvertimento" - Il formato di una data può cambiare in base al valore della lingua definita nella variabile di ambiente `$LANG`. +!!! Warning "Avvertimento" Il formato di una data può cambiare in base al valore della lingua definita nella variabile di ambiente `$LANG`. Il display della data può seguire i seguenti formati: -| Opzione | Formato | -| ------- | ---------------------------------------- | -| `+%A` | Nome completo del giorno | -| `+%B` | Nome completo del mese | -| `+%c` | Visualizzazione completa della data | -| `+%d` | Numero del giorno | -| `+%F` | Data nel formato`YYYY-MM-DD` | -| `+%G` | Anno | -| `+%H` | Ora del giorno | -| `+%j` | Giorno dell'anno | -| `+%m` | Numero del mese | -| `+%M` | Minuti | -| `+%R` | Tempo nel formato`hh:mm` | -| `+%s` | Secondi dal 1° gennaio 1970 | -| `+%T` | Tempo nel formato`hh:mm:ss` | -| `+%u` | Giorno della settimana (`1` per Lunedì) | -| `+%V` | Numero della settimana (`+%V`) | -| `+%x` | Data in formato`DD/MM/YYYY` | +| Opzione | Formato | +| ------- | --------------------------------------- | +| `+%A` | Nome completo del giorno | +| `+%B` | Nome completo del mese | +| `+%c` | Visualizzazione completa della data | +| `+%d` | Numero del giorno | +| `+%F` | Data nel formato`YYYY-MM-DD` | +| `+%G` | Anno | +| `+%H` | Ora del giorno | +| `+%j` | Giorno dell'anno | +| `+%m` | Numero del mese | +| `+%M` | Minuti | +| `+%R` | Tempo nel formato`hh:mm` | +| `+%s` | Secondi dal 1° gennaio 1970 | +| `+%T` | Tempo nel formato`hh:mm:ss` | +| `+%u` | Giorno della settimana (`1` per Lunedì) | +| `+%V` | Numero della settimana (`+%V`) | +| `+%x` | Data in formato`DD/MM/YYYY` | Il comando `date` consente anche di modificare la data e l'ora del sistema. In questo caso, verrà utilizzata l'opzione `-s`. @@ -463,24 +457,24 @@ $ ls /home Le opzioni principali del comando `ls` sono : -| Opzione | Informazione | -| ------- | --------------------------------------------------------------------------------------- | -| `-a` | Visualizza tutti i file, anche quelli nascosti. I file nascosti in Linux sono quelli che iniziano con`.`. | -| `-i` | Visualizza i numeri di inode. | +| Opzione | Informazione | +| ------- | ----------------------------------------------------------------------------------------------------------------------- | +| `-a` | Visualizza tutti i file, anche quelli nascosti. I file nascosti in Linux sono quelli che iniziano con`.`. | +| `-i` | Visualizza i numeri di inode. | | `-l` | Il comando con l'opzione`-l` visualizza un elenco verticale dei file con informazioni aggiuntive formattate in colonne. | Il comando `ls`, tuttavia, ha molte opzioni (vedi `man`): -| Opzione | Informazione | -| ------- | ------------------------------------------------------------------------------------------ | -| `-d` | Visualizza le informazioni di una directory invece di elencare i suoi contenuti. | -| `-g` | Visualizza UID e GID al posto dei nomi dei proprietari. | -| `-h` | Visualizza le dimensioni dei file nel formato più appropriato (byte, kilobyte, megabyte, gigabyte, ...).`h` stà per Human Readable. | -| `-s` | Visualizza la dimensione in byte (tranne l'opzione`k`). | -| `-A` | Visualizza tutti i file nella directory tranne`.` e `..`. | -| `-R` | Visualizza il contenuto delle sottodirectory in modo ricorsivo. | +| Opzione | Informazione | +| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-d` | Visualizza le informazioni di una directory invece di elencare i suoi contenuti. | +| `-g` | Visualizza UID e GID al posto dei nomi dei proprietari. | +| `-h` | Visualizza le dimensioni dei file nel formato più appropriato (byte, kilobyte, megabyte, gigabyte, ...). `h` stà per Human Readable. | +| `-s` | Visualizza la dimensione in byte (tranne l'opzione`k`). | +| `-A` | Visualizza tutti i file nella directory tranne`.` e `..`. | +| `-R` | Visualizza il contenuto delle sottodirectory in modo ricorsivo. | | `-F` | Visualizza il tipo di file. Stampa un`/` per una directory, `*` per gli eseguibili, `@` per un collegamento simbolico, e niente per un file di testo. | -| `-X` | ordina i file in base alle loro estensioni. | +| `-X` | ordina i file in base alle loro estensioni. | * Descrizione delle colonne: @@ -489,25 +483,24 @@ $ ls -lia /home 78489 drwx------ 4 rockstar rockstar 4096 25 oct. 08:10 rockstar ``` -| Valore | Informazione | -| ----------------- | ------------------------------------------------------------------------------- | -| `78489` | Numero di inode. | -| `drwx------` | Tipo di file (`d`) e permessi (`rwx------`). | +| Valore | Informazione | +| --------------- | --------------------------------------------------------------------------------------------------------------- | +| `78489` | Numero di inode. | +| `drwx------` | Tipo di file (`d`) e permessi (`rwx------`). | | `4` | Numero di sottodirectory. (`.` e `..` incluse). Per un file di tipo link fisico: numero di collegamenti fisici. | -| `rockstar` | Per un file di collegamento fisico: numero di collegamenti fisici. | -| `rockstar` | Per un file di tipo link fisico: numero di collegamenti fisici. | -| `4096` | Per un file di tipo di collegamento fisico: numero di collegamenti fisici. | -| `25 oct. 08:10` | Ultima data di modifica. | -| `rockstar` | Il nome del file (o directory). | +| `rockstar` | Per un file di collegamento fisico: numero di collegamenti fisici. | +| `rockstar` | Per un file di tipo link fisico: numero di collegamenti fisici. | +| `4096` | Per un file di tipo di collegamento fisico: numero di collegamenti fisici. | +| `25 oct. 08:10` | Ultima data di modifica. | +| `rockstar` | Il nome del file (o directory). | -!!! Note "Nota" - Gli **Alias** sono spesso già inseriti nelle distribuzioni comuni. +!!! Note "Nota" Gli **Alias** sono spesso già inseriti nelle distribuzioni comuni. -Questo è il caso dell'alias `ll`: + Questo è il caso dell'alias `ll`: -```bash -alias ll='ls -l --color=auto' -``` + ``` + alias ll='ls -l --color=auto' + ``` Il comando `ls` ha molte opzioni ed ecco alcuni esempi avanzati di uso: @@ -576,8 +569,7 @@ dr-xr-xr-x. 5 root root 1024 2014-11-23 11-23 05:29 boot * Aggiungi la _trailing slash_ alla fine della cartella: -Per impostazione predefinita, il comando `ls` non visualizza l'ultima barra di una cartella. -In alcuni casi, come per gli script, ad esempio, è utile visualizzarla: +Per impostazione predefinita, il comando `ls` non visualizza l'ultima barra di una cartella. In alcuni casi, come per gli script, ad esempio, è utile visualizzarla: ```bash $ ls -dF /etc @@ -604,11 +596,9 @@ Esempio: $ mkdir /home/rockstar/work ``` -La directory "rockstar" deve esistere per creare la directory "work". -Altrimenti, dovrebbe essere utilizzata l'opzione `-p`. L'opzione `-p` crea le directory genitore se queste non esistono. +La directory "rockstar" deve esistere per creare la directory "work". Altrimenti, dovrebbe essere utilizzata l'opzione `-p`. L'opzione `-p` crea le directory genitore se queste non esistono. -!!! Danger "Pericolo" - Non è consigliato utilizzare i nomi dei comandi Linux come directory o nomi di file. +!!! Danger "Pericolo" Non è consigliato utilizzare i nomi dei comandi Linux come directory o nomi di file. ### comando `touch` @@ -624,14 +614,13 @@ Esempio : $ touch /home/rockstar/myfile ``` -| Opzione | Informazione | -| ----------- | ----------------------------------------------------------------------- | -| `-t date` | Modifica la data dell'ultima modifica del file con la data specificata. | +| Opzione | Informazione | +| --------- | ----------------------------------------------------------------------- | +| `-t date` | Modifica la data dell'ultima modifica del file con la data specificata. | Formato data: `[AAAA]MMJJhhmm[ss]` -!!! Tip "Suggerimento" - Il comando `touch` viene utilizzato principalmente per creare un file vuoto, ma può essere utile per i backup incrementali o differenziali per esempio. Davvero, l'unico effetto di eseguire un `touch` su un file sarà quello di costringerlo a essere salvato durante il backup successivo. +!!! Tip "Suggerimento" Il comando `touch` viene utilizzato principalmente per creare un file vuoto, ma può essere utile per i backup incrementali o differenziali per esempio. Davvero, l'unico effetto di eseguire un `touch` su un file sarà quello di costringerlo a essere salvato durante il backup successivo. ### comando `rmdir` @@ -647,8 +636,7 @@ $ rmdir /home/rockstar/work | ------- | --------------------------------------------------------------------- | | `-p` | Rimuove la directory o le directory principale fornite se sono vuote. | -!!! Tip "Suggerimento" - Per eliminare sia una directory non vuota che il suo contenuto, utilizzare il comando `rm`. +!!! Tip "Suggerimento" Per eliminare sia una directory non vuota che il suo contenuto, utilizzare il comando `rm`. ### comando`rm` @@ -658,8 +646,7 @@ Il comando `rm` elimina un file o una directory. rm [-f] [-r] file [file] [...] ``` -!!! Danger "Pericolo" - Qualsiasi cancellazione di un file o directory è definitiva. +!!! Danger "Pericolo" Qualsiasi cancellazione di un file o directory è definitiva. | Opzioni | Informazione | | ------- | ------------------------------------------ | @@ -667,8 +654,7 @@ rm [-f] [-r] file [file] [...] | `-i` | Richiede conferma di cancellazione. | | `-r` | Elimina ricorsivamente le sottodirectory.. | -!!! Note "Nota" - Il comando `rm` non chiede la conferma durante l'eliminazione dei file. Tuttavia, con una distribuzione RedHat/Rocky, `rm` chiede la conferma della cancellazione in quanto il comando `rm` è un` alias` di `rm -i`. Non sorprenderti se su un'altra distribuzione, come Debian, ad esempio, non ottieni una richiesta di conferma. +!!! Note "Nota" Il comando `rm` non chiede la conferma durante l'eliminazione dei file. Tuttavia, con una distribuzione RedHat/Rocky, `rm` chiede la conferma della cancellazione in quanto il comando `rm` è un`alias` di `rm -i`. Non sorprenderti se su un'altra distribuzione, come Debian, ad esempio, non ottieni una richiesta di conferma. L'eliminazione di una cartella con il comando `rm`, che la cartella sia vuota o meno, richiederà l'aggiunta dell'opzione `-r`. @@ -763,6 +749,7 @@ $ cp -r /home/rockstar /tmp | `-f` | Non chiedere conferma per la sovrascrittura del file di destinazione. | | `-p` | Mantiene il proprietario, le autorizzazioni e il timestamp del file copiato. | | `-r` | Copia una directory con i suoi file e sottodirectory. | +| `-s` | Crea un collegamento simbolico invece di copiare | ```bash cp file1 /repexist/file2 @@ -834,16 +821,16 @@ less file1 [files] I comandi specifici per `less` sono: -| Command | Action | -| ----------------- | ----------------------------------------------------- | -| `h` | Aiuto. | -| `Arrows` | Sposta su, giù di una linea, o a destra e sinistra. | -| `Enter` | Sposta giù di una riga. | -| `Space` | Sposta giù di una pagina. | -| `PgUp` and `PgDn` | Sposta su o giù di una pagina. | -| `Begin` and `End` | Passa all'inizio o alla fine di un file. | -| `/text` | Cerca il testo. | -| `q` | Chiude il comando`less`. | +| Command | Action | +| ----------------- | --------------------------------------------------- | +| `h` | Aiuto. | +| `Arrows` | Sposta su, giù di una linea, o a destra e sinistra. | +| `Enter` | Sposta giù di una riga. | +| `Space` | Sposta giù di una pagina. | +| `PgUp` and `PgDn` | Sposta su o giù di una pagina. | +| `Begin` and `End` | Passa all'inizio o alla fine di un file. | +| `/text` | Cerca il testo. | +| `q` | Chiude il comando`less`. | ### comando `cat` @@ -916,7 +903,7 @@ head [-n x] file ``` | Opzione | Osservazione | -| --------- | ----------------------------------- | +| ------- | --------------------------------- | | `-n x` | Mostra le prime linee`x` del file | Per impostazione predefinita (senza l'opzione `-n`), il comando `head` visualizzerà le prime 10 righe del file. @@ -965,13 +952,14 @@ root:x:0:0:root:/root:/bin/bash adm:x:3:4:adm:/var/adm/:/sbin/nologin ``` -| Opzione | Osservazione | -| ------------ | --------------------------------------------------- | -| `-kx` | Specifica la colonna`x` per ordinare | -| `-n` | Richiede un ordinamento numerico | -| `-o file` | Salva l'ordinamento nel file specificato | -| `-ty` | Specifica il carattere del separatore del campo `y` | -| `-r` | Inverte l'ordine del risultato | +| Opzione | Observation | +| --------- | --------------------------------------------------- | +| `-kx` | Specifica la colonna`x` per ordinare | +| `-n` | Richiede un ordinamento numerico | +| `-o file` | Salva l'ordinamento nel file specificato | +| `-ty` | Specifica il carattere del separatore del campo `y` | +| `-r` | Inverte l'ordine del risultato | +| `- u` | unico | Il comando `sort` ordina il file solo sullo schermo. Il file non è modificato dall'ordinamento. Per salvare l'ordinamento, usa l'opzione `-o` o un reindirizzamento dell'output `>`. @@ -987,7 +975,7 @@ adm:x:3:4:adm:/var/adm/:/sbin/nologin In questo esempio, il comando `sort` ordinerà il contenuto del file `/etc /passwd` questa volta dal UID più grande al più piccolo. -Alcuni esempi avanzati di utilizzazione del comando `sort` +Alcuni esempi avanzati di utilizzazione del comando `sort`: * Mischiando valori @@ -1001,9 +989,9 @@ $ sort -R /etc/passwd Un amministratore di sistema si deve spesso confrontare con l'elaborazione di indirizzi IP provenienti dai registri dei suoi servizi come SMTP, VSFTP o Apache. Questi indirizzi sono tipicamente estratti con il comando `cut`. -Ecco un esempio con il file `dns-client.txt` : +Ecco un esempio con il file `dns-client.txt`: -```bash +``` 192.168.1.10 192.168.1.200 5.1.150.146 @@ -1020,13 +1008,34 @@ $ sort -nr dns-client.txt 5.1.150.146 ``` -* Ordinamento dei file per dimensioni +* Ordinamento file rimuovendo i duplicati -Il comando `sort` sa come riconoscere le dimensioni dei file, dai comandi come `ls` con l'opzione `-h`. +Il comando `sort` sa come rimuovere i duplicati dall'output del file usando `-u` come opzione. -Ecco un esempio con il file `size.txt` : +Ecco un esempio con il file `colours.txt`: -```bash +``` +Red +Green +Blue +Red +Pink +``` +``` +$ sort -u colours.txt +Blue +Green +Pink +Red +``` + +* Ordinamento file per dimensioni + +Il comando `sort` sa riconoscere le dimensioni dei file, da comandi come `ls` con l'opzione `-h`. + +Ecco un esempio con il file `size.txt`: + +``` 1,7G 18M 69K @@ -1061,7 +1070,7 @@ Il comando `wc` conta il numero di linee, parole e/o byte in un file. wc [-l] [-m] [-w] file [files] ``` -| Option | Observation | +| Option | Osservazione | | ------ | ----------------------------- | | `-c` | Conta il numero di byte. | | `-m` | Conta il numero di caratteri. | @@ -1097,21 +1106,22 @@ $ find /tmp -name *.txt -exec rm -f {} \; Il comando precedente cerca tutti i file nella directory `/tmp` con il suffisso `*.txt` e li elimina. -!!! Tip "Comprendere l'opzione `-exec`" - Nell'esempio sopra, il comando `find` costruirà una stringa che rappresenta il comando da eseguire. -Se il comando `find` trova tre file denominati `log1.txt`, `log2.txt`, e `log3.txt`, il comando `find` costruirà la stringa sostituendo nella stringa `rm -f {} \;` le parentesi graffe con uno dei risultati della ricerca, e farà questo tutte le volte che ci sono dei risultati. +!!! Tip "Comprendere l'opzione `-exec`" +Nell'esempio sopra, il comando `find` costruirà una stringa che rappresenta il comando da eseguire. -Questo ci darà : + Se il comando `find` trova tre file denominati `log1.txt`, `log2.txt`, e `log3.txt`, il comando `find` costruirà la stringa sostituendo nella stringa `rm -f {} \;` le parentesi graffe con uno dei risultati della ricerca, e farà questo tutte le volte che ci sono dei risultati. + + Questo ci darà: + + ``` + rm -f /tmp/log1.txt ; rm -f /tmp/log2.txt ; rm -f /tmp/log3.txt ; + ``` -```bash -rm -f /tmp/log1.txt ; rm -f /tmp/log2.txt ; rm -f /tmp/log3.txt ; -``` -Il carattere `;` è un carattere speciale di shell che deve essere protetto da `\` per evitare che venga interpretato troppo presto dal comando `find` (e non nel `-exec`). + Il carattere `;` è un carattere speciale di shell che deve essere protetto da `\` per evitare che venga interpretato troppo presto dal comando `find` (e non nel `-exec`). -!!! Tip "Suggerimento" - `$ find /tmp -name *.txt -delete` fa la stessa cosa. +!!! Tip "Suggerimento" `$ find /tmp -name *.txt -delete` fa la stessa cosa. ### comando `whereis` @@ -1156,7 +1166,6 @@ root:x:0:0:root:/root:/bin/bash | `-w` | Cerca la parola esatta. | Il comando `grep` restituisce la linea completa contenente la stringa che stai cercando. - * Il carattere speciale `^` è usato per cercare una stringa all'inizio di una linea. * Il carattere speciale `$` cerca una stringa alla fine di una linea. @@ -1164,8 +1173,7 @@ Il comando `grep` restituisce la linea completa contenente la stringa che stai c $ grep -w "^root" /etc/passwd ``` -!!! Note "Nota" - Questo comando è molto potente ed è altamente raccomandata la consultazione del manuale. Ha molti utilizzi derivati. +!!! Note "Nota" Questo comando è molto potente ed è altamente raccomandata la consultazione del manuale. Ha molti utilizzi derivati. È possibile cercare una stringa in un albero di file con l'opzione `-R`. @@ -1205,11 +1213,9 @@ $ find /home -name "test[123]*" /home/rockstar/test362 ``` -!!! Note "Nota" - Delimita sempre le parole contenenti meta-caratteri con `"` per evitare che vengano sostituiti dai nomi dei file che soddisfano i criteri. +!!! Note "Nota" Delimita sempre le parole contenenti meta-caratteri con `"` per evitare che vengano sostituiti dai nomi dei file che soddisfano i criteri. -!!! Warning "Avvertimento" - Non confondere i meta-caratteri della shell con i meta-caratteri dell'espressione regolare. Il comando `grep` usa i meta-caratteri dell'espressione regolare. +!!! Warning "Avvertimento" Non confondere i meta-caratteri della shell con i meta-caratteri dell'espressione regolare. Il comando `grep` usa i meta-caratteri dell'espressione regolare. ## Reindirizzamenti e pipes @@ -1220,7 +1226,6 @@ Sui sistemi UNIX e Linux, ci sono tre flussi standard. Consentono ai programmi, Questi flussi sono chiamati canale X descrittore di file X. Per impostazione predefinita: - * la tastiera è il dispositivo di input per il canale 0, chiamato **stdin** ; * lo schermo è il dispositivo di uscita per i canali 1 e 2, chiamati **stdout** e **stderr**. @@ -1238,8 +1243,7 @@ Questi flussi puntano ai file delle periferiche, ma poiché tutto è un file in $ ftp -in serverftp << ftp-commands.txt ``` -!!! Note "Nota" - Solo i comandi che richiedono l'input della tastiera saranno in grado di gestire il reindirizzamento dell'ingresso. +!!! Note "Nota" Solo i comandi che richiedono l'input della tastiera saranno in grado di gestire il reindirizzamento dell'ingresso. Il reindirizzamento dell'ingresso può anche essere utilizzato per simulare l'interattività dell'utente. Il comando leggerà il flusso di input finché non incontrerà la parola chiave definita dopo il reindirizzamento dell'ingresso. @@ -1265,8 +1269,7 @@ STOP La shell esce dal comando `ftp` quando riceve una linea contenente solo la parola chiave. -!!! Warning "Avvertimento" - La parola chiave finale, quì `END` o `STOP`, deve essere l'unica parola sulla linea e deve essere all'inizio della linea. +!!! Warning "Avvertimento" La parola chiave finale, quì `END` o `STOP`, deve essere l'unica parola sulla linea e deve essere all'inizio della linea. Il reindirizzamento dell'ingresso standard viene usato raramente perché la maggior parte dei comandi accetta un nome di file come argomento. @@ -1306,7 +1309,7 @@ $ ls -R / 2>> errors_file ### Esempi di reindirizzamento -Reindirizzamento di 2 uscite a 2 file : +Reindirizzamento di 2 uscite a 2 file: ```bash $ ls -R / >> ok_file 2>> nok_file @@ -1352,7 +1355,7 @@ Mostra solo la fine: $ ls -lia / | tail ``` -Ordina il risultato.: +Ordina il risultato: ```bash $ ls -lia / | sort @@ -1376,7 +1379,7 @@ $ ls -lia / | grep fichier Il comando `tee` viene utilizzato per reindirizzare l'output standard di un comando a un file mantenendo il display dello schermo. -Viene combinato con la pipe `|` per ricevere come input l'output del comando da reindirizzare: +Viene combinato con la pipe `|` per ricevere come input l'output del comando da reindirizzare: ```bash $ ls -lia / | tee fic @@ -1395,7 +1398,7 @@ Per esempio: $ ll ``` -sostituirà il comando : +sostituirà il comando: ```bash $ ls -l @@ -1419,8 +1422,8 @@ Per un uso permanente, devono essere creati nel: * `.bashrc` file nella directory di accesso dell'utente; * `/etc/profile.d/alias.sh` file per tutti gli utenti. -!!! Warning "Avvertimento" - Prestare particolare attenzione quando si utilizzano alias che possono essere potenzialmente pericolosi! Ad esempio, un alias creato senza una conoscenza di base di amministratore: +!!! Warning "Avvertimento" Prestare particolare attenzione quando si utilizzano alias che possono essere potenzialmente pericolosi! Ad esempio, un alias creato senza una conoscenza di base di amministratore: + ```bash alias cd='rm -Rf' ``` @@ -1464,20 +1467,15 @@ file1.txt file2.txt file3.txt ### Aliases e funzioni utili -* `grep` alias - Colora il risultato del comando `grep`: - `alias grep='grep --color=auto'` -* `mcd` function - È comune creare una cartella e quindi muoversi in essa: - `mcd() { mkdir -p "$1"; cd "$1"; }` -* `cls` function - Spostati in una cartella e elenca il suo contenuto: - `cls() { cd "$1"; ls; }` -* `backup` function - Creare una copia di backup di un file: - `backup() { cp "$1"{,.bak}; }` -* `extract` function - Estrai qualsiasi tipo di archivio: +* `grep` alias Colora il risultato del comando `grep`: `alias grep='grep --color=auto'` + +* `mcd` function È comune creare una cartella e quindi muoversi in essa: `mcd() { mkdir -p "$1"; cd "$1"; }` + +* `cls` function Spostati in una cartella e elenca il suo contenuto: `cls() { cd "$1"; ls; }` + +* `backup` function Creare una copia di backup di un file: `backup() { cp "$1"{,.bak}; }` + +* `extract` function Estrai qualsiasi tipo di archivio: ```bash extract () { @@ -1504,8 +1502,7 @@ extract () { ``` -* Se `alias cmount` restituisce quanto segue: - `alias cmount="mount | column -t"` +* Se `alias cmount` restituisce quanto segue: `alias cmount="mount | column -t"` Possiamo usare il cmount per mostrare tutti i supporti del sistema in colonne come questa: @@ -1528,7 +1525,7 @@ none on /proc/sys/fs/binfmt_misc type binfmt_misc (r Il carattere `;` concatena i comandi. -I comandi funzioneranno tutti in sequenza nell'ordine di ingresso una volta che l'utente preme ENTER. +I comandi funzioneranno tutti in sequenza nell'ordine di ingresso una volta che l'utente preme ENTER. ```bash $ ls /; cd /home; ls -lia; cd / @@ -1564,4 +1561,4 @@ $ ls /; cd /home; ls -lia; cd / - [ ] `ls -R / 2> errors.log` - [ ] `ls -R / 2>> errors.log` -- [ ] `ls -R / 2> errors.log 2>&1` +- [ ] `ls -R / 2> errors.log 2>&1` From 65f93209ec54e31e15d8a6193f92e2e83c174bb1 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:03 -0500 Subject: [PATCH 27/37] New translations 03-commands.md (Chinese Simplified) --- docs/books/admin_guide/03-commands.zh.md | 1563 ++++++++++++++++++++++ 1 file changed, 1563 insertions(+) create mode 100644 docs/books/admin_guide/03-commands.zh.md diff --git a/docs/books/admin_guide/03-commands.zh.md b/docs/books/admin_guide/03-commands.zh.md new file mode 100644 index 0000000000..b0c06a8b85 --- /dev/null +++ b/docs/books/admin_guide/03-commands.zh.md @@ -0,0 +1,1563 @@ +--- +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** + +**Knowledge**: :star: +**Complexity**: :star: + +**阅读时间**: 40 分钟 + +**** + +## 概论 + +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. + +The commands will all run sequentially in the order of input once the user presses ENTER. + +```bash +$ ls /; cd /home; ls -lia; cd / +``` + +## 检测所学知识 + +: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` From a48be24063d9831927815c5f0c5ecb6e7f180f93 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:04 -0500 Subject: [PATCH 28/37] New translations 04-advanced-commands.md (Italian) --- .../admin_guide/04-advanced-commands.it.md | 74 +++++++++---------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/docs/books/admin_guide/04-advanced-commands.it.md b/docs/books/admin_guide/04-advanced-commands.it.md index e03e4b8fa8..7f9b097677 100644 --- a/docs/books/admin_guide/04-advanced-commands.it.md +++ b/docs/books/admin_guide/04-advanced-commands.it.md @@ -6,21 +6,21 @@ title: Comandi Avanzati Linux In questo capitolo imparerai alcuni comandi avanzati per Linux. ---- +**** **Obiettivi** : In questo capitolo, i futuri amministratori Linux impareranno: :heavy_check_mark: alcuni comandi utili non trattati nel capitolo precedente; -:heavy_check_mark: alcuni comandi avanzati. +:heavy_check_mark: alcuni comandi avanzati. :checkered_flag: **comandi utente**, **Linux** **Conoscenza**: :star: -**Complessità**: :star: :star: :star: +**Complessità**: :star: :star: :star: **Tempo di lettura**: 20 minuti ---- +**** ## comando `uniq` @@ -28,7 +28,7 @@ Il comando `uniq` è un comando molto potente, usato con il comando `sort`, sopr Per illustrare come funziona il comando `uniq`, usiamo un file `firstnames.txt` contenente un elenco di nomi primi: -```bash +``` antoine xavier steven @@ -39,12 +39,11 @@ antoine steven ``` -!!! Note "Nota" - `uniq` richiede che il file di input sia ordinato perché confronta solo le linee consecutive. +!!! !!! Note "Nota" `uniq` richiede che il file di input sia ordinato perché confronta solo le linee consecutive. Senza un argomento, il comando `uniq` non mostrerà righe identiche che si susseguono nel file `firstnames.txt`: -```bash +``` $ sort firstnames.txt | uniq antoine patrick @@ -54,14 +53,14 @@ xavier Per visualizzare solo le righe che appaiono solo una volta, utilizzare l'opzione `-u`: -```bash +``` $ sort firstnames.txt | uniq -u patrick ``` Al contrario, per visualizzare solo le linee che appaiono almeno due volte nel file, è necessario utilizzare l'opzione `-d`: -```bash +``` $ sort firstnames.txt | uniq -d antoine steven @@ -70,7 +69,7 @@ xavier Per eliminare semplicemente linee che appaiono solo una volta, utilizzare l'opzione `-D`: -```bash +``` $ sort firstnames.txt | uniq -D antoine antoine @@ -83,7 +82,7 @@ xavier Infine, contare il numero di occorrenze di ciascuna linea, utilizzare l'opzione `-c`: -```bash +``` $ sort firstnames.txt | uniq -c 3 antoine 1 patrick @@ -91,7 +90,7 @@ $ sort firstnames.txt | uniq -c 2 xavier ``` -```bash +``` $ sort firstnames.txt | uniq -cd 3 antoine 2 steven @@ -106,7 +105,7 @@ Il comando `xargs` legge lo spazio bianco o gli argomenti delimitati da linefeed Un primo e più semplice esempio sarebbe il seguente: -```bash +``` $ xargs use of @@ -117,7 +116,7 @@ use of xargs Il comando `xargs` attende un input dallo standard input **stdin**. Sono state inserite tre linee. La fine dell'ingresso dell'utente in `xargs` è specificato dalla sequenza di tasti CTRL+D. `xargs` esegue quindi il comando predefinito `echo` seguito dai tre argomenti corrispondenti all'ingresso dell'utente, vale a dire: -```bash +``` $ echo "use" "of" "xargs" use of xargs ``` @@ -126,7 +125,7 @@ use of xargs Nell'esempio seguente, `xargs` eseguirà il comando `ls -ld` sul set di cartelle specificate nell'input standard: -```bash +``` $ xargs ls -ld /home /tmp @@ -141,7 +140,7 @@ In pratica, il comando `xargs` esegue il comando `ls -ld /home /tmp /root`. Cosa succede se il comando da eseguire non accetta più di un argomento come nel caso del comando `find`? -```bash +``` $ xargs find /var/log -name *.old *.log @@ -150,14 +149,14 @@ find: paths must precede expression: *.log Il comando `xargs` tenta di eseguire il comando `find` con più argomenti dietro l'opzione `-name`, questo causa la generazione di un errore in `find`: -```bash +``` $ find /var/log -name "*.old" "*.log" find: paths must precede expression: *.log ``` In questo caso, il comando `xargs` deve essere costretto ad eseguire il comando `find` più volte (una volta per riga immessa come ingresso standard). L'opzione `-L` Seguito da un **intero** consente di specificare il numero massimo di voci da elaborare con il comando contemporaneamente: -```bash +``` $ xargs -L 1 find /var/log -name *.old /var/log/dmesg.old @@ -176,7 +175,7 @@ $ xargs -L 1 find /var/log -name Se vogliamo essere in grado di specificare entrambi gli argomenti sulla stessa linea, dobbiamo usare l'opzione `-n 1` : -```bash +``` $ xargs -n 1 find /var/log -name *.old *.log /var/log/dmesg.old @@ -194,7 +193,7 @@ $ xargs -n 1 find /var/log -name Caso di esempio di un backup con un `tar` basato su una ricerca: -```bash +``` $ find /var/log/ -name "*.log" -mtime -1 | xargs tar cvfP /root/log.tar $ tar tvfP /root/log.tar -rw-r--r-- root/root 1720 2017-04-05 15:43 /var/log/boot.log @@ -205,7 +204,7 @@ La caratteristica speciale del comando `xargs` è che posiziona l'argomento di i Ora, se prendiamo l'esempio del comando `cp` e vogliamo copiare un elenco di file in una directory, questo elenco di file verrà aggiunto alla fine del comando... ma quello che si aspetta il comando `cp` alla fine del comando è la destinazione. Per fare ciò, usiamo l'opzione `-I` per mettere gli argomenti di input da qualche altra parte rispetto alla fine della linea. -```bash +``` $ find /var/log -type f -name "*.log" | xargs -I % cp % /root/backup ``` @@ -216,7 +215,7 @@ L'opzione `-I` ti consente di specificare un carattere (nel nostro esempio ilcar Il pacchetto `yum-utils` è una raccolta di utilità da diversi autori per `yum`, che lo rendono più facile e più potente da usare. !!! Note "Nota" - Mentre `yum` è stato sostituito da` dnf` in Rocky Linux 8, Il nome del pacchetto è rimasto `yum-utils` anche se può essere installato come `dnf-utils`. Queste sono le classiche utilità YUM implementate come CLI shims sopra a DNF per mantenere la compatibilità all'indietro con `yum-3`. +Mentre `yum` è stato sostituito da`dnf` in Rocky Linux 8, Il nome del pacchetto è rimasto `yum-utils` anche se può essere installato come `dnf-utils`. Queste sono le classiche utilità YUM implementate come CLI shims sopra a DNF per mantenere la compatibilità all'indietro con `yum-3`. Ecco alcuni esempi di utilizzo: @@ -226,15 +225,15 @@ Il comando `repoquery` interroga i repository. Esempi di utilizzo: -* Conoscere le dipendenze di un pacchetto disinstallato: + * Conoscere le dipendenze di un pacchetto disinstallato: -```bash +``` repoquery --requires ``` -* Conoscere i file forniti da un pacchetto non installato: + * Conoscere i file forniti da un pacchetto non installato: -```bash +``` $ repoquery -l yum-utils /etc/bash_completion.d /etc/bash_completion.d/yum-utils.bash @@ -267,11 +266,11 @@ $ repoquery -l yum-utils Il comando `yumdownloader` scarica i pacchetti RPM dai repository. !!! Note "Nota" - Questo comando è molto utile per costruire rapidamente un repository locale di alcuni rpm! +Questo comando è molto utile per costruire rapidamente un repository locale di alcuni rpm! Esempio: `yumdownloader` scaricherà il pacchetto rpm _repoquery_ e tutte le sue dipendenze: -```bash +``` $ yumdownloader --destdir /var/tmp --resolve repoquery ``` @@ -290,7 +289,7 @@ Il pacchetto `psmisc` contiene utilità per la gestione dei processi di sistema: Esempi: -```bash +``` $ pstree systemd─┬─NetworkManager───2*[{NetworkManager}] ├─agetty @@ -310,13 +309,13 @@ systemd─┬─NetworkManager───2*[{NetworkManager}] └─tuned───4*[{tuned}] ``` -```bash +``` # killall httpd ``` Arresta i processi (opzione `-k`) che accedono al file `/etc/httpd/conf/httpd.conf`: -```bash +``` # fuser -k /etc/httpd/conf/httpd.conf ``` @@ -326,20 +325,19 @@ Il comando `watch` esegue regolarmente un comando e visualizza il risultato nel L'opzione `-n` consente di specificare il numero di secondi tra ogni esecuzione del comando. -!!! Note "Nota" - Per uscire dal comando `watch`, devi digitare i tasti: CTRL+C per arrestare il processo. +!!! Note "Nota" Per uscire dal comando `watch`, devi digitare i tasti: CTRL+C per arrestare il processo. Esempi: * Mostra la fine del file `/etc/passwd` ogni 5 secondi: -```bash +``` $ watch -n 5 tail -n 3 /etc/passwd ``` Risultato: -```bash +``` Every 5,0s: tail -n 3 /etc/passwd rockstar.rockylinux.lan: Thu Jul 1 15:43:59 2021 sssd:x:996:993:User for sssd:/:/sbin/nologin @@ -349,12 +347,12 @@ sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin * Monitoraggio del numero di file in una cartella: -```bash +``` $ watch -n 1 'ls -l | wc -l' ``` * Mostra un orologio: -```bash +``` $ watch -t -n 1 date ``` From 2cd69008eb39b91c22e0fdbf3cde3787154c573d Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:05 -0500 Subject: [PATCH 29/37] New translations 07-file-systems.md (French) --- docs/books/admin_guide/07-file-systems.fr.md | 1068 ++++++++++++++++++ 1 file changed, 1068 insertions(+) create mode 100644 docs/books/admin_guide/07-file-systems.fr.md diff --git a/docs/books/admin_guide/07-file-systems.fr.md b/docs/books/admin_guide/07-file-systems.fr.md new file mode 100644 index 0000000000..0f9356c2ef --- /dev/null +++ b/docs/books/admin_guide/07-file-systems.fr.md @@ -0,0 +1,1068 @@ +--- +title: File System +--- + +# File System + +In this chapter you will learn how to work with filesystems. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: manage partitions on disk; +:heavy_check_mark: use LVM for a better use of disk resources; +:heavy_check_mark: provide users with a filesystem and manage the access rights. + +and also discover: + +:heavy_check_mark: how the tree structure is organized in Linux; +:heavy_check_mark: the different types of files offered and how to work with them; + +:checkered_flag: **hardware**, **disk**, **partition**, **lvm**, **linux** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**Temps de lecture : **20 minutes + +**** + +## Partitioning + +Partitioning will allow the installation of several operating systems because it is impossible to have several of them cohabit on the same logical drive. Partitioning also allows the separation of data logically (security, access optimization, ...). + +The division of the physical disk into partitioned volumes is recorded in the partition table, stored in the first sector of the disk (MBR: _Master Boot Record_). + +The same physical disk can be divided into a maximum of 4 partitions: + +* *Primary* (or main) +* *Extended* + +!!! Warning There can be only one extended partition per physical disk. In order to benefit from additional drives, the extended partition can be split into logical partitions + +![Breakdown into only 4 primary partitions](images/07-file-systems-001.png) + +![Breakdown into 3 primary partitions and one extended](images/07-file-systems-002.png) + +The _devices_ are the files identifying the various hardware detected by the motherboard. These files are stored without `/dev`. The service which detects new devices and gives them names is called *udev*. + +They are identified by their type. + +Storage devices are named *hd* for IDE hard drives and *sd* for other media. Then comes a letter that starts with *a* for the first device, then *b*, *c*, ... + +Finally we will find a number that defines the partitioned volume: *1* for the first primary partition, ... + +!!! Warning Beware, the extended partition, which does not support a file system, still has a number. + +![Identification of partitions](images/07-file-systems-003.png) + +There are at least two commands for partitioning a disk: `fdisk` and `cfdisk`. Both commands have an interactive menu. `cfdisk` is more reliable and better optimized, so it is best to use it. + +The only reason to use `fdisk` is when you want to list all logical devices with the `-l` option. + +``` +sudo fdisk -l +sudo fdisk -l /dev/sdc +sudo fdisk -l /dev/sdc2 +``` + +### `parted` command + +The `parted` (_partition editor_) command is able to partition a disk. + +``` +parted [-l] [device] +``` + +It also has a recovery function capable of rewriting a deleted partition table. + +Under graphical interface, there is the very complete `gparted` tool: *G*nome *PAR*tition *ED*itor. + +The `gparted -l` command lists all logical devices on a computer. + +The `gparted` command alone will return to an interactive mode with its own internal options: + +* `help` or an incorrect command will display these options. +* `print all` in this mode will have the same result as `gparted -l` on the command line. +* `quit` to return to the prompt. + +### `cfdisk` command + +The `cfdisk` command is used to manage partitions. + +``` +cfdisk device +``` + +Example: + +``` +$ sudo cfdisk /dev/sda + Disk: /dev/sda + Size: 16 GiB, 17179869184 bytes, 33554432 sectors + Label: dos, identifier: 0xcf173747 + Device Boot Start End Sectors Size Id Type +>> /dev/sda1 * 2048 2099199 2097152 1G 83 Linux + /dev/sda2 2099200 33554431 31455232 15G 8e Linux LVM + lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk + x Partition type: Linux (83) x + x Attributes: 80 x + xFilesystem UUID: 54a1f5a7-b8fa-4747-a87c-2dd635914d60 x + x Filesystem: xfs x + x Mountpoint: /boot (mounted) x + mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj + [Bootable] [ Delete ] [ Resize ] [ Quit ] [ Type ] [ Help ] + [ Write ] [ Dump ] +``` + +The preparation, without _LVM_, of the physical media goes through five steps: + +* Setting up the physical disk; +* Partitioning of the volumes (geographical division of the disk, possibility of installing several systems, ...); +* Creation of the file systems (allows the operating system to manage the files, the tree structure, the rights, ...); +* Mounting of file systems (registration of the file system in the tree structure); +* Manage user access. + +## Logical Volume Manager (LVM) + +**L**ogical **V**olume **M**anager (*LVM]*) + +Volume management creates an abstract layer on top of physical storage, offering advantages over using physical storage directly: + +* More flexible disk capacity; +* Online data movement; +* Disks in _stripe_ mode; +* Mirrored volumes (recopy); +* Volume snapshots (_snapshot_). + +The disadvantage is that if one of the physical volumes becomes out of order, then all the logical volumes that use this physical volume are lost. You will have to use LVM on raid disks. + +LVM is available under Linux from kernel version 2.4. + +!!! Note LVM is only managed by the operating system. Therefore the _BIOS_ needs at least one partition without LVM to boot. + +### Volume groups + +The physical volumes *PV* _Physical Volumes_ (from partitions) are combined into volume groups *VG*. Each *VG* represents disk space that can be partitioned into *LV* _Logical Volumes_. *Extension* is the smallest unit of fixed-size space that can be allocated. + +* **PE** : _Physical Extension_ +* **LE** : _Logical Extension_ + +![Volume group, PE size equal to 4MB](images/07-file-systems-004.png) + +### Logical volumes + +A volume group, *VG*, is divided into logical volumes, *LV*, offering different operating modes: + +* Linear volumes; +* Volumes in _stripe_ mode; +* Mirrored volumes. + +![Linear volumes](images/07-file-systems-005.png) + +![Volumes in stripe mode](images/07-file-systems-006.png) + +!!! Tip Striping_ improves performance by writing data to a predetermined number of physical volumes with a _round-robin_ technique. + +![Mirrored volumes](images/07-file-systems-007.png) + +### LVM commands for volume management + +#### `pvcreate` command + +The `pvcreate` command is used to create physical volumes. It turns Linux partitions (or disks) into physical volumes. + +``` +pvcreate [-options] partition +``` + +Example: + +``` +[root]# pvcreate /dev/hdb1 +pvcreate -- physical volume « /dev/hdb1 » successfully created +``` + +You can also use a whole disk (which facilitates disk size increases in virtual environments for example). + +``` +[root]# pvcreate /dev/hdb +pvcreate -- physical volume « /dev/hdb » successfully created +``` + +| Option | Description | +| ------ | ---------------------------------------------------------------------------------- | +| `-f` | Forces the creation of the volume (disk already transformed into physical volume). | + +#### `vgcreate` command + +The `vgcreate` command is used to create volume groups. It groups one or more physical volumes into a volume group. + +``` +vgcreate volume physical_volume [PV...] +``` + +Example: + +``` +[root]# vgcreate volume1 /dev/hdb1 +… +vgcreate – volume group « volume1 » successfully created and activated +``` + +#### `lvcreate` command + +The `lvcreate` command creates logical volumes. The file system is then created on these logical volumes. + +``` +lvcreate -L size [-n name] VG_name +``` + +Example: + +``` +[root]# lvcreate –L 600M –n VolLog1 volume1 +lvcreate -- logical volume « /dev/volume1/VolLog1 » successfully created +``` + +| Option | Description | +| --------- | ------------------------------------------------------------------- | +| `-L size` | Logical volume size in K, M or G. | +| `-n name` | LV name. Special file created in `/dev/name_volume` with this name. | + +### LVM commands to view volume information + +#### `pvdisplay` command + +The `pvdisplay` command allows you to view information about the physical volumes. + +``` +pvdisplay /dev/PV_name +``` + +Example: + +``` +[root]# pvdisplay /dev/PV_name +``` + +#### `vgdisplay` command + +The `vgdisplay` command allows you to view information about volume groups. + +``` +vgdisplay VG_name +``` + +Example: + +``` +[root]# vgdisplay volume1 +``` + +#### `lvdisplay` command + +The `lvdisplay` command allows you to view information about the logical volumes. + +``` +lvdisplay /dev/VG_name/LV_name +``` + +Example: + +``` +[root]# lvdisplay /dev/volume1/VolLog1 +``` + +### Preparation of the physical media + +The preparation with LVM of the physical support is broken down as follows: + +* Setting up the physical disk +* Partitioning of the volumes +* **LVM physical volume** +* **LVM volume groups** +* **LVM logical volumes** +* Creating file systems +* Mounting file systems +* Manage user access + +## Structure of a file system + +A _file system_ **FS** is in charge of the following actions: + +* Securing access and modification rights to files; +* Manipulating files: create, read, modify and delete; +* Locating files on the disk; +* Managing partition space. + +The Linux operating system is able to use different file systems (ext2, ext3, ext4, FAT16, FAT32, NTFS, HFS, BtrFS, JFS, XFS, ...). + +### `mkfs` command + +The `mkfs` command allows you to create a Linux file system. + +``` +mkfs [-t fstype] filesys +``` + +Example: + +``` +[root]# mkfs -t ext4 /dev/sda1 +``` + +| Option | Description | +| ------ | ----------------------------------------- | +| `-t` | Indicates the type of file system to use. | + +!!! Warning Without a file system it is not possible to use the disk space. + +Each file system has a structure which is identical on each partition. A **boot block** and a **super block** initialized by the system and then an **inode table** and a **data area** initialized by the administrator. + +!!! Note The only exception is the **swap** partition. + +### Boot block + +The **boot block** occupies the first block on the disk and is present on all partitions. It contains the program that starts and initializes the system and is therefore only filled in for the boot partition. + +### Super block + +The size of the **super block** table is defined at creation. It is present on each partition and contains the elements necessary for its utilization. + +It describes the File System: + +* Name of the Logical Volume; +* Name of the File System; +* Type of the File System; +* File System Status; +* Size of the File System; +* Number of free blocks; +* Pointer to the beginning of the list of free blocks; +* Size of the inode list; +* Number and list of free inodes. + +A copy is loaded in the central memory as soon as the system is initialized. This copy is updated as soon as it is modified and the system saves it periodically (command `sync`). + +When the system stops, it also copies this table in memory to its block. + +### Table of inodes + +The size of the **inode table** is defined at its creation and is stored on the partition. It consists of records, called inodes, corresponding to the files created. Each record contains the addresses of the data blocks making up the file. + +!!! Note An inode number is unique within a file system. + +A copy is loaded in the central memory as soon as the system is initialized. This copy is updated as soon as it is modified and the system saves it periodically (command `sync`). + +When the system stops, it also copies this table in memory to its block. + +A file is managed by its inode number. + +!!! Note The size of the inode table determines the maximum number of files the FS can contain. + +Information present in the *inode table* : + +* Inode number; +* File type and access permissions; +* Owner identification number; +* Identification number of the owner group; +* Number of links on this file; +* Size of the file in bytes; +* Date the file was last accessed; +* Date the file was last modified; +* Date of the last modification of the inode (= creation); +* Table of several pointers (block table) to the logical blocks containing the pieces of the file. + +### Data area + +Its size corresponds to the rest of the available space of the partition. This area contains the catalogs corresponding to each directory and the data blocks corresponding to the contents of the files. + +**In order to guarantee the consistency of the file system**, an image of the superblock and the inode table is loaded into memory (RAM) when the operating system is loaded so that all I/O operations are done through these system tables. When the user creates or modifies files, this memory image is updated first. The operating system must therefore regularly update the superblock of the logical disk (`sync` command). + +These tables are written to the hard disk when the system is shut down. + +!!! Danger In the event of a sudden stop, the file system may lose its consistency and cause data loss. + +### Repairing the file system + +It is possible to check the consistency of a file system with the `fsck` command. + +In case of errors, solutions are proposed to repair the inconsistencies. After repair, files that remain without entries in the inode table are attached to the `/lost+found` folder of the logical drive. + +#### `fsck` command + +The `fsck` command is a console-mode integrity check and repair tool for Linux file systems. + +``` +fsck [-sACVRTNP] [ -t fstype ] filesys +``` + +Example: + +``` +[root]# fsck /dev/sda1 +``` + +To check the root partition, it is possible to create a `forcefsck` file and reboot or run `shutdown` with the `-F` option. + +``` +[root]# touch /forcefsck +[root]# reboot +or +[root]# shutdown –r -F now +``` + +!!! Warning The partition to be checked must be unmounted. + +## Organization of a file system + +By definition, a File System is a tree structure of directories built from a root directory (a logical device can only contain one file system). + +![Organization of a file system](images/07-file-systems-008.png) + +!!! Note In Linux everything is a file. + +Text document, directory, binary, partition, network resource, screen, keyboard, Unix kernel, user program, ... + +Linux meets the **FHS** (_Filesystems Hierarchy Standard_) (see `man hier`) which defines the names of folders and their roles. + +| Directory | Observation | Abbreviation of | +| ---------- | ------------------------------------------------------------- | ----------------------------- | +| `/` | Contains special directories | | +| `/boot` | Files related to system startup | | +| `/sbin` | Commands necessary for system startup and repair | _system binaries_ | +| `/bin` | Executables of basic system commands | _binaries_ | +| `/usr/bin` | System administration commands | | +| `/lib` | Shared libraries and kernel modules | _libraries_ | +| `/usr` | Everything that is not necessary for minimal system operation | _UNIX System Resources_ | +| `/mnt` | For mounting temporary SF | _mount_ | +| `/media` | For mounting removable media | | +| `/root` | Administrator's login directory | | +| `/home` | User data | | +| `/tmp` | Temporary files | _temporary_ | +| `/dev` | Special device files | _device_ | +| `/etc` | Configuration and script files | _editable text configuration_ | +| `/opt` | Specific to installed applications | _optional_ | +| `/proc` | Virtual file system representing different processes | _les processus_ | +| `/var` | Miscellaneous variable files | _variables_ | + +* To perform a mount or unmount, at the tree level, you must not be under its mount point. +* Mounting on a non-empty directory does not delete the content. It is only hidden. +* Only the administrator can perform mounts. +* Mount points to be automatically mounted at boot time must be entered in `/etc/fstab`. + +### `/etc/fstab` file + +The `/etc/fstab` file is read at system startup and contains the mounts to be performed. Each file system to be mounted is described on a single line, the fields being separated by spaces or tabs. + +!!! Note Lines are read sequentially (`fsck`, `mount`, `umount`). + +``` +/dev/mapper/VolGroup-lv_root / ext4 defaults 1 1 +UUID=46….92 /boot ext4 defaults 1 2 +/dev/mapper/VolGroup-lv_swap swap swap defaults 0 0 +tmpfs /dev/shm tmpfs defaults 0 0 +devpts /dev/pts devpts gid=5,mode=620 0 0 +sysfs /sys sysfs defaults 0 0 +proc /proc proc defaults 0 0 + 1 2 3 4 5 6 +``` + +| Column | Description | +| ------ | ------------------------------------------------------------------------------------------------- | +| 1 | File system device (`/dev/sda1`, UUID=..., ...) | +| 2 | Mount point name, **absolute path** (except **swap**) | +| 3 | Filesystem type (ext4, swap, ...) | +| 4 | Special options for mounting (`defaults`, `ro`, ...) | +| 5 | Enable or disable backup management (0:not backed up, 1:backed up) | +| 6 | Check order when checking the SF with the `fsck` command (0:no check, 1:priority, 2:not priority) | + +The `mount -a` command allows new mounts to be taken into account without rebooting. They are then written to the `/etc/mtab` file which contains the current mounts. + +!!! Warning Only the mount points listed in `/etc/fstab` will be mounted on reboot. + +It is possible to make a copy of the `/etc/mtab` file or to copy its contents to `/etc/fstab`. + +### Mount management commands + +#### `mount` command + +The `mount` command allows you to mount and view the logical drives in the tree. + +``` +mount [-option] [device] [directory] +``` + +Example: + +``` +[root]# mount /dev/sda7 /home +``` + +| Option | Description | +| ------ | ------------------------------------------------------------------------------ | +| `-n` | Mount without writing to `/etc/mtab`. | +| `-t` | To indicate the type of file system to use. | +| `-a` | Mounts all filesystems mentioned in `/etc/fstab`. | +| `-r` | Mounts the file system read-only (equivalent to `-o ro`). | +| `-w` | Mounts the file system read/write, by default (equivalent `-o rw`). | +| `-o` | Argument followed by a comma-separated list of options (`remount`, `ro`, ...). | + +!!! Note The `mount` command alone displays all mounted file systems. + +#### `umount` command + +The `umount` command is used to unmount logical drives. + +``` +umount [-option] [device] [directory] +``` + +Example: + +``` +[root]# umount /home +[root]# umount /dev/sda7 +``` + +| Option | Description | +| ------ | -------------------------------------------------- | +| `-n` | Unmount without writing to `/etc/mtab`. | +| `-r` | If unmount fails, remount as read-only. | +| `-f` | Force unmount. | +| `-a` | Unmount all filesystems mentioned in `/etc/fstab`. | + +!!! Note When disassembling, you must not stay below the mounting point. Otherwise, the following error message is displayed: `device is busy`. + +## Types of files + +As in any system, in order to be able to find one's way through the tree structure and the file management, it is important to respect the file naming rules. + +* Files are coded on 255 characters; +* All ASCII characters can be used; +* Uppercase and lowercase letters are differentiated; +* No notion of extension. + +Groups of words separated by spaces must be enclosed in quotation marks: + +``` +[root]# mkdir "working dir" +``` + +!!! Note While there is nothing technically wrong with creating a file or directory with a space in it, it is generally a "best practice" to avoid this and replace any space with an underscore. + +!!! Note The **.** at the beginning of the file name only serves to hide it from a simple `ls`. + +!!! Warning Under Linux, the extension of a file is not a necessary reference to open or modify it. However, it can be useful for the user. + +Examples of extension agreements: + +* `.c` : source file in C language; +* `.h` : C and Fortran header file; +* `.o` : object file in C language; +* `.tar` : data file archived with the `tar` utility; +* `.cpio` : data file archived with the `cpio` utility; +* `.gz` : data file compressed with the `gzip` utility; +* `.tgz` : data file archived with the `tar` utility and compressed with the `gzip` utility; +* `.html` : web page. + +### Details of a file name + +``` +[root]# ls -liah /usr/bin/passwd +266037 -rwsr-xr-x 1 root root 59K mars 22 2019 /usr/bin/passwd +1 2 3 4 5 6 7 8 9 +``` + +| Row | Description | +| --- | ---------------------------------------------------------- | +| `1` | Inode number | +| `2` | File type (1st character of the block of 10) | +| `3` | Access rights (last 9 characters of the block of 10) | +| `4` | Number of links (ordinary) or subdirectories (directories) | +| `5` | Name of the owner | +| `6` | Name of the group | +| `7` | Size (byte, kilo, mega) | +| `8` | Date of last update | +| `9` | Name of the file | + +### Different types of files + +The following types of files can be found on a system: + +* Ordinary (text, binary, ...); +* Directories; +* Special (printers, screens, ...); +* Links; +* Communications (tubes and socket). + +#### Ordinary files + +These are text, program (source), executable (after compilation) or data (binary, ASCII) and multimedia files. + +``` +[root]# ls -l myfile +-rwxr-xr-x 1 root root 26 nov 31 15:21 myfile +``` + +The dash `-` at the beginning of the rights group (10-character block) indicates that it is an ordinary file type. + +#### Directory files + +Directory files contain references to other files. + +By default in each directory are present **.** and **..**. + +* The **.** represents the position in the tree. +* The **..** represents the father of the current position. + +``` +[root]# ls -l mydirectory +drwxr-xr-x 1 root root 26 nov 31 15:21 mydirectory +``` + +The letter `d` at the beginning of the rights group indicates that it is a directory type file. + +#### Special files + +In order to communicate with peripherals (hard disks, printers, ...), Linux uses interface files called special files (_device file_ or _special file_). They allow identification by the peripherals. + +These files are special because they do not contain data but specify the access mode to communicate with the device. + +They are defined in two modes: + +* **block** mode; +* **character** mode. + +##### Block mode + +The special **block mode** file allows, using the system buffers, to transfer data to the device. + +``` +[root]# ls -l /dev/sda +brw------- 1 root root 8, 0 jan 1 1970 /dev/sda +``` + +The letter `b` at the beginning of the rights group indicates that it is a special file **block**. + +##### Character mode + +The special *character mode* file is used to transfer data to the device as a stream of one character at a time without using a buffer. These are devices like printer, screen or DAT tapes, ... + +The standard output is the screen. + +``` +[root]# ls -l /dev/tty0 +crw------- 1 root root 8, 0 jan 1 1970 /dev/tty0 +``` + +The letter `c` at the beginning of the rights group indicates that it is a special character file. + +#### Communication files + +These are the pipe (_pipes_) and the _socket_ files. + +* **Pipe files** pass information between processes by FIFO (_First In, First Out_). One process writes transient information to a _pipe_ file and another reads it. After reading, the information is no longer accessible. + +* **Socket files** allow bidirectional inter-process communication (on local or remote systems). They use an _inode_ of the file system. + +#### Link files + +These files give the possibility to give several logical names to the same physical file. A new access point to the file is therefore created. + +There are two types of link files: + +* Physical links; +* Symbolic links. + +##### Physical link + +The link file and the source file have the same _inode_ number and the link counter is incremented. It is not possible to link different directories or files from different file systems. + +!!! Warning If the source file is destroyed, the counter is decremented and the link file still accesses the file. + +###### Command `ln` for a physical link + +The `ln` command allows you to create physical links. + +``` +[root]# ls –li letter +666 –rwxr--r-- 1 root root … letter +``` + +``` +[root]# ln /home/paul/letter /home/jack/read +``` + +``` +[root]# ls –li /home/*/* +666 –rwxr--r-- 2 root root … letter +666 –rwxr--r-- 2 root root … read +``` + +![Representation of a physical link](images/07-file-systems-009.png) + +##### Symbolic link + +Unlike the physical link, the symbolic link involves the creation of a new _inode_. At the symbolic link level, only a path is stored in the inode table. + +The file created contains only an indication of the path to the file. This notion no longer has the limitations of physical links and it is now possible to link directories and files belonging to different file systems. + +!!! Warning If the source file is destroyed, the link file can no longer access the file. + +###### `ln` command for a symbolic link + +The command `ln` with the argument `-s` allows to create symbolic links. + +``` +[root]# ls –li letter +666 -rwxr--r-- 1 root root … letter +``` + +``` +[root]# ln -s /home/paul/letter /tmp/read +``` + +``` +[root]# ls –li /home/paul/letter /tmp/read +666 -rwxr--r--- 1 root root … letter +678 lrwxrwxrwx 1 root root … read -> letter +``` + +![Representation of a symbolic link](images/07-file-systems-010.png) + +## File attributes + +Linux is a multi-user operating system where the control of access to files is essential. + +These controls are functions of: + +* file access permissions ; +* users (_ugo_ _Users Groups Others_). + +The command `ls -l` allows to display the attributes. + +There are 4 file access rights: + +* **r**ead; +* **w**rite; +* e**x**ecution; +* **-** no right. + +!!! Warning The rights associated with files differ from those associated with directories (see below). + +The user types associated with file access rights are: + +* **u**ser_ (owner) ; +* **g**roup_ (owner group); +* **o**thers (others users); + +In some commands it is possible to designate everyone with **a** (_all_). + +**a = ugo** + +### Rights associated with ordinary files + +* **r**ead: Allows reading a file (`cat`, `less`, ...) and copying a file (`cp`, ...). +* **w**rite: Allows modification of the file content (`cat`, `>>`, `vim`, ...). +* e**x**ecute: Considers the file as an e**X**ecutable (binary or script). +* **-**: No permissions. + +!!! Note Moving or renaming a file depends on the rights of the target directory. Deleting a file depends on the rights of the parent directory. + +### Rights associated with directories + +* **r**ead: Allows reading the contents of a directory (`ls -R`). +* **w**rite: Allows modification of the contents of a directory (`touch`) and allows creation and deletion of files if the **x** permission is enabled. +* e**x**ecute: Allows descending in the directory (`cd`). +* **-**: No rights. + +### Attribute management + +The display of rights is done with the command `ls -l`. It is the last 9 characters of the block of 10. More precisely 3 times 3 characters. + +``` +[root]# ls -l /tmp/myfile +-rwxrw-r-x 1 root sys ... /tmp/myfile + 1 2 3 4 5 +``` + +| Row | Description | +| --- | ------------------------------------------------- | +| 1 | Owner (**u**ser) permissions, here `rwx` | +| 2 | Owner group permissions (**g**roup), here `rw-` | +| 3 | Other users' permissions (**o**thers), here `r-x` | +| 4 | File owner | +| 5 | Group owner of the file | + +!!! Note Permissions apply to **u**ser, **g**roup and **o**ther (**ugo**) depending on the owner and group. + +By default, the _owner_ of a file is the one who creates it. The _group_ of the file is the group of the owner who created the file. The _others_ are those which are not concerned by the previous cases. + +The attributes are changed with the `chmod` command. + +Only the administrator and the owner of a file can change the rights of a file. + +#### `chmod` command + +The `chmod` command allows you to change the access permissions to a file. + +``` +chmod [option] mode file +``` + +The mode indication can be an octal representation (e.g. `744`) or a symbolic representation ([`ugoa`][`+=-`][`rwxst`]). + +Several symbolic operations can be separated by commas + +Example: + +``` +[root]# chmod -R u+rwx,g+wx,o-r /tmp/file1 +[root]# chmod g=x,o-r /tmp/file2 +[root]# chmod -R o=r /tmp/file3 +``` + +``` +[root]# ls -l /tmp/fic* +-rwxrwx--- 1 root root … /tmp/file1 +-rwx--x--- 1 root root … /tmp/file2 +-rwx--xr-- 1 root root … /tmp/file3 +``` + +``` +[root]# chmod 741 /tmp/file1 +[root]# chmod -R 744 /tmp/file2 +[root]# ls -l /tmp/fic* +-rwxr----x 1 root root … /tmp/file1 +-rwxr--r-- 1 root root … /tmp/file2 +``` + +| Option | Observation | +| ------ | --------------------------------------------------------------------- | +| `-R` | Recursively modify the permissions of directories and their contents. | + +There are two methods for making rights changes: + +* The **octal** method; +* The **symbolic** method. + +!!! Warning The rights of files and directories are not dissociated. For some operations, it will be necessary to know the rights of the directory containing the file. A write-protected file can be deleted by another user as long as the rights of the directory containing it allow this user to perform this operation. + +#### Principle of the octal method + +Each right has a value. + +![Octal method](images/07-file-systems-011.png) + +``` +[root]# ls -l /tmp/myfile +-rwxrwxrwx 1 root root ... /tmp/myfile +``` + +![Rights 777](images/07-file-systems-012.png) + +``` +[root]# chmod 741 /tmp/myfile +-rwxr----x 1 root root ... /tmp/myfile +``` + +![Rights 741](images/07-file-systems-013.png) + +#### Principle of the symbolic method + +This method can be considered as a "literal" association between a user type, an operator, and rights. + +![Symbolic method](images/07-file-systems-014.png) + +``` +[root]# chmod u+rwx,g+wx,o-r /tmp/myfile +[root]# chmod g=x,o-r /tmp/myfile +[root]# chmod o=r /tmp/myfile +``` + +``` +[root]# ls -l /tmp/myfile +r--r-- 1 root root … /tmp/myfile +``` + +``` +[root]# chmod u+rwx,g+wx,o-r /tmp/myfile +``` + +``` +[root]# ls -l /tmp/myfile +-rwxrwx--- 1 root root … /tmp/myfile +``` + +### Special rights + +In addition to the fundamental rights (`rwx`), there are the particular rights: + +* **set-user-ID** (_SUID]_) +* **set-group-ID** (_SGID]_) +* **sticky-bit** + +As with the fundamental rights, the particular rights each have a value. This value is placed before the `ugo` set of rights. + +![Special rights](images/07-file-systems-015.png) + +!!! Danger `S`, `S` and `T` in capital letters **if the right does not exist**. + +#### The sticky-bit + +One of the peculiarities of rights in Linux is that the right to write to a directory also allows deletion of *all* files, owner or not. + +The _sticky-bit_ set on the directory will only allow users to delete files they own. This is the basic case for the `/tmp` directory. + +The setting of the _sticky-bit_ can be done as follows: + +Octal method: +``` +[root]# chmod 1777 directory +``` + +Symbolic method: +``` +[root]# chmod o+t directory +``` + +Verification: +``` +[root]# ls -l +drwxrwxrwt … directory +``` + +#### SUID and SGID on a command + +These rights allow execution of a command according to the rights set on the command, and not according to the user's rights. + +The command is executed with the identity of the owner (_SUID_) or the group (_SGID_) of the command. + +!!! Note The identity of the user requesting the execution of the order is no longer taken into account. + + This is an additional possibility of access rights assigned to a user when it is necessary for them to have the same rights as the owner of a file or those of the group concerned. + +Indeed, a user may have to run a program (usually a system utility) but not have the necessary access rights. By setting the appropriate rights (**s** at the owner level and/or at the group level), the user of the program has, for the time of its execution, the identity of the owner (or that of the group) of the program. + +Example: + +The file `/usr/bin/passwd` is an executable file (a command) with a _SUID_. + +When the user _bob_ runs it, he will have to access the `/etc/shadow` file, but the permissions on this file do not allow _bob_ to access it. + +Having a _SUID_ this command, `/usr/bin/passwd`, will be executed with the _UID_ of root and the _GID_ of _root_. The latter being the owner of the `/etc/shadow` file, he will have read rights. + +![How the SUID works](images/07-file-systems-016.png) + +The setting of _SUID_ and _SGID_ can be done as below with the command `chmod`: + +Octal method: +``` +[root]# chmod 4777 command1 +[root]# chmod 2777 command2 +``` + +Symbolic method: +``` +[root]# chmod u+s command1 +[root]# chmod g+s command2 +``` + +Verification: +``` +[root]# ls -l +-rwsrwxrwx … command1 +-rwxrwsrwx … command2 +``` + +!!! Warning It is not possible to pass the _SUID_ or _SGID_ to a shell script. The system does not allow it because it is too dangerous for security! + +#### SGID on a file + +In a directory with the _SGID_ right, any file created will inherit the group that owns the directory instead of that of the creating user. + +Example: +``` +[rockstar] $ ls -ld /data/ +drwxrwsr-x 2 root users 4096 26 oct. 19:43 /data +``` + +``` +[rockstar] $ touch /data/test_sgid /tmp/fic_reference +``` + +``` +[rockstar] $ ls -ld /data/test_sgid /tmp/fic_reference +-rw-r--r--. 1 rockstar users 0 26 oct. 19:43 /data/test_sgid <1> +-rw-r--r--. 1 rockstar rockstar 0 26 oct. 19:43 /tmp/fic_ref +``` + +<1> The `test_sgid` file inherits the group owner of its `/data` folder (in this case `users`) whatever the main group of the `rockstar` user is. + +## Default rights and mask + +When a file or directory is created, it already has permissions. + +* For a directory: `rwxr-xr-x` or _755_. +* For a file: `rw-r-r-` or _644_. + +This behavior is defined by the **default mask**. + +The principle is to remove the value defined by the mask at maximum rights without the execution right. + +For a directory : + +![How the SUID works](images/07-file-systems-017.png) + +For a file, the execution rights are removed: + +![Default rights of a file](images/07-file-systems-018.png) + +### `umask` command + +The `umask` command allows you to display and modify the mask. + +``` +umask [option] [mode] +``` + +Example: +``` +$ umask 033 +$ umask +0033 +$ umask -S +u=rwx,g=r,o=r +$ touch umask_033 +$ ls -la umask_033 +-rw-r--r-- 1 rockstar rockstar 0 nov. 4 16:44 umask_033 +$ umask 025 +$ umask -S +u=rwx,g=rx,o=w +$ touch umask_025 +$ ls -la umask_025 +-rw-r---w- 1 rockstar rockstar 0 nov. 4 16:44 umask_025 +``` + +| Option | Description | +| ------ | -------------------------------- | +| `-S` | Symbolic display of file rights. | + +!!! Warning `umask` does not affect existing files. + +!!! Note `umask` modifies the mask until the disconnection. + +To keep the value, you have to modify the following profile files: For all users: + +* `/etc/profile` +* `/etc/bashrc` + +For a particular user: + +* `~/.bashrc` + +!!! Warning `umask -S` displays the file rights (without the execute right) of the files that will be created. So it is not the display of the mask used to subtract the maximum value. + +!!! Tip The `umask` command being a _bash_ command, (a `type umask` returns `umask is a shell primitive`) you have to search `umask` in `man bash`. From bded5f369496282261fb2cbe92ca0fe9bcb2e601 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:05 -0500 Subject: [PATCH 30/37] New translations 04-advanced-commands.md (Chinese Simplified) --- .../admin_guide/04-advanced-commands.zh.md | 356 ++++++++++++++++++ 1 file changed, 356 insertions(+) create mode 100644 docs/books/admin_guide/04-advanced-commands.zh.md diff --git a/docs/books/admin_guide/04-advanced-commands.zh.md b/docs/books/admin_guide/04-advanced-commands.zh.md new file mode 100644 index 0000000000..80914c650b --- /dev/null +++ b/docs/books/admin_guide/04-advanced-commands.zh.md @@ -0,0 +1,356 @@ +--- +title: Advanced Linux Commands +--- + +# Advanced Commands for Linux users + +In this chapter you will learn some advanced commands for Linux. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn: + +:heavy_check_mark: some useful commands not covered in the previous chapter; +:heavy_check_mark: some advanced commands. + +:checkered_flag: **user commands**, **Linux** + +**Knowledge**: :star: +**Complexity**: :star: :star: :star: + +**阅读时间**: 20 分钟 + +**** + +## `uniq` command + +The `uniq` command is a very powerful command, used with the `sort` command, especially for log file analysis. It allows you to sort and display entries by removing duplicates. + +To illustrate how the `uniq` command works, let's use a `firstnames.txt` file containing a list of first names: + +``` +antoine +xavier +steven +patrick +xavier +antoine +antoine +steven +``` + +!!! Note `uniq` requires the input file to be sorted because it only compares consecutive lines. + +Without an argument, the `uniq` command will not display identical lines that follow each other in the `firstnames.txt` file: + +``` +$ sort firstnames.txt | uniq +antoine +patrick +steven +xavier +``` + +To display only the rows that appear only once, use the `-u` option: + +``` +$ sort firstnames.txt | uniq -u +patrick +``` + +Conversely, to display only the lines that appear at least twice in the file, you must use the `-d` option: + +``` +$ sort firstnames.txt | uniq -d +antoine +steven +xavier +``` + +To simply delete lines that appear only once, use the `-D` option: + +``` +$ sort firstnames.txt | uniq -D +antoine +antoine +antoine +steven +steven +xavier +xavier +``` + +Finally, to count the number of occurrences of each line, use the `-c` option: + +``` +$ sort firstnames.txt | uniq -c + 3 antoine + 1 patrick + 2 steven + 2 xavier +``` + +``` +$ sort firstnames.txt | uniq -cd + 3 antoine + 2 steven + 2 xavier +``` + +## `xargs` commands + +The `xargs` command allows the construction and execution of command lines from standard input. + +The `xargs` command reads whitespace or linefeed delimited arguments from standard input, and executes the command (`/bin/echo` by default) one or more times using the initial arguments followed by the arguments read from standard input. + +A first and simplest example would be the following: + +``` +$ xargs +use +of +xargs + +use of xargs +``` + +The `xargs` command waits for an input from the standard **stdin** input. Three lines are entered. The end of the user input is specified to `xargs` by the keystroke sequence CTRL+D. `xargs` then executes the default command `echo` followed by the three arguments corresponding to the user input, namely : + +``` +$ echo "use" "of" "xargs" +use of xargs +``` + +It is possible to specify a command to be run by `xargs`. + +In the following example, `xargs` will run the command `ls -ld` on the set of folders specified in the standard input: + +``` +$ xargs ls -ld +/home +/tmp +/root + +drwxr-xr-x. 9 root root 4096 5 avril 11:10 /home +dr-xr-x---. 2 root root 4096 5 avril 15:52 /root +drwxrwxrwt. 3 root root 4096 6 avril 10:25 /tmp +``` + +In practice, the `xargs` command executed the `ls -ld /home /tmp /root` command. + +What happens if the command to be executed does not accept multiple arguments as is the case with the `find` command? + +``` +$ xargs find /var/log -name +*.old +*.log +find: paths must precede expression: *.log +``` + +The `xargs` command attempted to execute the `find` command with multiple arguments behind the `-name` option, which caused `find` to generate an error: + +``` +$ find /var/log -name "*.old" "*.log" +find: paths must precede expression: *.log +``` + +In this case, the `xargs` command must be forced to execute the `find` command several times (once per line entered as standard input). The `-L` option followed by an **integer** allows you to specify the maximum number of entries to be processed with the command at one time: + +``` +$ xargs -L 1 find /var/log -name +*.old +/var/log/dmesg.old +*.log +/var/log/boot.log +/var/log/anaconda.yum.log +/var/log/anaconda.storage.log +/var/log/anaconda.log +/var/log/yum.log +/var/log/audit/audit.log +/var/log/anaconda.ifcfg.log +/var/log/dracut.log +/var/log/anaconda.program.log + +``` + +If we wanted to be able to specify both arguments on the same line, we would have to use the `-n 1` option: + +``` +$ xargs -n 1 find /var/log -name +*.old *.log +/var/log/dmesg.old +/var/log/boot.log +/var/log/anaconda.yum.log +/var/log/anaconda.storage.log +/var/log/anaconda.log +/var/log/yum.log +/var/log/audit/audit.log +/var/log/anaconda.ifcfg.log +/var/log/dracut.log +/var/log/anaconda.program.log + +``` + +Case study of a backup with a `tar` based on a search: + +``` +$ find /var/log/ -name "*.log" -mtime -1 | xargs tar cvfP /root/log.tar +$ tar tvfP /root/log.tar +-rw-r--r-- root/root 1720 2017-04-05 15:43 /var/log/boot.log +-rw-r--r-- root/root 499270 2017-04-06 11:01 /var/log/audit/audit.log +``` + +The special feature of the `xargs` command is that it places the input argument at the end of the called command. This works very well with the above example since the files passed in will form the list of files to be added to the archive. + +Now, if we take the example of the `cp` command and want to copy a list of files in a directory, this list of files will be added at the end of the command... but what the `cp` command expects at the end of the command is the destination. To do this, we use the `-I` option to put the input arguments somewhere else than at the end of the line. + +``` +$ find /var/log -type f -name "*.log" | xargs -I % cp % /root/backup +``` + +The `-I` option allows you to specify a character (in our example the `%` character) where the input files to `xargs` will be placed. + +## `yum-utils` package + +The `yum-utils` package is a collection of utilities from different authors for `yum`, which make it easier and more powerful to use. + +!!! Note While `yum` has been replaced by `dnf` in Rocky Linux 8, the package name has remained `yum-utils` although it can be installed as `dnf-utils` as well. These are classic YUM utilities implemented as CLI shims on top of DNF to maintain backwards compatibility with `yum-3`. + +Here are some examples of usage: + +* `repoquery` command: + +The `repoquery` command queries the repositories. + +Examples of use: + + * Knowing the dependencies of an uninstalled package: + +``` +repoquery --requires +``` + + * Know the files provided by a non-installed package: + +``` +$ repoquery -l yum-utils +/etc/bash_completion.d +/etc/bash_completion.d/yum-utils.bash +/usr/bin/debuginfo-install +/usr/bin/find-repos-of-install +/usr/bin/needs-restarting +/usr/bin/package-cleanup +/usr/bin/repo-graph +/usr/bin/repo-rss +/usr/bin/repoclosure +/usr/bin/repodiff +/usr/bin/repomanage +/usr/bin/repoquery +/usr/bin/reposync +/usr/bin/repotrack +/usr/bin/show-changed-rco +/usr/bin/show-installed +/usr/bin/verifytree +/usr/bin/yum-builddep +/usr/bin/yum-config-manager +/usr/bin/yum-debug-dump +/usr/bin/yum-debug-restore +/usr/bin/yum-groups-manager +/usr/bin/yumdownloader +… +``` + +* `yumdownloader` command: + +The `yumdownloader` command downloads RPM packages from the repositories. + +!!! Note This command is very useful to quickly build a local repository of a few rpm! + +Example: `yumdownloader` will download the _repoquery_ rpm package and all its dependencies: + +``` +$ yumdownloader --destdir /var/tmp -- resolve repoquery +``` + +| Options | Comments | +| ----------- | --------------------------------------------------------------- | +| -`-destdir` | The downloaded packages will be stored in the specified folder. | +| `--resolve` | Also downloads the package dependencies. | + +## `psmisc` packages + +The `psmisc` package contains utilities for managing system processes: + +* `pstree`: the `pstree` command displays the current processes on the system in a tree-like structure. +* `killall`: the `killall` command sends a kill signal to all processes identified by name. +* `fuser`: the `fuser` command identifies the `PID` of processes that use the specified files or file systems. + +Examples: + +``` +$ pstree +systemd─┬─NetworkManager───2*[{NetworkManager}] + ├─agetty + ├─auditd───{auditd} + ├─crond + ├─dbus-daemon───{dbus-daemon} + ├─firewalld───{firewalld} + ├─lvmetad + ├─master─┬─pickup + │ └─qmgr + ├─polkitd───5*[{polkitd}] + ├─rsyslogd───2*[{rsyslogd}] + ├─sshd───sshd───bash───pstree + ├─systemd-journal + ├─systemd-logind + ├─systemd-udevd + └─tuned───4*[{tuned}] +``` + +``` +# killall httpd +``` + +Kill processes (option `-k`) that access the `/etc/httpd/conf/httpd.conf` file: + +``` +# fuser -k /etc/httpd/conf/httpd.conf +``` + +## `watch` command + +The `watch` command regularly executes a command and displays the result in the terminal in full screen. + +The `-n` option allows you to specify the number of seconds between each execution of the command. + +!!! Note To exit the `watch` command, you must type the keys: CTRL+C to kill the process. + +Examples: + +* Display the end of the `/etc/passwd` file every 5 seconds: + +``` +$ watch -n 5 tail -n 3 /etc/passwd +``` + +Result: + +``` +Every 5,0s: tail -n 3 /etc/passwd rockstar.rockylinux.lan: Thu Jul 1 15:43:59 2021 + +sssd:x:996:993:User for sssd:/:/sbin/nologin +chrony:x:995:992::/var/lib/chrony:/sbin/nologin +sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin +``` + +* Monitoring the number of files in a folder: + +``` +$ watch -n 1 'ls -l | wc -l' +``` + +* Display a clock: + +``` +$ watch -t -n 1 date +``` From cd1fbd19e3c2621533b9e202c1faceb59a32f0c9 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:06 -0500 Subject: [PATCH 31/37] New translations 05-vi.md (French) --- docs/books/admin_guide/05-vi.fr.md | 481 +++++++++++++++++++++++++++++ 1 file changed, 481 insertions(+) create mode 100644 docs/books/admin_guide/05-vi.fr.md diff --git a/docs/books/admin_guide/05-vi.fr.md b/docs/books/admin_guide/05-vi.fr.md new file mode 100644 index 0000000000..d958a5a937 --- /dev/null +++ b/docs/books/admin_guide/05-vi.fr.md @@ -0,0 +1,481 @@ +--- +title: VI Text Editor +--- + +# VI Text Editor + +In this chapter you will learn how to work with the VIsual editor. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: Use the main commands of the VI editor; +:heavy_check_mark: Modify a text with the VI editor. + +:checkered_flag: **user commands**, **linux** + +**Knowledge**: :star: +**Complexity**: :star: :star: + +**Temps de lecture : **20 minutes + +**** + +*Visual* (**VI**) is a very popular text editor under Linux, despite its limited ergonomics. It is indeed an editor entirely in text mode: each action is done with a key on the keyboard or dedicated commands. + +Very powerful, it is above all very practical since it is on the whole minimal for basic applications. It is therefore accessible in case of system failure. Its *universality* (it is present on all Linux distributions and under Unix) makes it a *crucial* tool for the administrator. + +Its functionalities are: + +* Insert, delete, modify text; +* Copy words, lines or blocks of text; +* Search and replace characters. + +## `vi` command + +The `vi` command opens the *VI* text editor. + +``` +vi [-c command] [file] +``` + +Example: + +``` +$ vi /home/rockstar/file +``` + +| Option | Information | +| ------------ | ------------------------------------------------- | +| `-c command` | Execute VI by specifying a command at the opening | + +If the file exists at the location mentioned by the path, it is read by VI which is placed in **commands** mode. + +If the file does not exist, VI opens a blank file and an empty page is displayed on the screen. When the file is saved, it will take the name specified with the command. + +If the command `vi` is executed without specifying a file name, VI opens a blank file and an empty page is displayed on the screen. When the file is saved, VI will ask for a file name. + +The `vim` editor takes the interface and functions of VI with many improvements. + +``` +vim [-c command] [file] +``` + +Among these improvements, the user has syntax highlighting, which is very useful for editing shell scripts or configuration files. + +During a session, VI uses a buffer file in which it records all the changes made by the user. + +!!! Note As long as the user has not saved his work, the original file is not modified. + +At startup, VI is in *commands* mode. + +!!! Tip A line of text is ended by pressing ENTER but if the screen is not wide enough, VI makes automatic line breaks, _wrap_ configuration by default. These line breaks may not be desired, this is the _nowrap_ configuration. + +To exit VI, from the Commands mode, tap : then type: + +* `q` to exit without saving (_quit_); +* `w` to save your work (_write_); +* `wq` (_write quit_) or `x` (_eXit_) to save and exit. + +To force the exit without confirmation, you must add *!* to the previous commands. + +!!! Warning There is no periodic backup, so you must remember to save your work regularly. + +## Operating mode + +In VI, there are 3 working modes: + +* The *command* mode; +* The *insertion* mode; +* The *ex* mode. + +The philosophy of VI is to alternate between the *command* mode and the *insertion* mode. + +The third mode, *ex*, is a footer command mode from an old text editor. + +### The Command Mode + +This is the default mode when VI starts up. To access it from any of the other modes, simply press the ESC key. + +All entries are interpreted as commands and the corresponding actions are executed. These are essentially commands for editing text (copy, paste, undo, ...). + +The commands are not displayed on the screen. + +### The Insert mode + +This is the text modification mode. To access it from the *command* mode, you have to press special keys that will perform an action in addition to changing the mode. + +The text is not entered directly into the file but into a buffer zone in the memory. The changes are only effective when the file is saved. + +### The Ex mode + +This is the file modification mode. To access it, you must first switch to *command* mode, then enter the *ex* command frequently starting with the character `:`. + +The command is validated by pressing the ENTER key. + +## Moving the cursor + +In *command* mode, there are several ways to move the cursor. + +The mouse is not active in a text environment but is in a graphic environment, it is possible to move it character by character, but shortcuts exist to go faster. + +VI remains in *command* mode after moving the cursor. + +The cursor is placed under the desired character. + +### From a character + +* Move one or `n` characters to the left: + +, n, h or nh + +* Move one or `n` characters to the right: + +, n, l or nl + +* Move one or `n` characters up: + +, n, k or nk + +* Move one or `n` characters down: + +, n, j or nj + +* Move to the end of the line: + +$ or END + +* Move to the beginning of the line: + +0 or POS1 + +### From the first character of a word + +Words are made up of letters or numbers. Punctuation characters and apostrophes separate words. + +If the cursor is in the middle of a word w moves to the next word, b moves to the beginning of the word. + +If the line is finished, VI goes automatically to the next line. + +* Move one or `n` words to the right: + +w or nw + +* Move one or `n` words to the left: + +b or nb + +### From any location on a line + +* Move to last line of text: + +G + +* Move to line `n`: + +nG + +* Move to the first line of the screen: + +H + +* Move to the middle line of the screen: + +M + +* Move to the last line of the screen: + +L + +## Inserting text + +In *command* mode, there are several ways to insert text. + +VI switches to *insert* mode after entering one of these keys. + +!!! Note VI switches to *insertion* mode. So you will have to press the ESC key to return to *command* mode. + +### In relation to a character + +* Inserting text before a character: + +i (_insert_) + +* Inserting text after a character: + +a (_append_) + +### In relation to a line + +* Inserting text at the beginning of a line: + +I + +* Inserting text at the end of a line: + +A + +### In relation to the text + +* Inserting text before a line: + +O + +* Inserting text after a line: + +o + +## Characters, words and lines + +VI allows text editing by managing: + +* characters, +* words, +* lines. + +In each case it is possible to : + +* delete, +* replace, +* copy, +* cut, +* paste. + +These operations are done in *command* mode. + +### Characters + +* Delete one or `n` characters: + +x or nx + +* Replace a character with another: + +rcharacter + +* Replace more than one character with others: + +RcharactersESC + +!!! Note The R command switches to *replace* mode, which is a kind of *insert* mode. + +### Words + +* Delete (cut) one or `n` words: + +dw or ndw + +* Copy one or `n` words: + +yw or nyw + +* Paste a word once or `n` times after the cursor: + +p or np + +* Paste a word once or `n` times before the cursor: + +P or nP + +* Replace one word: + +cw_word_ESC + +!!! Tip It is necessary to position the cursor under the first character of the word to cut (or copy) otherwise VI will cut (or copy) only the part of the word between the cursor and the end. To delete a word is to cut it. If it is not pasted afterwards, the buffer is emptied and the word is deleted. + +### Lines + +* Delete (cut) one or `n` lines: + +dd or ndd + +* Copy one or `n` lines: + +yy or nyy + +* Paste what has been copied or deleted once or `n` times after the current line: + +p or np + +* Paste what has been copied or deleted once or `n` times before the current line: + +P or nP + +* Delete (cut) from the beginning of the line to the cursor: + +d0 + +* Delete (cut) from the cursor to the end of the line: + +d$ + +* Copy from the beginning of the line to the cursor: + +y0 + +* Copy from the cursor to the end of the line: + +y$ + +* Delete (cut) the text from the current line: + +dL or dG + +* Copy the text from the current line: + +yL or yG + +### Cancel an action + +* Undo the last action: + +u + +* Undo the actions on the current line: + +U + +### Cancel cancellation + +* Cancel a cancellation + +Ctrl+R + +## EX commands + +The *Ex* mode allows you to act on the file (saving, layout, options, ...). It is also in *Ex* mode where search and replace commands are entered. The commands are displayed at the bottom of the page and must be validated with the ENTER key. + +To switch to *Ex* mode, from *command* mode, type :. + +### Numbering the lines + +* Show/hide numbering: + +`:set nu` and the longer `:set number` + +`:set nonu` and the longer `:set nonumber` + +### Search for a string + +* Search for a string from the cursor: + +`/string` + +* Search for a string before the cursor: + +`?string` + +* Go to the next occurrence found: + +n + +* Go to the previous occurrence found: + +N + +There are wildcards to facilitate the search in VI. + +* `[]` : Searches for a range of characters or a single character whose possible values are specified. + +Example: + +`/[Ww]ord` : search _word_ and _Word_ + +`/[1-9]word` : search _1word_, _2word_ … _`x`word_ where `x` is a number + +* `^` : Search for a string starting the line. + +Example: + +`/^Word` + +* `$` : Search for a string ending the line. + +Example: + +`/Word$` + +* `.` : Search for a word with an unknown letter. + +Example: + +`/W.rd` : search _Word_, _Ward_ … + +* `*` : Search for one or more characters, whatever they are. + +Example: + +`/W*d` + +### Replace a string + +From the 1st to the last line of the text, replace the searched string by the specified string: + +`:1,$ s/search/replace` + +**Note:** You can also use `:0,$s/search/replace` to specify starting at the absolute beginning of the file. + +From line `n` to line `m`, replace the searched string with the specified string: + +`:n,m s/search/replace` + +By default, only the first occurrence found of each line is replaced. To force the replacement of each occurrence, you have to add `/g` at the end of the command: + +`:n,m s/search/replace/g` + +Browse an entire file to replace the searched string with the specified string: + +`:% s/search/replace` + +### File operations + +* Save the file: + +`:w` + +* Save under another name: + +`:w file` + +* Save from line `n` to line `m` in another file: + +`:n,m w file` + +* Reload the last record of the file: + +`e!` + +* Paste the content of another file after the cursor: + +`:r file` + +* Quit editing a file without saving: + +`:q` + +* Quit editing a file that has been modified during the session but not saved: + +`:q!` + +* Exit the file and save: + +`:wq` or `:x` + +## Other functions + +It is possible to execute VI by specifying the options to be loaded for the session. To do this, you must use the `-c` option: + +``` +$ vi -c "set nu" /home/rockstar/file +``` + +It is also possible to enter the *Ex* commands in a file named `.exrc` put in the user's login directory. At each VI or VIM startup, the commands will be read and applied. + +### `vimtutor` command + +There is a tutorial for learning how to use VI. It is accessible with the command `vimtutor`. + +``` +$ vimtutor +``` From 83f2d84edb86e80af06985a5689c6b487fc692ab Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:07 -0500 Subject: [PATCH 32/37] New translations 05-vi.md (Italian) --- docs/books/admin_guide/05-vi.it.md | 36 +++++++++++++++--------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/books/admin_guide/05-vi.it.md b/docs/books/admin_guide/05-vi.it.md index 3d021b787b..57bb663530 100644 --- a/docs/books/admin_guide/05-vi.it.md +++ b/docs/books/admin_guide/05-vi.it.md @@ -6,21 +6,21 @@ title: Editor di Testo VI In questo capitolo imparerai come lavorare con il VIsual editor. ---- +**** **Obiettivi** : In questo capitolo, i futuri amministratori Linux impareranno come: :heavy_check_mark: Utilizzare i comandi principali dell'Editor VI; -:heavy_check_mark: Modificare un testo con l'editor VI. +:heavy_check_mark: Modificare un testo con l'editor VI. :checkered_flag: **comandi utente**, **linux** **Conoscenza**: :star: -**Complessità**: :star: :star: +**Complessità**: :star: :star: **Tempo di lettura**: 20 minuti ---- +**** *Visual* (**VI**) è un editor di testo molto popolare sotto Linux, nonostante la sua limitata ergonomia. È infatti un editor interamente in modalità testo: ogni azione viene eseguita con una chiave sulla tastiera o sui comandi dedicati. @@ -36,13 +36,13 @@ Le sue funzionalità sono: Il comando `vi` Apre l'editor di testo *VI*. -```bash +``` vi [-c command] [file] ``` Esempio: -```bash +``` $ vi /home/rockstar/file ``` @@ -58,7 +58,7 @@ Se il comando. `vi` viene eseguito senza specificare un nome di file, VI apre un L'editor `vim` prende l'interfaccia e le funzioni di VI con molti miglioramenti. -```bash +``` vim [-c command] [file] ``` @@ -67,12 +67,12 @@ Tra questi miglioramenti, l'utente ha l'evidenziazione della sintassi, che è mo Durante una sessione, VI utilizza un file buffer in cui registra tutte le modifiche apportate dall'utente. !!! Note "Nota" - Finché l'utente non ha salvato il suo lavoro, il file originale non viene modificato. +Finché l'utente non ha salvato il suo lavoro, il file originale non viene modificato. All'avvio, VI è in modalità *comando*. !!! Tip "Suggerimento" - Una riga di testo è terminata premendo ENTER Ma se lo schermo non è abbastanza largo, VI interrompe automaticamente le linee, (_wrap_) configurazione per impostazione predefinita. Queste interruzioni di linea potrebbero non essere desiderate, questa è la configurazione _nowrap_. +Una riga di testo è terminata premendo ENTER Ma se lo schermo non è abbastanza largo, VI interrompe automaticamente le linee, (_wrap_) configurazione per impostazione predefinita. Queste interruzioni di linea potrebbero non essere desiderate, questa è la configurazione _nowrap_. Per uscire da VI, dalla modalità Comando, premi : quindi digita: @@ -83,7 +83,7 @@ Per uscire da VI, dalla modalità Comando, premi : quindi digita: Per forzare l'uscita senza conferma, devi aggiungere *!* ai precedenti comandi. !!! Warning "Avvertimento" - Non esiste un backup periodico, quindi devi ricordarti di salvare il tuo lavoro regolarmente. +Non esiste un backup periodico, quindi devi ricordarti di salvare il tuo lavoro regolarmente. ## Modalità operativa @@ -158,6 +158,7 @@ Il cursore è posizionato sotto il carattere desiderato. Le parole sono costituite da lettere o numeri. Caratteri di punteggiatura e apostrofi separarano le parole. Se il cursore è nel mezzo di una parola w muove alla parola successiva, b si posiziona all'inizio della parola. + Se la linea è finita, VI va automaticamente alla riga successiva. * Muoversi di una o `n` parole a destra: @@ -197,7 +198,7 @@ In modalità *comando*, ci sono diversi modi per inserire il testo. VI passa alla modalità *inserimento* dopo l'inserimento di uno di questi chiavi. !!! Note "Nota" - VI passa alla modalità *inserimento*. Quindi dovrai premere il tasto ESC per ritornare alla modalità *comando*. +VI passa alla modalità *inserimento*. Quindi dovrai premere il tasto ESC per ritornare alla modalità *comando*. ### In relazione a un carattere @@ -251,7 +252,7 @@ Queste operazioni sono fatte in modalità *comando*. * Elimina uno o `n` caratteri: -x o nx +x or nx * Sostituisce un carattere con un altro: @@ -262,7 +263,7 @@ Queste operazioni sono fatte in modalità *comando*. RcaratteriESC !!! Note "Nota" - Il comando R passa alla modalità *sostituire*, che è un tipo di modalità *inserimento*. +Il comando R passa alla modalità *sostituire*, che è un tipo di modalità *inserimento*. ### Parole @@ -287,8 +288,7 @@ Queste operazioni sono fatte in modalità *comando*. cw_word_ESC !!! Tip "Suggerimento" - È necessario posizionare il cursore sotto il primo carattere della parola da tagliare (o copiare) altrimenti VI taglierà (o copierà) solo la parte della parola tra il cursore e la fine della parola. -Per eliminare una parola è sufficiente tagliarla. Se non è incollata dopo, il buffer viene svuotato e la parola è cancellata. +È necessario posizionare il cursore sotto il primo carattere della parola da tagliare (o copiare) altrimenti VI taglierà (o copierà) solo la parte della parola tra il cursore e la fine della parola. Per eliminare una parola è sufficiente tagliarla. Se non è incollata dopo, il buffer viene svuotato e la parola è cancellata. ### Linee @@ -406,7 +406,7 @@ Esempio: Esempio: -`/W.rd` : ricerca _Word_, _Ward_ … +`/W.rd` : ricerca _Word_, _Ward_… * `*` : Cerca uno o più caratteri, qualunque cosa siano. @@ -472,7 +472,7 @@ Sfoglia un intero file per sostituire la stringa cercata con la stringa specific È possibile eseguire VI specificando le opzioni da caricare per la sessione. Per fare questo, devi usare l'opzione `-c`: -```bash +``` $ vi -c "set nu" /home/rockstar/file ``` @@ -482,6 +482,6 @@ $ vi -c "set nu" /home/rockstar/file C'è un tutorial per imparare come usare VI. Ed è accessibile con il comando `vimtutor`. -```bash +``` $ vimtutor ``` From 66dfeef130a6a49ab267f7468185b3274f94cbd0 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:07 -0500 Subject: [PATCH 33/37] New translations 05-vi.md (Chinese Simplified) --- docs/books/admin_guide/05-vi.zh.md | 481 +++++++++++++++++++++++++++++ 1 file changed, 481 insertions(+) create mode 100644 docs/books/admin_guide/05-vi.zh.md diff --git a/docs/books/admin_guide/05-vi.zh.md b/docs/books/admin_guide/05-vi.zh.md new file mode 100644 index 0000000000..12cb5b5cb3 --- /dev/null +++ b/docs/books/admin_guide/05-vi.zh.md @@ -0,0 +1,481 @@ +--- +title: VI Text Editor +--- + +# VI Text Editor + +In this chapter you will learn how to work with the VIsual editor. + +**** + +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: Use the main commands of the VI editor; +:heavy_check_mark: Modify a text with the VI editor. + +:checkered_flag: **user commands**, **linux** + +**Knowledge**: :star: +**Complexity**: :star: :star: + +**阅读时间**: 20 分钟 + +**** + +*Visual* (**VI**) is a very popular text editor under Linux, despite its limited ergonomics. It is indeed an editor entirely in text mode: each action is done with a key on the keyboard or dedicated commands. + +Very powerful, it is above all very practical since it is on the whole minimal for basic applications. It is therefore accessible in case of system failure. Its *universality* (it is present on all Linux distributions and under Unix) makes it a *crucial* tool for the administrator. + +Its functionalities are: + +* Insert, delete, modify text; +* Copy words, lines or blocks of text; +* Search and replace characters. + +## `vi` command + +The `vi` command opens the *VI* text editor. + +``` +vi [-c command] [file] +``` + +Example: + +``` +$ vi /home/rockstar/file +``` + +| Option | Information | +| ------------ | ------------------------------------------------- | +| `-c command` | Execute VI by specifying a command at the opening | + +If the file exists at the location mentioned by the path, it is read by VI which is placed in **commands** mode. + +If the file does not exist, VI opens a blank file and an empty page is displayed on the screen. When the file is saved, it will take the name specified with the command. + +If the command `vi` is executed without specifying a file name, VI opens a blank file and an empty page is displayed on the screen. When the file is saved, VI will ask for a file name. + +The `vim` editor takes the interface and functions of VI with many improvements. + +``` +vim [-c command] [file] +``` + +Among these improvements, the user has syntax highlighting, which is very useful for editing shell scripts or configuration files. + +During a session, VI uses a buffer file in which it records all the changes made by the user. + +!!! Note As long as the user has not saved his work, the original file is not modified. + +At startup, VI is in *commands* mode. + +!!! Tip A line of text is ended by pressing ENTER but if the screen is not wide enough, VI makes automatic line breaks, _wrap_ configuration by default. These line breaks may not be desired, this is the _nowrap_ configuration. + +To exit VI, from the Commands mode, tap : then type: + +* `q` to exit without saving (_quit_); +* `w` to save your work (_write_); +* `wq` (_write quit_) or `x` (_eXit_) to save and exit. + +To force the exit without confirmation, you must add *!* to the previous commands. + +!!! Warning There is no periodic backup, so you must remember to save your work regularly. + +## Operating mode + +In VI, there are 3 working modes: + +* The *command* mode; +* The *insertion* mode; +* The *ex* mode. + +The philosophy of VI is to alternate between the *command* mode and the *insertion* mode. + +The third mode, *ex*, is a footer command mode from an old text editor. + +### The Command Mode + +This is the default mode when VI starts up. To access it from any of the other modes, simply press the ESC key. + +All entries are interpreted as commands and the corresponding actions are executed. These are essentially commands for editing text (copy, paste, undo, ...). + +The commands are not displayed on the screen. + +### The Insert mode + +This is the text modification mode. To access it from the *command* mode, you have to press special keys that will perform an action in addition to changing the mode. + +The text is not entered directly into the file but into a buffer zone in the memory. The changes are only effective when the file is saved. + +### The Ex mode + +This is the file modification mode. To access it, you must first switch to *command* mode, then enter the *ex* command frequently starting with the character `:`. + +The command is validated by pressing the ENTER key. + +## Moving the cursor + +In *command* mode, there are several ways to move the cursor. + +The mouse is not active in a text environment but is in a graphic environment, it is possible to move it character by character, but shortcuts exist to go faster. + +VI remains in *command* mode after moving the cursor. + +The cursor is placed under the desired character. + +### From a character + +* Move one or `n` characters to the left: + +, n, h or nh + +* Move one or `n` characters to the right: + +, n, l or nl + +* Move one or `n` characters up: + +, n, k or nk + +* Move one or `n` characters down: + +, n, j or nj + +* Move to the end of the line: + +$ or END + +* Move to the beginning of the line: + +0 or POS1 + +### From the first character of a word + +Words are made up of letters or numbers. Punctuation characters and apostrophes separate words. + +If the cursor is in the middle of a word w moves to the next word, b moves to the beginning of the word. + +If the line is finished, VI goes automatically to the next line. + +* Move one or `n` words to the right: + +w or nw + +* Move one or `n` words to the left: + +b or nb + +### From any location on a line + +* Move to last line of text: + +G + +* Move to line `n`: + +nG + +* Move to the first line of the screen: + +H + +* Move to the middle line of the screen: + +M + +* Move to the last line of the screen: + +L + +## Inserting text + +In *command* mode, there are several ways to insert text. + +VI switches to *insert* mode after entering one of these keys. + +!!! Note VI switches to *insertion* mode. So you will have to press the ESC key to return to *command* mode. + +### In relation to a character + +* Inserting text before a character: + +i (_insert_) + +* Inserting text after a character: + +a (_append_) + +### In relation to a line + +* Inserting text at the beginning of a line: + +I + +* Inserting text at the end of a line: + +A + +### In relation to the text + +* Inserting text before a line: + +O + +* Inserting text after a line: + +o + +## Characters, words and lines + +VI allows text editing by managing: + +* characters, +* words, +* lines. + +In each case it is possible to : + +* delete, +* replace, +* copy, +* cut, +* paste. + +These operations are done in *command* mode. + +### Characters + +* Delete one or `n` characters: + +x or nx + +* Replace a character with another: + +rcharacter + +* Replace more than one character with others: + +RcharactersESC + +!!! Note The R command switches to *replace* mode, which is a kind of *insert* mode. + +### Words + +* Delete (cut) one or `n` words: + +dw or ndw + +* Copy one or `n` words: + +yw or nyw + +* Paste a word once or `n` times after the cursor: + +p or np + +* Paste a word once or `n` times before the cursor: + +P or nP + +* Replace one word: + +cw_word_ESC + +!!! Tip It is necessary to position the cursor under the first character of the word to cut (or copy) otherwise VI will cut (or copy) only the part of the word between the cursor and the end. To delete a word is to cut it. If it is not pasted afterwards, the buffer is emptied and the word is deleted. + +### Lines + +* Delete (cut) one or `n` lines: + +dd or ndd + +* Copy one or `n` lines: + +yy or nyy + +* Paste what has been copied or deleted once or `n` times after the current line: + +p or np + +* Paste what has been copied or deleted once or `n` times before the current line: + +P or nP + +* Delete (cut) from the beginning of the line to the cursor: + +d0 + +* Delete (cut) from the cursor to the end of the line: + +d$ + +* Copy from the beginning of the line to the cursor: + +y0 + +* Copy from the cursor to the end of the line: + +y$ + +* Delete (cut) the text from the current line: + +dL or dG + +* Copy the text from the current line: + +yL or yG + +### Cancel an action + +* Undo the last action: + +u + +* Undo the actions on the current line: + +U + +### Cancel cancellation + +* Cancel a cancellation + +Ctrl+R + +## EX commands + +The *Ex* mode allows you to act on the file (saving, layout, options, ...). It is also in *Ex* mode where search and replace commands are entered. The commands are displayed at the bottom of the page and must be validated with the ENTER key. + +To switch to *Ex* mode, from *command* mode, type :. + +### Numbering the lines + +* Show/hide numbering: + +`:set nu` and the longer `:set number` + +`:set nonu` and the longer `:set nonumber` + +### Search for a string + +* Search for a string from the cursor: + +`/string` + +* Search for a string before the cursor: + +`?string` + +* Go to the next occurrence found: + +n + +* Go to the previous occurrence found: + +N + +There are wildcards to facilitate the search in VI. + +* `[]` : Searches for a range of characters or a single character whose possible values are specified. + +Example: + +`/[Ww]ord` : search _word_ and _Word_ + +`/[1-9]word` : search _1word_, _2word_ … _`x`word_ where `x` is a number + +* `^` : Search for a string starting the line. + +Example: + +`/^Word` + +* `$` : Search for a string ending the line. + +Example: + +`/Word$` + +* `.` : Search for a word with an unknown letter. + +Example: + +`/W.rd` : search _Word_, _Ward_ … + +* `*` : Search for one or more characters, whatever they are. + +Example: + +`/W*d` + +### Replace a string + +From the 1st to the last line of the text, replace the searched string by the specified string: + +`:1,$ s/search/replace` + +**Note:** You can also use `:0,$s/search/replace` to specify starting at the absolute beginning of the file. + +From line `n` to line `m`, replace the searched string with the specified string: + +`:n,m s/search/replace` + +By default, only the first occurrence found of each line is replaced. To force the replacement of each occurrence, you have to add `/g` at the end of the command: + +`:n,m s/search/replace/g` + +Browse an entire file to replace the searched string with the specified string: + +`:% s/search/replace` + +### File operations + +* Save the file: + +`:w` + +* Save under another name: + +`:w file` + +* Save from line `n` to line `m` in another file: + +`:n,m w file` + +* Reload the last record of the file: + +`e!` + +* Paste the content of another file after the cursor: + +`:r file` + +* Quit editing a file without saving: + +`:q` + +* Quit editing a file that has been modified during the session but not saved: + +`:q!` + +* Exit the file and save: + +`:wq` or `:x` + +## Other functions + +It is possible to execute VI by specifying the options to be loaded for the session. To do this, you must use the `-c` option: + +``` +$ vi -c "set nu" /home/rockstar/file +``` + +It is also possible to enter the *Ex* commands in a file named `.exrc` put in the user's login directory. At each VI or VIM startup, the commands will be read and applied. + +### `vimtutor` command + +There is a tutorial for learning how to use VI. It is accessible with the command `vimtutor`. + +``` +$ vimtutor +``` From 8ff60939d512f79c0857ddec18ce00a2866bf562 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:08 -0500 Subject: [PATCH 34/37] New translations 06-users.md (French) --- docs/books/admin_guide/06-users.fr.md | 758 ++++++++++++++++++++++++++ 1 file changed, 758 insertions(+) create mode 100644 docs/books/admin_guide/06-users.fr.md diff --git a/docs/books/admin_guide/06-users.fr.md b/docs/books/admin_guide/06-users.fr.md new file mode 100644 index 0000000000..3b0085ccbf --- /dev/null +++ b/docs/books/admin_guide/06-users.fr.md @@ -0,0 +1,758 @@ +--- +title: User Management +--- + +# User Management + +In this chapter you will learn how to manage user. + +**** +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: add, delete or modify a **group** ; +:heavy_check_mark: add, delete or modify a **user** ; +:heavy_check_mark: know the syntax of the files associated with the management of groups and users ; +:heavy_check_mark: change the *owner* or the *group owner* of a file; +:heavy_check_mark: *secure* user accounts; +:heavy_check_mark: change identity. + +:checkered_flag: **users** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**Reading time**: 30 minutes +**** + +## General + +Each user is a member of at least one group: **this is their main group**. + +Several users can be part of the same group. + +Users can belong to other groups. These users are *invited* to these **secondary groups**. + +!!! Note Each user has a primary group and can be invited into one or more secondary groups. + +Groups and users are managed by their unique numerical identifiers `GID` and `UID`. + +Account and group declaration files are located in `/etc`. +* `UID`: _User IDentifier_. Unique user ID. +* `GID`: _Group IDentifier_. Unique group identifier. + +!!! Danger You should always use the administration commands instead of manually editing the files. + +## Group management + +Modified files, added lines: + +* `/etc/group` +* `/etc/gshadow` + +### `groupadd` command + +The `groupadd` command adds a group to the system. +``` +groupadd [-f] [-g GID] group +``` + +Example: + +``` +$ sudo groupadd -g 1012 GroupeB +``` + +| Option | Description | +| -------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `-g GID` | `GID` of the group to create. | +| `-f` | The system chooses a `GID` if the one specified by the `-g` option already exists. | +| `-r` | Creates a system group with a `GID` between `SYS_GID_MIN` and `SYS_GID_MAX`. These two variables are defined in `/etc/login.defs`. | + +Group naming rules: + +* No accents or special characters; +* Different from the name of an existing user or system files. + +!!! Note Under **Debian**, the administrator should use, except in scripts intended to be portable to all Linux distributions, the `addgroup` and `delgroup` commands as specified in the `man`: + + ``` + $ man addgroup + DESCRIPTION + adduser and addgroup add users and groups to the system according to command line options and configuration information + in /etc/adduser.conf. They are friendlier front ends to the low level tools like useradd, groupadd and usermod programs, + by default choosing Debian policy conformant UID and GID values, creating a home directory with skeletal configuration, + running a custom script, and other features. + ``` + +### Command `groupmod` + +The `groupmod` command allows you to modify an existing group on the system. + +``` +groupmod [-g GID] [-n nom] group +``` + +Example: + +``` +$ sudo groupmod -g 1016 GroupP +$ sudo groupmod -n GroupC GroupB +``` + +| Option | Description | +| --------- | --------------------------------- | +| `-g GID` | New `GID` of the group to modify. | +| `-n name` | New name. | + +It is possible to change the name of a group, its `GID` or both simultaneously. + +After modification, the files belonging to the group have an unknown `GID`. They must be reassigned the new `GID`. + +``` +$ sudo find / -gid 1002 -exec chgrp 1016 {} \; +``` + +### `groupdel` command + +The `groupdel` command is used to delete an existing group on the system. + +``` +groupdel group +``` + +Example: + +``` +$ sudo groupdel GroupC +``` + +!!! Tip To be deleted, a group must no longer contain users. + +Deleting the last user of an eponymous group will cause the system to delete the group. + +!!! Tip Each group has a unique `GID`. A group can be duplicated. By convention, the `GID` of system groups range from 0 (`root`) to 999. + +!!! Tip Since a user is necessarily part of a group, it is best to create the groups before adding the users. Therefore, a group may not have any members. + +### `/etc/group` file + +This file contains the group information (separated by `:`). + +``` +$ sudo tail -1 /etc/group +GroupP:x:516:patrick + (1) (2)(3) (4) +``` + +* 1: Name of the group. +* 2: Password (`x` if defined in `/etc/gshadow`). +* 3: GID. +* 4: Guest members (separated by commas, does not contain core members). + +!!! Note Each line in the `/etc/group` file corresponds to a group. Users whose group is their main group are not listed at this level. This membership information is in fact already provided by the `/etc/passwd` file... + +### `/etc/gshadow` file + +This file contains the security information about the groups (separated by `:`). + +``` +$ sudo grep GroupA /etc/gshadow +GroupA:$6$2,9,v...SBn160:alain:rockstar + (1) (2) (3) (4) +``` + +* 1: Name of the group. +* 2: Encrypted password. +* 3: Administrator of the group. +* 4: Guest members (separated by commas, does not contain core members). + +!!! Warning For each line in the `/etc/group` file there must be a corresponding line in the `/etc/gshadow` file. + +A `!` in the password indicates that it is locked. Thus no user can use the password to access the group (since group members do not need it). + +## User management + +### Definition + +A user is defined as follows in the `/etc/passwd` file: + +* 1: Login; +* 2: Password; +* 3: UID; +* 4: GID of the main group; +* 5: Comments; +* 6: Home directory; +* 7: Shell (`/bin/bash`, `/bin/nologin`, ...). + +There are three types of users: + +* **root**: the system administrator ; +* **system users**: Used by the system to manage application access rights ; +* **regular user**: Other account to log in to the system. + +Modified files, added lines: + +* `/etc/passwd` +* `/etc/shadow` + +### `useradd` command + +The `useradd` command is used to add a user. + +``` +useradd [-u UID] [-g GID] [-d directory] [-s shell] login +``` + +Example: + +``` +$ sudo useradd -u 1000 -g 1013 -d /home/GroupC/carine carine +``` + +| Option | Description | +| -------------- | ------------------------------------------------------------------- | +| `-u UID` | `UID` of the user to create. | +| `-g GID` | `GID` of the main group. | +| `-d directory` | Home directory. | +| `-s shell` | Shell. | +| `-c` | Add a comment. | +| `-U` | Adds the user to a group with the same name created simultaneously. | +| `-M` | Does not create the connection directory. | + +At creation, the account has no password and is locked. + +A password must be assigned to unlock the account. + +Account naming rules: + +* No accents, capital letters or special characters; +* Different from the name of an existing group or system file; +* Set the options `-u`, `-g`, `-d` and `-s` at creation. + +!!! Warning The home directory tree must be created except for the last directory. + +The last directory is created by the `useradd` command, which takes the opportunity to copy the files from `/etc/skel` into it. + +**A user can belong to several groups in addition to their main group.** + +For secondary groups, the `-G` option must be used. + +Example: + +``` +$ sudo useradd -u 1000 -g GroupA -G GroupP,GroupC albert +``` + +!!! Note Under **Debian**, you will have to specify the `-m` option to force the creation of the login directory or set the `CREATE_HOME` variable in the `/etc/login.defs` file. In all cases, the administrator should use the `adduser` and `deluser` commands as specified in the `man`, except in scripts intended to be portable to all Linux distributions: + + ``` + $ man useradd + DESCRIPTION + **useradd** is a low level utility for adding users. On Debian, administrators should usually use **adduser(8)** + instead. + ``` + +#### Default value for user creation. + +Modification of the file `/etc/default/useradd`. + +``` +useradd -D [-b directory] [-g group] [-s shell] +``` + +Example: + +``` +$ sudo useradd -D -g 1000 -b /home -s /bin/bash +``` + +| Option | Description | +| -------------- | ----------------------------------------------------------------------------- | +| `-D` | Sets the default values for user creation. | +| `-b directory` | Sets the default login directory. | +| `-g group` | Sets the default group. | +| `-s shell` | Sets the default shell. | +| `-f` | The number of days after the password expires before the account is disabled. | +| `-e` | The date the account will be disabled. | + +### `usermod` command + +The `usermod` command allows to modify a user. + +``` +usermod [-u UID] [-g GID] [-d directory] [-m] login +``` + +Example: + +``` +$ sudo usermod -u 1044 carine +``` + +Options identical to the `useradd` command. + +| Option | Description | +| --------------- | ---------------------------------------------------------------------------------------------- | +| `-m` | Associated with the `-d` option, moves the contents of the old login directory to the new one. | +| `-l login` | New name. | +| `-e AAAA-MM-JJ` | Account expiration date. | +| `-L` | Locks the account. | +| `-U` | Unlocks the account. | +| `-a` | Prevents the user from being deleted from a subgroup when added to another subgroup. | +| `-G` | Specifies multiple subgroups when adding. | + +With the `usermod` command, locking an account results in the addition of `!` before the password in the `/etc/shadow` file. + +!!! Tip To be modified, a user must be disconnected and have no running processes. + +After changing the identifier, the files belonging to the user have an unknown `UID`. It must be reassigned the new `UID`. + +``` +$ sudo find / -uid 1000 -exec chown 1044: {} \; +``` + +Where `1000` is the old `UID` and `1044` is the new one. + +It is possible to invite a user into one or more subgroups with the options *-a* and *-G*. + +Example: + +``` +$ sudo usermod -aG GroupP,GroupC albert +``` + +The `usermod` command acts as a modification and not as an addition. + +For a user invited to a group by this command and already positioned as a guest in other secondary groups, it will be necessary to indicate in the group management command all the groups to which he belongs otherwise he will disappear from them. + +The *-a* option changes this behavior. + +Examples: + +* Invite `albert` in the group `GroupP`. + +``` +$ sudo usermod -G GroupP albert +``` + +* Invites `albert` into the `GroupG` group, but removes him from the `GroupP` guest list. + +``` +$ sudo usermod -G GroupG albert +``` + +* So either : + +``` +$ sudo usermod -G GroupP,GroupG albert +``` + +* Or : + +``` +$ sudo usermod -aG GroupG albert +``` + +### `userdel` command + +The `userdel` command allows you to delete a user's account. + +``` +$ sudo userdel -r carine +``` + +| Option | Description | +| ------ | --------------------------------------------------------- | +| `-r` | Deletes the connection directory and the contained files. | + +!!! Tip To be deleted, a user must be logged out and have no running processes. + +`userdel` removes the user's line from the `/etc/passwd` and `/etc/gshadow` files. + +### `/etc/passwd` file + +This file contains user information (separated by `:`). + +``` +$ sudo head -1 /etc/passwd +root:x:0:0:root:/root:/bin/bash +(1)(2)(3)(4)(5) (6) (7) +``` + +* 1: Login. +* 2: Password (`x` if defined in `/etc/shadow`). +* 3: UID. +* 4: GID of the main group. +* 5: Comment. +* 6: Home directory. +* 7: Shell. + +### `/etc/shadow` file + +This file contains the users' security information (separated by `:`). +``` +$ sudo tail -1 /etc/shadow +root:$6$...:15399:0:99999:7::: + (1) (2) (3) (4) (5) (6)(7,8,9) +``` + +* 1: Login. +* 2: Encrypted password. +* 3: Date of last change. +* 4: Minimum lifetime of the password. +* 5: Maximum lifetime of the password. +* 6: Number of days before warning. +* 7: Time to deactivate account after expiration. +* 8: Account expiration time. +* 9: Reserved for future use. + +!!! Danger For each line in the `/etc/passwd` file there must be a corresponding line in the `/etc/shadow` file. + +## File owners + +!!! Danger All files necessarily belong to one user and one group. + +The main group of the user creating the file is, by default, the group that owns the file. + +### Modification commands + +#### `chown` command + +The `chown` command allows you to change the owners of a file. +``` +chown [-R] [-v] login[:group] file +``` + +Examples: +``` +$ sudo chown root myfile +$ sudo chown albert:GroupA myfile +``` + +| Option | Description | +| ------ | ----------------------------------------------------- | +| `-R` | Changes the owners of the directory and its contents. | +| `-v` | Displays the executed changes. | + +To change only the owner user: + +``` +$ sudo chown albert file +``` + +To modify only the owner group: + +``` +$ sudo chown :GroupA file +``` + +Changing the user and owner group: + +``` +$ sudo chown albert:GroupA file +``` + +In the following example the group assigned will be the main group of the specified user. + +``` +$ sudo chown albert: file +``` + +### `chgrp` command + +The `chgrp` command allows you to change the owner group of a file. + +``` +chgrp [-R] [-v] group file +``` + +Example: +``` +$ sudo chgrp group1 file +``` + +| Option | Description | +| ------ | ------------------------------------------------------------------------ | +| `-R` | Modifies the owner groups of the directory and its contents (recursion). | +| `-v` | Displays the executed changes. | + +!!! Note It is possible to apply to a file an owner and an owner group by taking as reference those of another file: + +``` +chown [options] --reference=RRFILE FILE +``` + +For example: + +``` +chown --reference=/etc/groups /etc/passwd +``` + +## Guest management + +### `gpasswd` command + +The command `gpasswd` allows to manage a group. + +``` +gpasswd [-a login] [-A login] [-d login] [-M login] group +``` + +Examples: + +``` +$ sudo gpasswd -A alain GroupA +[alain]$ gpasswd -a patrick GroupA +``` + +| Option | Description | +| ---------- | ------------------------------------ | +| `-a login` | Adds the user to the group. | +| `-A login` | Sets the group administrator. | +| `-d login` | Remove the user from the group. | +| `-M login` | Defines the complete list of guests. | + +The command `gpasswd -M` acts as a modification, not an addition. +``` +# gpasswd GroupeA +New Password : +Re-enter new password : +``` + +### `id` command + +The `id` command displays the group names of a user. +``` +id login +``` +Example: +``` +$ sudo id alain +uid=1000(alain) gid=1000(GroupA) groupes=1000(GroupA),1016(GroupP) +``` + +### `newgrp` command + +The `newgrp` command allows you to temporarily use a secondary group for file creation. +``` +newgrp [secondarygroups] +``` +Example: +``` +[alain]$ newgrp GroupB +``` + +!!! Note After using this command, the files will be created with the `GID` of its subgroup. + +The command `newgrp` without parameters reassigns the main group. + +## Securing + +### `passwd` command + +The `passwd` command is used to manage a password. +``` +passwd [-d] [-l] [-S] [-u] [login] +``` +Examples: +``` +$ sudo passwd -l albert +$ sudo passwd -n 60 -x 90 -w 80 -i 10 patrick +``` + +| Option | Description | +| --------- | ---------------------------------------------------- | +| `-d` | Removes the password. | +| `-l` | Locks the account. | +| `-S` | Displays the account status. | +| `-u` | Unlocks the account. | +| `-e` | Expires the password. | +| `-n days` | Minimum password lifetime. | +| `-x days` | Maximum password lifetime. | +| `-w days` | Warning time before expiration. | +| `-i days` | Delay before deactivation when the password expires. | + +With the `passwd` command, locking an account is accomplished by adding `!!` before the password in the `/etc/shadow` file. + +Using the command `usermod -U` command only removes one of the `!`. So the account remains locked. + +Example: + +* Alain changes his password: + +``` +[alain]$ passwd +``` + +* root changes Alain's password + +``` +$ sudo passwd alain +``` + +!!! Note The `passwd` command is available to users to change their password (the old password is requested). The administrator can change the passwords of all users without restriction. + +They will have to comply with the security restrictions. + +When managing user accounts by shell script, it may be useful to set a default password after creating the user. + +This can be done by passing the password to the `passwd` command. + +Example: +``` +$ sudo echo "azerty,1" | passwd --stdin philippe +``` +!!! Warning The password is entered in clear text, `passwd` takes care of encrypting it. + +### `chage` command + +The `chage` command is used to manage the account strategy. +``` +chage [-d date] [-E date] [-I days] [-l] [-m days] [-M days] [-W days] [login] +``` +Example: +``` +$ sudo chage -m 60 -M 90 -W 80 -I 10 alain +``` + +| Option | Description | +| --------------- | -------------------------------------------- | +| `-I days` | Delay before deactivation, password expired. | +| `-l` | Displays the policy details. | +| `-m days` | Minimum lifetime of the password. | +| `-M days` | Maximum lifetime of the password. | +| `-d AAAA-MM-JJ` | Last password change. | +| `-E AAAA-MM-JJ` | Account expiration date. | +| `-W days` | Warning time before expiration. | + +The `chage` command also offers an interactive mode. + +The `-d` option forces the password to be changed at login. + +Examples: +``` +$ sudo chage philippe +$ sudo chage -d 0 philippe +``` + +!!! Note If no user is specified, the order will concern the user who enters it. + +![User account management with chage](images/chage-timeline.png) + +## Advanced management + +Configuration files: +* `/etc/default/useradd` +* `/etc/login.defs` +* `/etc/skel` + +!!! Note Editing the `/etc/default/useradd` file is done with the `useradd` command. + + The other files are to be modified with a text editor. + +### `/etc/default/useradd` file + +This file contains the default data settings. + +!!! Tip When creating a user, if the options are not specified, the system uses the default values defined in `/etc/default/useradd`. + +This file is modified by the command `useradd -D` (`useradd -D` entered without any other option displays the contents of the `/etc/default/useradd` file). + +| Value | Comment | +| ------------------- | ------------------------------------------------------------------------- | +| `GROUP` | Default group. | +| `HOME` | Path where the login directory for the user's name will be created. | +| `INACTIVE` | Number of days after the password expires before the account is disabled. | +| `EXPIRE` | Account expiration date. | +| `SHELL` | Command interpreter. | +| `SKEL` | Skeleton directory of the login directory. | +| `CREATE_MAIL_SPOOL` | Mailbox creation in `/var/spool/mail`. | + +!!! Warning Without the `-g` option, the `useradd` command creates a group of the user's name name and places it there. + +In order for the `useradd` command to retrieve the value of the `GROUP` field from the `/etc/default/useradd` file, you must specify the `-N` option. + +Example: +``` +$ sudo useradd -u 501 -N GroupeA +``` + +### `/etc/login.defs` file + +This file contains many default parameters useful for creating or modifying users. This information is grouped by paragraph according to their use: + +* Mailboxes; +* Passwords ; +* UID and GID ; +* Umask ; +* Connections; +* Terminals. + +### `/etc/skel` directory + +When a user is created, their home directory and environment files are created. + +These files are automatically copied from the `/etc/skel` directory. + +* `.bash_logout` +* `.bash_profile` +* `.bashrc` + +All files and directories placed in this directory will be copied to the user tree when they are created. + +## Identity change + +### `su` command + +The `su` command allows you to change the identity of the connected user. + +``` +su [-] [-c command] [login] +``` + +Examples: + +``` +$ sudo su - alain +[albert]$ su -c "passwd alain" +``` + +| Option | Description | +| ------------ | ----------------------------------------------- | +| `-` | Loads the user's complete environment. | +| `-c` command | Executes the command under the user's identity. | + +If the login is not specified, it will be `root`. + +Standard users will have to type the password for the new identity. + +!!! Tip There are successive 'layers' created (a stack of `bash` environments). To switch from one user to another, you must first type the `exit` command to take back your identity and then the `su` command to take another identity. + +#### Profile loading + +`root` endorses the identity of the user `alain` with `su`: + +``` +... +/home/GroupA/alain/.bashrc +/etc/bashrc +... +``` + +`root` assumes the identity of the user `alain` with `su -`: + +``` +... +/home/GroupA/alain/.bash_profile +/home/GroupA/alain/.bashrc +/etc/bashrc +... +``` + +A user can temporarily (for another command or an entire session) assume the identity of another account. + +If no user is specified, the command will be for `root` (`su -`). + +It is necessary to know the password of the user whose identity is being endorsed unless it is `root` that is executing the command. + +An administrator can thus work on a standard user account and use the rights of the `root` account only occasionally. From a54fb6df87554668b97108021246491a8ada08b7 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:09 -0500 Subject: [PATCH 35/37] New translations 06-users.md (Italian) --- docs/books/admin_guide/06-users.it.md | 230 ++++++++++++-------------- 1 file changed, 102 insertions(+), 128 deletions(-) diff --git a/docs/books/admin_guide/06-users.it.md b/docs/books/admin_guide/06-users.it.md index f753c4e42d..1c9ece7f6a 100644 --- a/docs/books/admin_guide/06-users.it.md +++ b/docs/books/admin_guide/06-users.it.md @@ -6,8 +6,7 @@ title: Gestione utenti In questo capitolo imparerai come gestire l'utente. ---- - +**** **Obiettivi** : In questo capitolo, futuri amministratori Linux impareranno come: :heavy_check_mark: aggiungere, eliminare o modificare un **gruppo**; @@ -23,8 +22,7 @@ In questo capitolo imparerai come gestire l'utente. **Complessità**: :star: :star: **Tempo di lettura**: 30 minuti - ---- +**** ## Generale @@ -35,17 +33,16 @@ Diversi utenti possono far parte dello stesso gruppo. Gli utenti possono appartenere ad altri gruppi. Questi utenti sono *invitati* a questi **gruppi secondari**. !!! Note "Nota" - Ogni utente ha un gruppo primario e può essere invitato in uno o più gruppi secondari. +Ogni utente ha un gruppo primario e può essere invitato in uno o più gruppi secondari. I gruppi e gli utenti sono gestiti dai loro identificatori numerici unici `GID` e `UID`. I file di dichiarazione dell'account e del gruppo si trovano in `/etc`. - * `UID`: _User IDentifier_. ID utente unico.. * `GID`: _Group IDentifier_. Identificatore di gruppo unico.. !!! Danger "Pericolo" - È necessario utilizzare sempre i comandi di amministrazione invece di modificare manualmente i file. +È necessario utilizzare sempre i comandi di amministrazione invece di modificare manualmente i file. ## Gestione del gruppo @@ -57,14 +54,13 @@ File modificati, linee aggiunte: ### comando `groupadd` Il comando `groupadd` aggiunge un gruppo al sistema. - -```bash +``` groupadd [-f] [-g GID] group ``` Esempio: -```bash +``` $ sudo groupadd -g 1012 GroupeB ``` @@ -79,15 +75,16 @@ Regole di denominazione del gruppo: * Nessun accento o caratteri speciali; * Diverso dal nome di un utente o file di sistema esistenti. -!!! Note "Nota" - Sotto **Debian**, l'amministratore dovrebbe usare, tranne per gli script destinati ad essere portabili su tutte le distribuzioni Linux, il comando `addgroup` e `delgroup` come specificato nel `man`: +; Nota Sotto **Debian**, l'amministratore dovrebbe usare, tranne che negli script destinati ad essere portatili per tutte le distribuzioni Linux, i comandi `addgroup` e `delgroup` come specificato nell' `man`: - ```bash + ``` $ man addgroup DESCRIPTION adduser and addgroup add users and groups to the system according to command line options and configuration information in /etc/adduser.conf. They are friendlier front ends to the low level tools like useradd, groupadd and usermod programs, by default choosing Debian policy conformant UID and GID values, creating a home directory with skeletal configuration, + running a custom script, and other features. They are friendlier front ends to the low level tools like useradd, groupadd and usermod programs, + by default choosing Debian policy conformant UID and GID values, creating a home directory with skeletal configuration, running a custom script, and other features. ``` @@ -95,13 +92,13 @@ Regole di denominazione del gruppo: Il comando `groupmod` consente di modificare un gruppo esistente sul sistema. -```bash +``` groupmod [-g GID] [-n nom] group ``` Esempio: -```bash +``` $ sudo groupmod -g 1016 GroupP $ sudo groupmod -n GroupC GroupB ``` @@ -115,7 +112,7 @@ $ sudo groupmod -n GroupC GroupB Dopo la modifica, i file appartenenti al gruppo hanno un `GID` sconosciuto. Devono essere riassegnati al nuovo `GID`. -```bash +``` $ sudo find / -gid 1002 -exec chgrp 1016 {} \; ``` @@ -123,32 +120,32 @@ $ sudo find / -gid 1002 -exec chgrp 1016 {} \; Il comando `groupdel` è usato per eliminare un gruppo esistente sul sistema. -```bash +``` groupdel group ``` Esempio: -```bash +``` $ sudo groupdel GroupC ``` !!! Tip "Suggerimento" - Per essere cancellato, un gruppo non deve più contenere utenti. +Per essere cancellato, un gruppo non deve più contenere utenti. L'eliminazione dell'ultimo utente di un gruppo omonimo causerà l'eliminazione del gruppo stesso dal sistema. !!! Tip "Suggerimento" - Ogni gruppo ha un unico `GID`. Un gruppo può essere duplicato. Per convenzione, il `GID` dei gruppi di sistema vanno da 0 (`root`) a 999. +Ogni gruppo ha un unico `GID`. Un gruppo può essere duplicato. Per convenzione, il `GID` dei gruppi di sistema vanno da 0 (`root`) a 999. !!! Tip "Suggerimento" - Dal momento che un utente è necessariamente parte di un gruppo, È meglio creare i gruppi prima di aggiungere gli utenti. Pertanto, un gruppo inizialmente potrebbe non avere membri. +Dal momento che un utente è necessariamente parte di un gruppo, È meglio creare i gruppi prima di aggiungere gli utenti. Pertanto, un gruppo inizialmente potrebbe non avere membri. ### file `/etc/group` Questo file contiene le informazioni del Gruppo (divisi da `:`). -```bash +``` $ sudo tail -1 /etc/group GroupP:x:516:patrick (1) (2)(3) (4) @@ -160,13 +157,13 @@ GroupP:x:516:patrick * 4: Membri ospiti (separati da virgole, non contiene membri di base). !!! Note "Nota" - Ogni linea nel file `/etc/group` corrisponde a un gruppo. Gli utenti il cui gruppo è il loro gruppo principale non è elencato a questo livello. Questa informazione è infatti già fornita dal file `/etc/passwd` ... +Ogni linea nel file `/etc/group` corrisponde a un gruppo. Gli utenti il cui gruppo è il loro gruppo principale non è elencato a questo livello. Questa informazione è infatti già fornita dal file `/etc/passwd` ... ### file `/etc/gshadow` Questo file contiene le informazioni di sicurezza sui gruppi (divisi da `:`). -```bash +``` $ sudo grep GroupA /etc/gshadow GroupA:$6$2,9,v...SBn160:alain:rockstar (1) (2) (3) (4) @@ -178,10 +175,9 @@ GroupA:$6$2,9,v...SBn160:alain:rockstar * 4: Membri ospiti (separati da virgole, non contiene membri di base). !!! Warning "Avvertimento" - Per ogni linea nel file `/etc/group` ci deve essere una linea corrispondente nel file `/etc/gshadow`. +Per ogni linea nel file `/etc/group` ci deve essere una linea corrispondente nel file `/etc/gshadow`. -Un `!` nella password indica che la password è bloccata. -Quindi nessun utente può utilizzare la password per accedere al gruppo (dal momento che i membri del gruppo non ne hanno bisogno). +Un `!` nella password indica che la password è bloccata. Quindi nessun utente può utilizzare la password per accedere al gruppo (dal momento che i membri del gruppo non ne hanno bisogno). ## Gestione utenti @@ -199,7 +195,7 @@ Un utente è definito come segue nel file `/etc/passwd`: Ci sono tre tipi di utenti: -* **root**: L'amministratore di sistema. ; +* **root**: L'amministratore di sistema ; * **utenti di sistema**: Utilizzato dal sistema per gestire i diritti di accesso alle applicazioni ; * **utente normale**: Altro account per accedere al sistema. @@ -212,13 +208,13 @@ File modificati, linee aggiunte: Il comando `useradd` è usato per aggiungere un utente. -```bash +``` useradd [-u UID] [-g GID] [-d directory] [-s shell] login ``` Esempio: -```bash +``` $ sudo useradd -u 1000 -g 1013 -d /home/GroupC/carine carine ``` @@ -243,7 +239,7 @@ Regole di denominazione dell'account: * Imposta le opzioni `-u`, `-g`, `-d` e `-s` alla creazione. !!! Warning "Avvertimento" - L'albero della directory home deve essere già creato tranne per l'ultima directory. +L'albero della directory home deve essere già creato tranne per l'ultima directory. L'ultima directory è creata dal comando `useradd`, che coglie l'occasione per copiare i file da `/etc/skel` dentro di essa. @@ -253,14 +249,14 @@ Per gruppi secondari, deve essere usata l'opzione `-G`. Esempio: -```bash +``` $ sudo useradd -u 1000 -g GroupA -G GroupP,GroupC albert ``` !!! Note "Nota" - In **Debian**, dovrai specificare l'opzione `-m` per forzare la creazione della directory di accesso o impostare la variabile `CREATE_HOME` nel file `/etc/login.defs`. In tutti i casi, l'amministratore dovrebbe usare i comandi `adduser` e `deluser` come specificato nelle pagine `man`, tranne per gli script destinati ad essere portabili su tutte le distribuzioni Linux: +In **Debian**, dovrai specificare l'opzione `-m` per forzare la creazione della directory di accesso o impostare la variabile `CREATE_HOME` nel file `/etc/login.defs`. In tutti i casi, l'amministratore dovrebbe usare i comandi `adduser` e `deluser` come specificato nelle pagine `man`, tranne per gli script destinati ad essere portabili su tutte le distribuzioni Linux: - ```bash + ``` $ man useradd DESCRIPTION **useradd** is a low level utility for adding users. On Debian, administrators should usually use **adduser(8)** @@ -271,13 +267,13 @@ $ sudo useradd -u 1000 -g GroupA -G GroupP,GroupC albert Modifica del file `/etc/default/useradd`. -```bash +``` useradd -D [-b directory] [-g group] [-s shell] ``` Esempio: -```bash +``` $ sudo useradd -D -g 1000 -b /home -s /bin/bash ``` @@ -294,19 +290,19 @@ $ sudo useradd -D -g 1000 -b /home -s /bin/bash Il comando `usermod` permette di modificare un utente. -```bash +``` usermod [-u UID] [-g GID] [-d directory] [-m] login ``` Esempio: -```bash +``` $ sudo usermod -u 1044 carine ``` Opzioni identiche al comando `useradd`. -| Option | Description | +| Opzione | Descrizione | | --------------- | ------------------------------------------------------------------------------------------------------- | | `-m` | Associato all'opzione`-d`, sposta il contenuto della vecchia directory di accesso a quello nuova. | | `-l login` | Nuovo nome. | @@ -319,11 +315,11 @@ Opzioni identiche al comando `useradd`. Con il comando `usermod`, bloccare un account di fatto significa inserire un `!` prima della password nel file `/etc/shadow`. !!! Tip "Suggerimento" - Per essere modificato, un utente deve essere disconnesso e non avere processi in esecuzione. +Per essere modificato, un utente deve essere disconnesso e non avere processi in esecuzione. Dopo aver cambiato l'identificatore, i file appartenenti all'utente hanno un `UID` sconosciuto . Il nuovo `UID` deve essere riassegnato. -```bash +``` $ sudo find / -uid 1000 -exec chown 1044: {} \; ``` @@ -333,7 +329,7 @@ Dove `1000` è il vecchio `UID` e `1044` il nuovo. Esempio: -```bash +``` $ sudo usermod -aG GroupP,GroupC albert ``` @@ -347,25 +343,25 @@ Esempi: * Invitare `albert` nel gruppo `GroupP`. -```bash +``` $ sudo usermod -G GroupP albert ``` * Invita `albert` nel gruppo `GroupG`, ma lo rimuove dal gruppo elenco degli ospiti `GroupP` . -```bash +``` $ sudo usermod -G GroupG albert ``` * Quindi entrambi : -```bash +``` $ sudo usermod -G GroupP,GroupG albert ``` * O : -```bash +``` $ sudo usermod -aG GroupG albert ``` @@ -373,16 +369,16 @@ $ sudo usermod -aG GroupG albert Il comando `userdel` ti consente di eliminare l'account di un utente. -```bash +``` $ sudo userdel -r carine ``` -| Option | Description | -| ------ | ------------------------------------------------------- | -| `-r` | Elimina la directory di connessione e i file contenuti. | +| Opzione | Descrizione | +| ------- | ------------------------------------------------------- | +| `-r` | Elimina la directory di connessione e i file contenuti. | !!! Tip "Suggerimento" - Per essere cancellato, un utente deve essere disconnesso e non avere processi in esecuzione. +Per essere cancellato, un utente deve essere disconnesso e non avere processi in esecuzione. `userdel` rimuove la linea dell'utente dal file `/etc/passwd` e da `/etc/gshadow`. @@ -390,7 +386,7 @@ $ sudo userdel -r carine Questo file contiene le informazioni utente (divise da `:`). -```bash +``` $ sudo head -1 /etc/passwd root:x:0:0:root:/root:/bin/bash (1)(2)(3)(4)(5) (6) (7) @@ -407,8 +403,7 @@ root:x:0:0:root:/root:/bin/bash ### file `/etc/shadow` Questo file contiene le informazioni sulla sicurezza degli utenti (divisi da `:`). - -```bash +``` $ sudo tail -1 /etc/shadow root:$6$...:15399:0:99999:7::: (1) (2) (3) (4) (5) (6)(7,8,9) @@ -425,12 +420,12 @@ root:$6$...:15399:0:99999:7::: * 9: Riservato per un uso futuro. !!! Danger "Pericolo" - Per ogni linea nel file `/etc/passwd` ci deve essere una linea corrispondente nel file `/etc/shadow`. +Per ogni linea nel file `/etc/passwd` ci deve essere una linea corrispondente nel file `/etc/shadow`. ## Proprietari dei file !!! Danger "Pericolo" - Tutti i file appartengono necessariamente a un utente e un gruppo. +Tutti i file appartengono necessariamente a un utente e un gruppo. Il gruppo principale dell'utente che crea il file è, per impostazione predefinita, il gruppo che possiede il file. @@ -439,44 +434,42 @@ Il gruppo principale dell'utente che crea il file è, per impostazione predefini #### comando `chown` Il comando `chown` ti consente di modificare i proprietari di un file. - -```bash +``` chown [-R] [-v] login[:group] file ``` Esempi: - -```bash +``` $ sudo chown root myfile $ sudo chown albert:GroupA myfile ``` -| Option | Description | -| ------ | ---------------------------------------------------------- | -| `-R` | Cambia i proprietari della directory e dei suoi contenuti. | -| `-v` | Visualizza le modifiche eseguite. | +| Opzione | Descrizione | +| ------- | ---------------------------------------------------------- | +| `-R` | Cambia i proprietari della directory e dei suoi contenuti. | +| `-v` | Visualizza le modifiche eseguite. | Per cambiare solo l'utente proprietario: -```bash +``` $ sudo chown albert file ``` Per cambiare solo il gruppo proprietario: -```bash +``` $ sudo chown :GroupA file ``` Per cambiare il gruppo proprietario e l'utente proprietario: -```bash +``` $ sudo chown albert:GroupA file ``` Nell'esempio seguente il gruppo assegnato sarà il gruppo principale dell'utente specificato. -```bash +``` $ sudo chown albert: file ``` @@ -484,13 +477,12 @@ $ sudo chown albert: file Il comando `chgrp` ti consente di modificare il gruppo proprietario di un file. -```bash +``` chgrp [-R] [-v] group file ``` Esempio: - -```bash +``` $ sudo chgrp group1 file ``` @@ -500,15 +492,15 @@ $ sudo chgrp group1 file | `-v` | Visualizza le modifiche eseguite. | !!! Note "Nota" - È possibile applicare a un file un proprietario e un gruppo proprietario prendendo come riferimento quelli di un altro file: +È possibile applicare a un file un proprietario e un gruppo proprietario prendendo come riferimento quelli di un altro file: -```bash +``` chown [options] --reference=RRFILE FILE ``` Per esempio: -```bash +``` chown --reference=/etc/groups /etc/passwd ``` @@ -518,13 +510,13 @@ chown --reference=/etc/groups /etc/passwd Il comando `gpasswd` permette di gestire un gruppo. -```bash +``` gpasswd [-a login] [-A login] [-d login] [-M login] group ``` -Examples: +Esempi: -```bash +``` $ sudo gpasswd -A alain GroupA [alain]$ gpasswd -a patrick GroupA ``` @@ -537,8 +529,7 @@ $ sudo gpasswd -A alain GroupA | `-M login` | Definisce l'elenco completo degli ospiti. | Il comando `gpasswd -M` agisce come una modifica, non come un'aggiunta. - -```bash +``` # gpasswd GroupeA New Password : Re-enter new password : @@ -547,14 +538,11 @@ Re-enter new password : ### comando `id` Il comando `id` visualizza i nomi del gruppo di un utente. - -```bash +``` id login ``` - Esempio: - -```bash +``` $ sudo id alain uid=1000(alain) gid=1000(GroupA) groupes=1000(GroupA),1016(GroupP) ``` @@ -562,19 +550,16 @@ uid=1000(alain) gid=1000(GroupA) groupes=1000(GroupA),1016(GroupP) ### comando `newgrp` Il comando `newgrp` consente di utilizzare temporaneamente un gruppo secondario per la creazione di file. - -```bash +``` newgrp [secondarygroups] ``` - Esempio: - -```bash +``` [alain]$ newgrp GroupB ``` !!! Note "Nota" - Dopo aver usato questo comando, i file verranno creati con il `GID` del suo sottogruppo. +Dopo aver usato questo comando, i file verranno creati con il `GID` del suo sottogruppo. Il comando `newgrp` senza parametri riassegna al gruppo principale. @@ -583,19 +568,16 @@ Il comando `newgrp` senza parametri riassegna al gruppo principale. ### commando `passwd` Il comando `passwd` è usato per gestire una password. - -```bash +``` passwd [-d] [-l] [-S] [-u] [login] ``` - Esempi: - -```bash +``` $ sudo passwd -l albert $ sudo passwd -n 60 -x 90 -w 80 -i 10 patrick ``` -| Option | Description | +| Opzione | Descrizione | | --------- | ------------------------------------------------------------ | | `-d` | Rimuove la password. | | `-l` | Blocca l'account. | @@ -615,18 +597,18 @@ Esempio: * Alain cambia la sua password: -```bash +``` [alain]$ passwd ``` * root cambia la password di Alain -```bash +``` $ sudo passwd alain ``` !!! Note "Nota" - Il comando `passwd` è disponibile per gli utenti per cambiare la propria password (la vecchia password è richiesta). L'amministratore può modificare le password di tutti gli utenti senza restrizioni. +Il comando `passwd` è disponibile per gli utenti per cambiare la propria password (la vecchia password è richiesta). L'amministratore può modificare le password di tutti gli utenti senza restrizioni. Dovranno rispettare le restrizioni di sicurezza. @@ -635,25 +617,20 @@ Quando gestisci gli account utente da una shell script, potrebbe essere utile im Questo può essere fatto passando la password al comando `passwd`. Esempio: - -```bash +``` $ sudo echo "azerty,1" | passwd --stdin philippe ``` - !!! Warning "Avvertimento" - La password è inserita in chiaro, `passwd` si prende cura di crittografarla. +La password è inserita in chiaro, `passwd` si prende cura di crittografarla. ### comando `chage` Il comando `chage` è usato per gestire la strategia dell'account. - -```bash +``` chage [-d date] [-E date] [-I days] [-l] [-m days] [-M days] [-W days] [login] ``` - Esempio: - -```bash +``` $ sudo chage -m 60 -M 90 -W 80 -I 10 alain ``` @@ -672,36 +649,34 @@ Il comando `chage` offre anche una modalità interattiva. L'opzione `-d` costringe alla modifica della password al login. Esempi: - -```bash +``` $ sudo chage philippe $ sudo chage -d 0 philippe ``` !!! Note "Nota" - Se nessun utente è specificato, l'ordine riguarderà l'utente che entra. +Se nessun utente è specificato, l'ordine riguarderà l'utente che entra. ![User account management with chage](images/chage-timeline.png) ## Gestione avanzata File di configurazione.: - * `/etc/default/useradd` * `/etc/login.defs` * `/etc/skel` !!! Note "Nota" - La modifica del file `/etc/default/useradd` è fatta con il comando `useradd`. +La modifica del file `/etc/default/useradd` è fatta con il comando `useradd`. -Gli altri file devono essere modificati con un editor di testo. + Gli altri file devono essere modificati con un editor di testo. ### file `/etc/default/useradd` Questo file contiene le impostazioni dei dati predefinite. !!! Tip "Suggerimento" - Quando si crea un utente, se le opzioni non sono specificate, il sistema utilizza i valori predefiniti definiti in `/etc/default/useradd`. +Quando si crea un utente, se le opzioni non sono specificate, il sistema utilizza i valori predefiniti definiti in `/etc/default/useradd`. Questo file è modificato dal comando `useradd -D` (`useradd -D` inserito senza nessun'altra opzione visualizza il contenuto del file `/etc/default/useradd`). @@ -716,13 +691,12 @@ Questo file è modificato dal comando `useradd -D` (`useradd -D` inserito senza | `CREATE_MAIL_SPOOL` | Creazione della Mailbox in`/var/spool/mail`. | !!! Warning "Avvertimento" - Senza l'opzione `-g`, il comando `useradd` crea un gruppo dal nome dell'utente e il gruppo diventa il gruppo principale dell'utente. +Senza l'opzione `-g`, il comando `useradd` crea un gruppo dal nome dell'utente e il gruppo diventa il gruppo principale dell'utente. In ordine al comando `useradd` per poter recuperare il valore del campo `GROUP` dal file `/etc/default/useradd`, devi specificare l'opzione `-N`. Esempio: - -```bash +``` $ sudo useradd -u 501 -N GroupeA ``` @@ -755,34 +729,34 @@ Tutti i file e le directory inseriti in questa directory verranno copiati nell'a Il comando `su` consente di modificare l'identità dell'utente connesso. -```bash +``` su [-] [-c command] [login] ``` Esempi: -```bash +``` $ sudo su - alain [albert]$ su -c "passwd alain" ``` -| Opzione | Descrizione | -| ------------ | ------------------------------------------------------------ | -| `-` | Carica l'ambiente completo dell'utente. | -| `-c` comando | Esegue il comando sotto l'identità dell'utente specificato. | +| Opzione | Descrizione | +| ------------ | ----------------------------------------------------------- | +| `-` | Carica l'ambiente completo dell'utente. | +| `-c` comando | Esegue il comando sotto l'identità dell'utente specificato. | Se il login non è specificato, sarà `root`. Gli utenti standard dovranno digitare la password per la nuova identità. !!! Tip "Suggerimento" - Ci sono "strati" creati in successione (una pila di ambienti `bash`). Per passare da un utente all'altro, devi prima digitare il comando `exit` per riprendere la tua identità e poi il comando `su` per prendere un'altra identità. +Ci sono "strati" creati in successione (una pila di ambienti `bash`). Per passare da un utente all'altro, devi prima digitare il comando `exit` per riprendere la tua identità e poi il comando `su` per prendere un'altra identità. #### Caricamento del profilo `root` approva l'identità dell'utente `alain` insieme a `su`: -```bash +``` ... /home/GroupA/alain/.bashrc /etc/bashrc @@ -791,7 +765,7 @@ Gli utenti standard dovranno digitare la password per la nuova identità. `root` assume l'identità dell'utente `alain` with `su -`: -```bash +``` ... /home/GroupA/alain/.bash_profile /home/GroupA/alain/.bashrc @@ -803,6 +777,6 @@ Un utente può temporaneamente (per un altro comando o per un'intera sessione) a Se nessun utente è specificato, il comando sarà per `root` (`su -`). -È necessario conoscere la password dell'utente la cui identità viene approvata a meno che non sia "root` che esegue il comando. +È necessario conoscere la password dell'utente la cui identità viene approvata a meno che non sia `root` che esegue il comando. Un amministratore può quindi lavorare su un account utente standard e utilizzare i diritti dell'account `root` solo occasionalmente. From 9a8720927797d38d4b89e9054b9f4a79ffe292c5 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:09 -0500 Subject: [PATCH 36/37] New translations 06-users.md (Chinese Simplified) --- docs/books/admin_guide/06-users.zh.md | 758 ++++++++++++++++++++++++++ 1 file changed, 758 insertions(+) create mode 100644 docs/books/admin_guide/06-users.zh.md diff --git a/docs/books/admin_guide/06-users.zh.md b/docs/books/admin_guide/06-users.zh.md new file mode 100644 index 0000000000..3b0085ccbf --- /dev/null +++ b/docs/books/admin_guide/06-users.zh.md @@ -0,0 +1,758 @@ +--- +title: User Management +--- + +# User Management + +In this chapter you will learn how to manage user. + +**** +**Objectives** : In this chapter, future Linux administrators will learn how to: + +:heavy_check_mark: add, delete or modify a **group** ; +:heavy_check_mark: add, delete or modify a **user** ; +:heavy_check_mark: know the syntax of the files associated with the management of groups and users ; +:heavy_check_mark: change the *owner* or the *group owner* of a file; +:heavy_check_mark: *secure* user accounts; +:heavy_check_mark: change identity. + +:checkered_flag: **users** + +**Knowledge**: :star: :star: +**Complexity**: :star: :star: + +**Reading time**: 30 minutes +**** + +## General + +Each user is a member of at least one group: **this is their main group**. + +Several users can be part of the same group. + +Users can belong to other groups. These users are *invited* to these **secondary groups**. + +!!! Note Each user has a primary group and can be invited into one or more secondary groups. + +Groups and users are managed by their unique numerical identifiers `GID` and `UID`. + +Account and group declaration files are located in `/etc`. +* `UID`: _User IDentifier_. Unique user ID. +* `GID`: _Group IDentifier_. Unique group identifier. + +!!! Danger You should always use the administration commands instead of manually editing the files. + +## Group management + +Modified files, added lines: + +* `/etc/group` +* `/etc/gshadow` + +### `groupadd` command + +The `groupadd` command adds a group to the system. +``` +groupadd [-f] [-g GID] group +``` + +Example: + +``` +$ sudo groupadd -g 1012 GroupeB +``` + +| Option | Description | +| -------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `-g GID` | `GID` of the group to create. | +| `-f` | The system chooses a `GID` if the one specified by the `-g` option already exists. | +| `-r` | Creates a system group with a `GID` between `SYS_GID_MIN` and `SYS_GID_MAX`. These two variables are defined in `/etc/login.defs`. | + +Group naming rules: + +* No accents or special characters; +* Different from the name of an existing user or system files. + +!!! Note Under **Debian**, the administrator should use, except in scripts intended to be portable to all Linux distributions, the `addgroup` and `delgroup` commands as specified in the `man`: + + ``` + $ man addgroup + DESCRIPTION + adduser and addgroup add users and groups to the system according to command line options and configuration information + in /etc/adduser.conf. They are friendlier front ends to the low level tools like useradd, groupadd and usermod programs, + by default choosing Debian policy conformant UID and GID values, creating a home directory with skeletal configuration, + running a custom script, and other features. + ``` + +### Command `groupmod` + +The `groupmod` command allows you to modify an existing group on the system. + +``` +groupmod [-g GID] [-n nom] group +``` + +Example: + +``` +$ sudo groupmod -g 1016 GroupP +$ sudo groupmod -n GroupC GroupB +``` + +| Option | Description | +| --------- | --------------------------------- | +| `-g GID` | New `GID` of the group to modify. | +| `-n name` | New name. | + +It is possible to change the name of a group, its `GID` or both simultaneously. + +After modification, the files belonging to the group have an unknown `GID`. They must be reassigned the new `GID`. + +``` +$ sudo find / -gid 1002 -exec chgrp 1016 {} \; +``` + +### `groupdel` command + +The `groupdel` command is used to delete an existing group on the system. + +``` +groupdel group +``` + +Example: + +``` +$ sudo groupdel GroupC +``` + +!!! Tip To be deleted, a group must no longer contain users. + +Deleting the last user of an eponymous group will cause the system to delete the group. + +!!! Tip Each group has a unique `GID`. A group can be duplicated. By convention, the `GID` of system groups range from 0 (`root`) to 999. + +!!! Tip Since a user is necessarily part of a group, it is best to create the groups before adding the users. Therefore, a group may not have any members. + +### `/etc/group` file + +This file contains the group information (separated by `:`). + +``` +$ sudo tail -1 /etc/group +GroupP:x:516:patrick + (1) (2)(3) (4) +``` + +* 1: Name of the group. +* 2: Password (`x` if defined in `/etc/gshadow`). +* 3: GID. +* 4: Guest members (separated by commas, does not contain core members). + +!!! Note Each line in the `/etc/group` file corresponds to a group. Users whose group is their main group are not listed at this level. This membership information is in fact already provided by the `/etc/passwd` file... + +### `/etc/gshadow` file + +This file contains the security information about the groups (separated by `:`). + +``` +$ sudo grep GroupA /etc/gshadow +GroupA:$6$2,9,v...SBn160:alain:rockstar + (1) (2) (3) (4) +``` + +* 1: Name of the group. +* 2: Encrypted password. +* 3: Administrator of the group. +* 4: Guest members (separated by commas, does not contain core members). + +!!! Warning For each line in the `/etc/group` file there must be a corresponding line in the `/etc/gshadow` file. + +A `!` in the password indicates that it is locked. Thus no user can use the password to access the group (since group members do not need it). + +## User management + +### Definition + +A user is defined as follows in the `/etc/passwd` file: + +* 1: Login; +* 2: Password; +* 3: UID; +* 4: GID of the main group; +* 5: Comments; +* 6: Home directory; +* 7: Shell (`/bin/bash`, `/bin/nologin`, ...). + +There are three types of users: + +* **root**: the system administrator ; +* **system users**: Used by the system to manage application access rights ; +* **regular user**: Other account to log in to the system. + +Modified files, added lines: + +* `/etc/passwd` +* `/etc/shadow` + +### `useradd` command + +The `useradd` command is used to add a user. + +``` +useradd [-u UID] [-g GID] [-d directory] [-s shell] login +``` + +Example: + +``` +$ sudo useradd -u 1000 -g 1013 -d /home/GroupC/carine carine +``` + +| Option | Description | +| -------------- | ------------------------------------------------------------------- | +| `-u UID` | `UID` of the user to create. | +| `-g GID` | `GID` of the main group. | +| `-d directory` | Home directory. | +| `-s shell` | Shell. | +| `-c` | Add a comment. | +| `-U` | Adds the user to a group with the same name created simultaneously. | +| `-M` | Does not create the connection directory. | + +At creation, the account has no password and is locked. + +A password must be assigned to unlock the account. + +Account naming rules: + +* No accents, capital letters or special characters; +* Different from the name of an existing group or system file; +* Set the options `-u`, `-g`, `-d` and `-s` at creation. + +!!! Warning The home directory tree must be created except for the last directory. + +The last directory is created by the `useradd` command, which takes the opportunity to copy the files from `/etc/skel` into it. + +**A user can belong to several groups in addition to their main group.** + +For secondary groups, the `-G` option must be used. + +Example: + +``` +$ sudo useradd -u 1000 -g GroupA -G GroupP,GroupC albert +``` + +!!! Note Under **Debian**, you will have to specify the `-m` option to force the creation of the login directory or set the `CREATE_HOME` variable in the `/etc/login.defs` file. In all cases, the administrator should use the `adduser` and `deluser` commands as specified in the `man`, except in scripts intended to be portable to all Linux distributions: + + ``` + $ man useradd + DESCRIPTION + **useradd** is a low level utility for adding users. On Debian, administrators should usually use **adduser(8)** + instead. + ``` + +#### Default value for user creation. + +Modification of the file `/etc/default/useradd`. + +``` +useradd -D [-b directory] [-g group] [-s shell] +``` + +Example: + +``` +$ sudo useradd -D -g 1000 -b /home -s /bin/bash +``` + +| Option | Description | +| -------------- | ----------------------------------------------------------------------------- | +| `-D` | Sets the default values for user creation. | +| `-b directory` | Sets the default login directory. | +| `-g group` | Sets the default group. | +| `-s shell` | Sets the default shell. | +| `-f` | The number of days after the password expires before the account is disabled. | +| `-e` | The date the account will be disabled. | + +### `usermod` command + +The `usermod` command allows to modify a user. + +``` +usermod [-u UID] [-g GID] [-d directory] [-m] login +``` + +Example: + +``` +$ sudo usermod -u 1044 carine +``` + +Options identical to the `useradd` command. + +| Option | Description | +| --------------- | ---------------------------------------------------------------------------------------------- | +| `-m` | Associated with the `-d` option, moves the contents of the old login directory to the new one. | +| `-l login` | New name. | +| `-e AAAA-MM-JJ` | Account expiration date. | +| `-L` | Locks the account. | +| `-U` | Unlocks the account. | +| `-a` | Prevents the user from being deleted from a subgroup when added to another subgroup. | +| `-G` | Specifies multiple subgroups when adding. | + +With the `usermod` command, locking an account results in the addition of `!` before the password in the `/etc/shadow` file. + +!!! Tip To be modified, a user must be disconnected and have no running processes. + +After changing the identifier, the files belonging to the user have an unknown `UID`. It must be reassigned the new `UID`. + +``` +$ sudo find / -uid 1000 -exec chown 1044: {} \; +``` + +Where `1000` is the old `UID` and `1044` is the new one. + +It is possible to invite a user into one or more subgroups with the options *-a* and *-G*. + +Example: + +``` +$ sudo usermod -aG GroupP,GroupC albert +``` + +The `usermod` command acts as a modification and not as an addition. + +For a user invited to a group by this command and already positioned as a guest in other secondary groups, it will be necessary to indicate in the group management command all the groups to which he belongs otherwise he will disappear from them. + +The *-a* option changes this behavior. + +Examples: + +* Invite `albert` in the group `GroupP`. + +``` +$ sudo usermod -G GroupP albert +``` + +* Invites `albert` into the `GroupG` group, but removes him from the `GroupP` guest list. + +``` +$ sudo usermod -G GroupG albert +``` + +* So either : + +``` +$ sudo usermod -G GroupP,GroupG albert +``` + +* Or : + +``` +$ sudo usermod -aG GroupG albert +``` + +### `userdel` command + +The `userdel` command allows you to delete a user's account. + +``` +$ sudo userdel -r carine +``` + +| Option | Description | +| ------ | --------------------------------------------------------- | +| `-r` | Deletes the connection directory and the contained files. | + +!!! Tip To be deleted, a user must be logged out and have no running processes. + +`userdel` removes the user's line from the `/etc/passwd` and `/etc/gshadow` files. + +### `/etc/passwd` file + +This file contains user information (separated by `:`). + +``` +$ sudo head -1 /etc/passwd +root:x:0:0:root:/root:/bin/bash +(1)(2)(3)(4)(5) (6) (7) +``` + +* 1: Login. +* 2: Password (`x` if defined in `/etc/shadow`). +* 3: UID. +* 4: GID of the main group. +* 5: Comment. +* 6: Home directory. +* 7: Shell. + +### `/etc/shadow` file + +This file contains the users' security information (separated by `:`). +``` +$ sudo tail -1 /etc/shadow +root:$6$...:15399:0:99999:7::: + (1) (2) (3) (4) (5) (6)(7,8,9) +``` + +* 1: Login. +* 2: Encrypted password. +* 3: Date of last change. +* 4: Minimum lifetime of the password. +* 5: Maximum lifetime of the password. +* 6: Number of days before warning. +* 7: Time to deactivate account after expiration. +* 8: Account expiration time. +* 9: Reserved for future use. + +!!! Danger For each line in the `/etc/passwd` file there must be a corresponding line in the `/etc/shadow` file. + +## File owners + +!!! Danger All files necessarily belong to one user and one group. + +The main group of the user creating the file is, by default, the group that owns the file. + +### Modification commands + +#### `chown` command + +The `chown` command allows you to change the owners of a file. +``` +chown [-R] [-v] login[:group] file +``` + +Examples: +``` +$ sudo chown root myfile +$ sudo chown albert:GroupA myfile +``` + +| Option | Description | +| ------ | ----------------------------------------------------- | +| `-R` | Changes the owners of the directory and its contents. | +| `-v` | Displays the executed changes. | + +To change only the owner user: + +``` +$ sudo chown albert file +``` + +To modify only the owner group: + +``` +$ sudo chown :GroupA file +``` + +Changing the user and owner group: + +``` +$ sudo chown albert:GroupA file +``` + +In the following example the group assigned will be the main group of the specified user. + +``` +$ sudo chown albert: file +``` + +### `chgrp` command + +The `chgrp` command allows you to change the owner group of a file. + +``` +chgrp [-R] [-v] group file +``` + +Example: +``` +$ sudo chgrp group1 file +``` + +| Option | Description | +| ------ | ------------------------------------------------------------------------ | +| `-R` | Modifies the owner groups of the directory and its contents (recursion). | +| `-v` | Displays the executed changes. | + +!!! Note It is possible to apply to a file an owner and an owner group by taking as reference those of another file: + +``` +chown [options] --reference=RRFILE FILE +``` + +For example: + +``` +chown --reference=/etc/groups /etc/passwd +``` + +## Guest management + +### `gpasswd` command + +The command `gpasswd` allows to manage a group. + +``` +gpasswd [-a login] [-A login] [-d login] [-M login] group +``` + +Examples: + +``` +$ sudo gpasswd -A alain GroupA +[alain]$ gpasswd -a patrick GroupA +``` + +| Option | Description | +| ---------- | ------------------------------------ | +| `-a login` | Adds the user to the group. | +| `-A login` | Sets the group administrator. | +| `-d login` | Remove the user from the group. | +| `-M login` | Defines the complete list of guests. | + +The command `gpasswd -M` acts as a modification, not an addition. +``` +# gpasswd GroupeA +New Password : +Re-enter new password : +``` + +### `id` command + +The `id` command displays the group names of a user. +``` +id login +``` +Example: +``` +$ sudo id alain +uid=1000(alain) gid=1000(GroupA) groupes=1000(GroupA),1016(GroupP) +``` + +### `newgrp` command + +The `newgrp` command allows you to temporarily use a secondary group for file creation. +``` +newgrp [secondarygroups] +``` +Example: +``` +[alain]$ newgrp GroupB +``` + +!!! Note After using this command, the files will be created with the `GID` of its subgroup. + +The command `newgrp` without parameters reassigns the main group. + +## Securing + +### `passwd` command + +The `passwd` command is used to manage a password. +``` +passwd [-d] [-l] [-S] [-u] [login] +``` +Examples: +``` +$ sudo passwd -l albert +$ sudo passwd -n 60 -x 90 -w 80 -i 10 patrick +``` + +| Option | Description | +| --------- | ---------------------------------------------------- | +| `-d` | Removes the password. | +| `-l` | Locks the account. | +| `-S` | Displays the account status. | +| `-u` | Unlocks the account. | +| `-e` | Expires the password. | +| `-n days` | Minimum password lifetime. | +| `-x days` | Maximum password lifetime. | +| `-w days` | Warning time before expiration. | +| `-i days` | Delay before deactivation when the password expires. | + +With the `passwd` command, locking an account is accomplished by adding `!!` before the password in the `/etc/shadow` file. + +Using the command `usermod -U` command only removes one of the `!`. So the account remains locked. + +Example: + +* Alain changes his password: + +``` +[alain]$ passwd +``` + +* root changes Alain's password + +``` +$ sudo passwd alain +``` + +!!! Note The `passwd` command is available to users to change their password (the old password is requested). The administrator can change the passwords of all users without restriction. + +They will have to comply with the security restrictions. + +When managing user accounts by shell script, it may be useful to set a default password after creating the user. + +This can be done by passing the password to the `passwd` command. + +Example: +``` +$ sudo echo "azerty,1" | passwd --stdin philippe +``` +!!! Warning The password is entered in clear text, `passwd` takes care of encrypting it. + +### `chage` command + +The `chage` command is used to manage the account strategy. +``` +chage [-d date] [-E date] [-I days] [-l] [-m days] [-M days] [-W days] [login] +``` +Example: +``` +$ sudo chage -m 60 -M 90 -W 80 -I 10 alain +``` + +| Option | Description | +| --------------- | -------------------------------------------- | +| `-I days` | Delay before deactivation, password expired. | +| `-l` | Displays the policy details. | +| `-m days` | Minimum lifetime of the password. | +| `-M days` | Maximum lifetime of the password. | +| `-d AAAA-MM-JJ` | Last password change. | +| `-E AAAA-MM-JJ` | Account expiration date. | +| `-W days` | Warning time before expiration. | + +The `chage` command also offers an interactive mode. + +The `-d` option forces the password to be changed at login. + +Examples: +``` +$ sudo chage philippe +$ sudo chage -d 0 philippe +``` + +!!! Note If no user is specified, the order will concern the user who enters it. + +![User account management with chage](images/chage-timeline.png) + +## Advanced management + +Configuration files: +* `/etc/default/useradd` +* `/etc/login.defs` +* `/etc/skel` + +!!! Note Editing the `/etc/default/useradd` file is done with the `useradd` command. + + The other files are to be modified with a text editor. + +### `/etc/default/useradd` file + +This file contains the default data settings. + +!!! Tip When creating a user, if the options are not specified, the system uses the default values defined in `/etc/default/useradd`. + +This file is modified by the command `useradd -D` (`useradd -D` entered without any other option displays the contents of the `/etc/default/useradd` file). + +| Value | Comment | +| ------------------- | ------------------------------------------------------------------------- | +| `GROUP` | Default group. | +| `HOME` | Path where the login directory for the user's name will be created. | +| `INACTIVE` | Number of days after the password expires before the account is disabled. | +| `EXPIRE` | Account expiration date. | +| `SHELL` | Command interpreter. | +| `SKEL` | Skeleton directory of the login directory. | +| `CREATE_MAIL_SPOOL` | Mailbox creation in `/var/spool/mail`. | + +!!! Warning Without the `-g` option, the `useradd` command creates a group of the user's name name and places it there. + +In order for the `useradd` command to retrieve the value of the `GROUP` field from the `/etc/default/useradd` file, you must specify the `-N` option. + +Example: +``` +$ sudo useradd -u 501 -N GroupeA +``` + +### `/etc/login.defs` file + +This file contains many default parameters useful for creating or modifying users. This information is grouped by paragraph according to their use: + +* Mailboxes; +* Passwords ; +* UID and GID ; +* Umask ; +* Connections; +* Terminals. + +### `/etc/skel` directory + +When a user is created, their home directory and environment files are created. + +These files are automatically copied from the `/etc/skel` directory. + +* `.bash_logout` +* `.bash_profile` +* `.bashrc` + +All files and directories placed in this directory will be copied to the user tree when they are created. + +## Identity change + +### `su` command + +The `su` command allows you to change the identity of the connected user. + +``` +su [-] [-c command] [login] +``` + +Examples: + +``` +$ sudo su - alain +[albert]$ su -c "passwd alain" +``` + +| Option | Description | +| ------------ | ----------------------------------------------- | +| `-` | Loads the user's complete environment. | +| `-c` command | Executes the command under the user's identity. | + +If the login is not specified, it will be `root`. + +Standard users will have to type the password for the new identity. + +!!! Tip There are successive 'layers' created (a stack of `bash` environments). To switch from one user to another, you must first type the `exit` command to take back your identity and then the `su` command to take another identity. + +#### Profile loading + +`root` endorses the identity of the user `alain` with `su`: + +``` +... +/home/GroupA/alain/.bashrc +/etc/bashrc +... +``` + +`root` assumes the identity of the user `alain` with `su -`: + +``` +... +/home/GroupA/alain/.bash_profile +/home/GroupA/alain/.bashrc +/etc/bashrc +... +``` + +A user can temporarily (for another command or an entire session) assume the identity of another account. + +If no user is specified, the command will be for `root` (`su -`). + +It is necessary to know the password of the user whose identity is being endorsed unless it is `root` that is executing the command. + +An administrator can thus work on a standard user account and use the rights of the `root` account only occasionally. From 5619eb167013f182f37ecc139865ca4998cb87e0 Mon Sep 17 00:00:00 2001 From: Rocky Linux Automation <75949597+rockylinux-auto@users.noreply.github.com> Date: Fri, 17 Dec 2021 11:30:10 -0500 Subject: [PATCH 37/37] New translations 13-softwares.md (Chinese Simplified) --- docs/books/admin_guide/13-softwares.zh.md | 217 ++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 docs/books/admin_guide/13-softwares.zh.md diff --git a/docs/books/admin_guide/13-softwares.zh.md b/docs/books/admin_guide/13-softwares.zh.md new file mode 100644 index 0000000000..258efd4acb --- /dev/null +++ b/docs/books/admin_guide/13-softwares.zh.md @@ -0,0 +1,217 @@ +--- +title: Software Management +--- + +# Software Management + +## 概论 + +On a Linux system, it is possible to install software in two ways: + +* Using an installation package; +* Compiling from source files. + +!!! Note Installing from source is not covered here. As a rule, you should use the package method unless the software you want is not available via the package manager. The reason for this is that dependencies are generally managed by the package system, whereas with source, you need to manage the dependencies manually. + +**The package**: This is a single file containing all the data needed to install the program. It can be executed directly on the system from a software repository. + +**The source files** : Some software is not provided in packages ready to be installed, but via an archive containing the source files. It is up to the administrator to prepare these files and compile them to install the program. + +## RPM : RedHat Package Manager + +**RPM** (RedHat Package Manager) is a software management system. It is possible to install, uninstall, update or check software contained in packages. + +**RPM** is the format used by all RedHat based distributions (RockyLinux, Fedora, CentOS, SuSe, Mandriva, ...). Its equivalent in the Debian world is DPKG (Debian Package). + +The name of an RPM package follows a specific nomenclature: + +![Illustration of a package name](images/software-001.png) + +### `rpm` command + +The rpm command allows you to install a package. + +``` +rpm [-i][-U] package.rpm [-e] package +``` + +Example (for a package named 'package'): + +``` +[root]# rpm -ivh package.rpm +``` + +| Option | Description | +| ---------------- | -------------------------------------------- | +| `-i package.rpm` | Installs the package. | +| `-U package.rpm` | Updates an already installed package. | +| `-e package.rpm` | Uninstalls the package. | +| `-h` | Displays a progress bar. | +| `-v` | Informs about the progress of the operation. | +| `--test` | Tests the command without executing it. | + +The `rpm` command also allows you to query the system package database by adding the `-q` option. + +It is possible to execute several types of queries to obtain different information about the installed packages. The RPM database is located in the directory `/var/lib/rpm`. + +Example: + +``` +[root]# rpm -qa +``` + +This command queries all the packages installed on the system. + +``` +rpm -q [-a][-i][-l] package [-f] file +``` + +Example: + +``` +[root]# rpm -qil package +[root]# rpm -qf /path/to/file +``` + +| Option | Description | +| ---------------- | ---------------------------------------------------------------------------------------------- | +| `-a` | Lists all packages installed on the system. | +| `-i __package__` | Displays the package information. | +| `-l __package__` | Lists the files contained in the package. | +| `-f` | Shows the name of the package containing the specified file. | +| `--last` | The list of packages is given by installation date (the last installed packages appear first). | + +!!! Warning After the `-q` option, the package name must be exact. Metacharacters (wildcards) are not supported. + +!!! Tip However, it is possible to list all installed packages and filter with the `grep` command. + +Example: list the last installed packages: + +``` +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 +``` + +Example: list the installation history of the kernel: + +``` +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 +``` + +Example: list all installed packages with a specific name using `grep`: + +``` +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**) is a software package manager, successor of **YUM** (**Yellow dog **U**pdater **M**odified). It works with **RPM** packages grouped in a local or remote repository (a directory for storing packages). For the most common commands, its usage is identical to that of `yum`. + +The `dnf` command allows the management of packages by comparing those installed on the system with those in the repositories defined on the server. It also automatically installs dependencies, if they are also present in the repositories. + +`dnf` is the manager used by many RedHat based distributions (RockyLinux, Fedora, CentOS, ...). Its equivalent in the Debian world is **APT** (**A**dvanced **P**ackaging **T**ool). + +### `dnf` command + +The dnf command allows you to install a package by specifying only the short name. + +``` +dnf [install][remove][list all][search][info] package +``` + +Example: + +``` +[root]# dnf install tree +``` + +Only the short name of the package is required. + +| Option | Description | +| ------------------------- | --------------------------------------------- | +| `install` | Installs the package. | +| `remove` | Uninstall the package. | +| `list all` | Lists the packages already in the repository. | +| `search` | Search for a package in the repository. | +| `provides */command_name` | Search for a command. | +| `info` | Displays the package information. | + +The `dnf list` command lists all the packages installed on the system and present in the repository. It accepts several parameters: + +| Parameter | Description | +| ----------- | -------------------------------------------------------------------------- | +| `all` | Lists the installed packages and then those available on the repositories. | +| `available` | Lists only the packages available for installation. | +| `updates` | Lists packages that can be upgraded. | +| `obsoletes` | Lists the packages made obsolete by higher versions available. | +| `recent` | Lists the latest packages added to the repository. | + +Example of a search for the `semanage` command: + +``` +[root]# dnf provides */semanage +``` + +### How DNF works + +The DNF manager relies on one or more configuration files to target the repositories containing the RPM packages. + +These files are located in `/etc/yum.repos.d/` and must end with `.repo` in order to be used by DNF. + +Example: + +``` +/etc/yum.repos.d/Rocky-BaseOS.repo +``` + +Each `.repo` file consists of at least the following information, one directive per line. + +Example: + +``` +[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 +``` + +By default, the `enabled` directive is absent which means that the repository is enabled. To disable a repository, you must specify the `enabled=0` directive. + +## The EPEL repository + +**EPEL** (**E**xtra **P**ackages for **E**nterprise **L**inux) is a repository containing additional software packages for Enterprise Linux, which includes RedHat Enterprise Linux (RHEL), RockyLinux, CentOS, etc. + +### Installation + +Download and install the rpm from the repository: + +If you are behind an internet proxy: + +``` +[root]# export http_proxy=http://172.16.1.10:8080 +``` + +Then: + +``` +[root]# dnf install epel-release +```