diff --git a/docs/books/admin_guide/01-presentation.fr.md b/docs/books/admin_guide/01-presentation.fr.md index 061206bf65..25336a3fd2 100644 --- a/docs/books/admin_guide/01-presentation.fr.md +++ b/docs/books/admin_guide/01-presentation.fr.md @@ -2,6 +2,8 @@ title: Introduction à Linux --- + + # Introduction au système d'exploitation Linux Dans ce chapitre, vous allez en apprendre plus à propos des distributions GNU/Linux. @@ -10,18 +12,19 @@ Dans ce chapitre, vous allez en apprendre plus à propos des distributions GNU/L **Objectifs** : Dans ce chapitre, vous apprendrez à : -:heavy_check_mark: Décrire les caractéristiques et les architectures possibles d'un système d'exploitation. -:heavy_check_mark: Retracer l'histoire d'UNIX et de GNU/Linux -:heavy_check_mark: Choisir la distribution Linux adaptée à ses besoins -:heavy_check_mark: Expliquer la philosophie des logiciels libres et open source +:heavy_check_mark: Décrire les caractéristiques et les architectures possibles d'un système d'exploitation. +:heavy_check_mark: Retracer l'histoire de UNIX et de GNU/Linux. +:heavy_check_mark: Choisir la distribution Linux adaptée à vos propres besoins. +:heavy_check_mark: Expliquer la philosophie des logiciels libres et open source. :heavy_check_mark: Découvrir l'utilité de la SHELL. :checkered_flag: **généralités**, **linux**, **distributions** -**Connaissances** : :star: -**Complexité** : :star: +**Connaissances**: :star: + +**Complexité**: :star: -**Temps de lecture** : 10 minutes +**Temps de lecture** : 11 minutes **** @@ -35,12 +38,18 @@ Linux, UNIX, BSD, VxWorks, Windows et MacOS sont tous des **systèmes d'exploita Dans le cadre de la gestion des ressources, le système d'exploitation doit : -* Gérer la mémoire physique ou virtuelle. +* Gérer la mémoire **physique** ou **virtuelle**. + * La **mémoire physique** est constituée des barrettes de RAM et de la mémoire cache du processeur qui sont utilisées pour l'exécution des programmes. + * La **mémoire virtuelle** est un emplacement sur le disque dur (la partition **swap**) qui permet de décharger la mémoire physique et de sauvegarder l'état actuel du système lors de l'arrêt électrique de l'ordinateur. + * Intercepter les **accès aux périphériques**. Les logiciels sont rarement autorisés à accéder directement au matériel (sauf les cartes graphiques pour des besoins très spécifiques). + * Fournir aux applications une **gestion correcte des tâches**. Le système d'exploitation est responsable de l'ordonnencement des processus pour les répartir sur le ou les processeur(s). + * **Protéger les fichiers** contre les accès non autorisés. + * **Collecter des informations** sur les programmes utilisés ou en cours d'exécution. ![Fonctionnement d'un système d'exploitation](images/operating_system.png) @@ -110,12 +119,17 @@ Linux équipe 100% des 500 superordinateurs depuis 2018. Un superordinateur est ### Conception architecturale * Le **noyau** est le premier composant logiciel. + * C'est le cœur du système GNU/Linux. * Il gère les ressources matérielles du système. * Les autres composants logiciels doivent passer par lui pour accéder au matériel. + * Le **shell** est un utilitaire qui interprète les commandes de l'utilisateur et assure leur exécution. + * Principaux shells : Bourne shell, C shell, Korn shell et Bourne-Again shell (bash). + * **Les applications** sont des programmes utilisateur incluant mais non limités à : + * Navigateurs Internet * Traitement de texte * Tableurs @@ -131,7 +145,7 @@ Linux appartient à la famille des systèmes d'exploitation à temps partagé. I #### Multi-utilisateurs -Le but de MULTIX était de permettre à plusieurs utilisateurs de travailler à partir de plusieurs terminaux (écran et clavier) simultanément sur un seul ordinateur (très cher à l'époque). Linux, inspiré de ce système d'exploitation, a conservé cette capacité de travailler avec plusieurs utilisateurs simultanément et indépendamment, chacun ayant son propre compte utilisateur avec un espace mémoire et des droits d'accès aux fichiers et aux logiciels. +Le but de MULTICS était de permettre à plusieurs utilisateurs de travailler à partir de plusieurs terminaux (écran et clavier) simultanément sur un seul ordinateur (très cher à l'époque). GNU/Linux, inspiré de ce système d'exploitation, a conservé cette capacité de travailler avec plusieurs utilisateurs simultanément et indépendamment, chacun ayant son propre compte utilisateur avec un espace mémoire et des droits d'accès aux fichiers et aux logiciels. #### Multi-processeurs @@ -139,7 +153,7 @@ Linux est capable de fonctionner sur des ordinateurs multi-processeurs et/ou ave #### Multi-plateforme -Linux est écrit dans un langage de haut niveau qui peut être adapté à différents types de plates-formes pendant la compilation. Cela lui permet de s'exécuter sur : +Linux est écrit dans un langage de haut niveau qui peut être adapté à différents types de plates-formes lors de la compilation. Cela lui permet d'être exécuté sur : * Ordinateurs domestiques (PC ou ordinateur portable) * Serveurs (données, applications, ...) @@ -158,12 +172,12 @@ Linux est basé sur et utilise des standards reconnus tels que [POSIX](http://fr * Portabilité. * Ne faire qu’une seule chose à la fois et la faire bien. * KISS : Keep It Simple and Stupid. -* “UNIX est simple, il faut juste être un génie pour comprendre sa simplicité” (__Dennis Ritchie__) -* “UNIX est convivial. Cependant UNIX ne précise pas vraiment avec qui.” (__Steven King__) +* “UNIX est simple, il faut juste être un génie pour comprendre sa simplicité” (**Dennis Ritchie**) +* “UNIX est convivial. Cependant UNIX ne précise pas vraiment avec qui.” (**Steven King**) ## Les distributions GNU/Linux -Une distribution Linux est un **ensemble cohérent de logiciels** assemblés autour du noyau Linux et prêt à être installé ainsi que le nécessaire à la gestion de ces logiciels (installation, suppression, configuration). Il existe des **distributions associatives ou communautaires** (Debian, CentOS) ou **commerciales** (RedHat, Ubuntu). +Une distribution Linux est un **ensemble cohérent de logiciels** assemblés autour du noyau Linux et prêt à être installé ainsi que le nécessaire à la gestion de ces logiciels (installation, suppression, configuration,...). Il existe des **distributions associatives ou communautaires** (Debian, CentOS) ou bien **commerciales** (RedHat, Ubuntu). Chaque distribution offre un ou plusieurs **environnements de bureau** et fournit un ensemble de logiciels préinstallés et une bibliothèque de logiciels supplémentaires. Les options de configuration (options du noyau ou des services par exemple) sont spécifiques à chaque distribution. @@ -171,15 +185,15 @@ Ce principe permet aux distributions d'être orientées vers **débutants** (Ubu ### Les environnements de bureau -Les environnements graphiques sont nombreux : **GNOME**, **KDE**, **LXDE**, **XFCE**, etc. Il y en a pour tous les goûts, et leurs **ergonomies** n’ont pas à rougir de ce que l’on peut retrouver sur les systèmes Microsoft ou Apple. +Les environnements graphiques sont nombreux : **GNOME**, **KDE**, **LXDE**, **XFCE**, etc. Il y en a pour tous les goûts et leurs **ergonomies** n’ont pas à rougir de ce que l’on peut retrouver sur les systèmes Microsoft ou Apple. -Alors pourquoi y a-t-il si peu d'enthousiasme pour Linux ? Peut-être est-ce parce que tant d'éditeurs (Adobe) et de fabricants (Nvidia) ne jouent pas au jeu du mouvement du libre et ne fournissent pas de version de leurs logiciels ou __pilotes__ pour GNU/Linux ? Peut-être est-ce la peur du changement, ou la difficulté de trouver où acheter un ordinateur Linux, ou trop peu de jeux distribués sous Linux. Cette dernière excuse au moins ne devrait pas être vraie pour longtemps, avec l'avènement du moteur de jeu Steam pour Linux. +Alors pourquoi y a-t-il si peu d'enthousiasme pour Linux ? Peut-être est-ce parce que tant d'éditeurs (Adobe) et de fabricants (Nvidia) ne jouent pas au jeu du libre et ne fournissent pas de version de leurs logiciels ou **pilotes** pour GNU/Linux ? Peut-être est-ce la peur du changement, la difficulté de trouver où acheter un ordinateur Linux ou trop peu de jeux distribués sous Linux. Cette dernière excuse au moins ne devrait pas être vraie pour longtemps, avec l'avènement du moteur de jeu Steam pour Linux. -![GNOME Desktop](images/01-presentation-gnome.png) +![Environment de bureau GNOME](images/01-presentation-gnome.png) L'environnement de bureau **GNOME 3** n'utilise plus le concept de bureau mais celui de GNOME Shell (à ne pas confondre avec le shell en ligne de commande). Il sert à la fois de bureau, de tableau de bord, de zone de notification et de sélecteur de fenêtre. L'environnement de bureau GNOME est basé sur la bibliothèque de composants **GTK+**. -![KDE Desktop](images/01-presentation-kde.png) +![Le bureau KDE](images/01-presentation-kde.png) L’environnement de bureau **KDE** se base sur la bibliothèque de composants **Qt**. Il est traditionnellement recommandé pour les utilisateurs familiers avec un environnement Windows. @@ -219,7 +233,7 @@ Une distribution Linux excelle pour : * **Ordinateur centraux** : Banques, assurances, industrie, etc. * **Systèmes embarqués**: Routeurs, boîtes Internet, SmartTVs, etc. -Linux est un choix adapté pour l’hébergement de bases de données ou de sites Web ou comme serveur de messagerie, DNS, pare-feu. Bref Linux peut à peu près tout faire, ce qui explique la quantité de distributions spécifiques. +Linux est un choix adapté pour l’hébergement de bases de données ou de sites Web ou comme serveur de messagerie, DNS ou bien pare-feu. Bref Linux peut à peu près tout faire, ce qui explique la quantité de distributions spécifiques. ## Le Shell @@ -251,62 +265,62 @@ Il existe plusieurs types d'interpréteurs de commandes disponibles et configura :heavy_check_mark: Un système d’exploitation est un ensemble de programmes permettant la gestion des ressources disponibles d’un ordinateur : -- [ ] Vrai -- [ ] Faux +* [ ] Vrai +* [ ] Faux :heavy_check_mark: Le système d’exploitation est amené à : -- [ ] Gérer la mémoire physique et virtuelle -- [ ] Permettre l’accès direct aux périphériques -- [ ] Sous traiter la gestion des tâches au processeur -- [ ] Collecter des informations sur les programmes utilisées ou en cours d’exécution +* [ ] Gérer la mémoire physique et virtuelle +* [ ] Permettre l’accès direct aux périphériques +* [ ] Sous traiter la gestion des tâches au processeur +* [ ] Collecter des informations sur les programmes utilisées ou en cours d’exécution :heavy_check_mark: Parmi ces personnalités, lesquelles ont participé au développement de UNIX : -- [ ] Linus Torvalds -- [ ] Ken Thompson -- [ ] Lionel Richie -- [ ] Brian Kernighan -- [ ] Andrew Stuart Tanenbaum +* [ ] Linus Torvalds +* [ ] Ken Thompson +* [ ] Lionel Richie +* [ ] Brian Kernighan +* [ ] Andrew Stuart Tanenbaum :heavy_check_mark: La nationalité d’origine de Linus Torvalds, créateur du noyau Linux, est : -- [ ] Suédoise -- [ ] Finlandaise -- [ ] Norvégienne -- [ ] Flamande -- [ ] Française (évidemment) +* [ ] Suédoise +* [ ] Finlandaise +* [ ] Norvégienne +* [ ] Flamande +* [ ] Française (évidemment) :heavy_check_mark: Parmi les distributions suivantes, quelle est la plus ancienne : -- [ ] Debian -- [ ] Slackware -- [ ] Red Hat -- [ ] Arch +* [ ] Debian +* [ ] Slackware +* [ ] Red Hat +* [ ] Arch :heavy_check_mark: Le noyau Linux est-il : -- [ ] Multitâche -- [ ] Multiutilisateurs -- [ ] Multi-processeurs -- [ ] Multicoeurs -- [ ] Multiplateforme -- [ ] Ouvert +* [ ] Multitâche +* [ ] Multiutilisateurs +* [ ] Multi-processeurs +* [ ] Multicoeurs +* [ ] Multiplateforme +* [ ] Ouvert :heavy_check_mark: Un logiciel libre est-il forcément Open Source ? -- [ ] Vrai -- [ ] Faux +* [ ] Vrai +* [ ] Faux :heavy_check_mark: Un logiciel Open Source est-il forcément libre ? -- [ ] Vrai -- [ ] Faux +* [ ] Vrai +* [ ] Faux :heavy_check_mark: Parmi les propositions suivantes, laquelle n’est pas un shell : -- [ ] Jason -- [ ] Jason-Bourne shell (jbsh) -- [ ] Bourne-Again shell (bash) -- [ ] C shell (csh) -- [ ] Korn shell (ksh) +* [ ] Jason +* [ ] Jason-Bourne shell (jbsh) +* [ ] Bourne-Again shell (bash) +* [ ] C shell (csh) +* [ ] Korn shell (ksh) diff --git a/docs/books/admin_guide/01-presentation.it.md b/docs/books/admin_guide/01-presentation.it.md index c26602c343..45af01b52f 100644 --- a/docs/books/admin_guide/01-presentation.it.md +++ b/docs/books/admin_guide/01-presentation.it.md @@ -2,6 +2,8 @@ title: Introduzione a Linux --- + + # Introduzione al Sistema Operativo Linux In questo capitolo imparerete a conoscere le distribuzioni GNU/Linux. @@ -18,30 +20,37 @@ In questo capitolo imparerete a conoscere le distribuzioni GNU/Linux. :checkered_flag: **generalità**, **linux**, **distribuzioni** -**Conoscenza**: :star: **Complessità**: :star: +**Complexity**: :star: + **Tempo di lettura**: 10 minuti **** ## Che cos'è un sistema operativo? -Linux, UNIX, BSD, Windows e MacOS sono tutti **sistemi operativi**. +Linux, UNIX, BSD, VxWorks, Windows e MacOS sono tutti **sistemi operativi**. -!!! abstract "Astratto" +!!! abstract "Astrazione" Un sistema operativo è un **insieme di programmi che gestisce le risorse disponibili di un computer**. Nell'ambito di questa gestione delle risorse, il sistema operativo deve: * Gestire la memoria **fisica** o **virtuale**. + * La **memoria fisica** è costituita dalle memorie RAM e dalla memoria cache del processore, utilizzate per l'esecuzione dei programmi. + * La **memoria virtuale** è una posizione sul disco rigido (la partizione **swap**) che consente di svuotare la memoria fisica e di salvare lo stato attuale del sistema durante lo spegnimento elettrico del computer. + * Intercettare **l'accesso alle periferiche**. Raramente il software può 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. + +* Fornire alle applicazioni una corretta **gestione delle attività**. Il sistema operativo è responsabile della pianificazione dei processi che occupano il processore + * **Proteggere i file** da accessi non autorizzati. -* **Raccogliere informazioni** sui programmi in uso o in svolgimento. + +* **Raccogliere informazioni** sui programmi in uso o in fase di esecuzione. ![Funzionamento di un sistema operativo](images/operating_system.png) @@ -55,11 +64,11 @@ Nell'ambito di questa gestione delle risorse, il sistema operativo deve: * **1969 — 1971**: Dopo il ritiro di Bell (1969) e poi di General Electric dal progetto, due sviluppatori, Ken Thompson e Dennis Ritchie (a cui si aggiunge in seguito Brian Kernighan), giudicando MULTICS troppo complesso, iniziano lo sviluppo di UNIX (UNiplexed Information and Computing Service). Sebbene sia stato originariamente creato in linguaggio Assembly, i creatori di UNIX svilupparono alla fine il linguaggio B e poi il linguaggio C (1971) e riscrissero completamente UNIX. Poiché è stato sviluppato nel 1970, la data di riferimento (epoch) per l'inizio del periodo di tempo dei sistemi UNIX/Linux è fissata al 01 gennaio 1970. -Il linguaggio C è ancora oggi uno dei linguaggi di programmazione più diffusi. Un linguaggio di basso livello, a contatto con l'hardware, che permette di adattare il sistema operativo a qualsiasi architettura di macchina dotata di un compilatore C. +Il linguaggio C rimane ancora oggi uno dei linguaggi di programmazione più diffusi. Un linguaggio di basso livello, a contatto con l'hardware, che permette di adattare il sistema operativo a qualsiasi architettura di macchina dotata di un compilatore C. UNIX è un sistema operativo aperto e in continua evoluzione che ha svolto un ruolo fondamentale nella storia dell'informatica. Costituisce la base di molti altri sistemi come Linux, BSD, MacOS e altri ancora. -UNIX è ancora rilevante oggi (HP-UX, AIX, Solaris, etc.) +UNIX è ancora rilevante al giorno d'oggi (HP-UX, AIX, Solaris, ecc.). #### Progetto GNU @@ -110,12 +119,17 @@ Linux equipaggia il 100% dei 500 supercomputer dal 2018. Un supercomputer è un ### Progettazione dell'architettura * Il **kernel** è il primo componente software. + * È il cuore del sistema Linux. * Gestisce le risorse hardware del sistema. * Gli altri componenti software devono passarvi attraverso per accedere all'hardware. + * La **shell** è un'utilità che interpreta i comandi dell'utente e ne garantisce l'esecuzione. + * Shell principali: shell Bourne, shell C, shell Korn e shell Bourne-Again (bash). -* **Applicazioni** sono programmi utente inclusi, ma non limitati a: + +* **Applicazioni** sono programmi utente, tra cui, a titolo esemplificativo e non esaustivo: + * Browser Internet * Elaboratore di testi * Fogli di calcolo @@ -158,8 +172,8 @@ Linux si basa su standard riconosciuti come [POSIX](http://en.wikipedia.org/wiki * Portabilità del valore. * Fai solo una cosa e falla bene. * 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__) +* "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**) ## Le distribuzioni GNU/Linux @@ -171,9 +185,9 @@ Questo principio permette alle distribuzioni di essere orientate ai **principian ### Ambienti desktop -Ci sono molti ambienti grafici: **GNOME**, **KDE**, **LXDE**, **XFCE**, etc. Ce n'è per tutti i gusti e l'**ergonomia** è all'altezza dei sistemi Microsoft o Apple. +Esistono numerosi ambienti grafici, come **GNOME**, **KDE**, **LXDE**, **XFCE**, etc. Ce n'è per tutti i gusti e la loro **ergonomia** regge il confronto con i sistemi Microsoft o Apple. -Allora perché c'è così poco entusiasmo per Linux, quando questo sistema è praticamente **privo di virus**? Forse perché molti editori (Adobe) e produttori (Nvidia) non fanno il gioco della libertà e non forniscono una versione del loro software o __driver__ per GNU/Linux? Forse è la paura del cambiamento, o la difficoltà di trovare dove acquistare un computer Linux, o ancora i pochi giochi distribuiti sotto Linux. Almeno quest'ultima scusa non dovrebbe essere vera a lungo, con l'avvento del motore di gioco Steam per Linux. +Allora perché c'è così poco entusiasmo per Linux, quando questo sistema è praticamente **privo di virus**? Potrebbe essere il motivo per cui cosi tanti editori (Adobe) e produttori (Nvidia) non sono gratuiti, né forniscono una versione del proprio software o dei propri **driver** per GNU/Linux? Forse è la paura del cambiamento, o la difficoltà nel trovare dove acquistare un computer Linux, o ancora i pochi giochi distribuiti sotto Linux. Almeno quest'ultima scusa non dovrebbe essere vera a lungo, con l'avvento del motore di gioco Steam per Linux. ![Desktop GNOME](images/01-presentation-gnome.png) @@ -189,17 +203,17 @@ L'ambiente desktop **KDE** si basa sulla libreria di componenti **Qt**. È tradi Un utente di un sistema operativo Microsoft o Mac deve acquistare una licenza per utilizzare il sistema operativo. Questa licenza ha un costo, anche se di solito è trasparente (il prezzo della licenza è incluso nel prezzo del computer). -Nel mondo **GNU/Linux**, il movimento del Software Libero fornisce principalmente distribuzioni gratuite. +Nel mondo **GNU/Linux**, il movimento del Software Libero fornisce principalmente distribuzioni libere. **Libero** non significa gratuito! -**Open source**: i codici sorgente sono disponibili, quindi è possibile consultare e modificarli a determinate condizioni. +**Open source**: il codice sorgente è disponibile, quindi è possibile consultarlo e modificarlo a determinate condizioni. Un software libero è necessariamente open-source, ma non è vero il contrario, poiché il software open-source si distingue per la libertà offerta dalla licenza GPL. #### GNU GPL (Licenza pubblica generale GNU) -La **GPL** garantisce all'autore di un software la sua proprietà intellettuale, ma consente modifiche, redistribuzione o rivendita di software da parte di terzi, a condizione che il codice sorgente sia incluso nel software. La GPL è la licenza dalla quale esce il progetto **GNU** (GNU is Not UNIX), che è stato strumentale nella creazione di Linux. +La **GPL** garantisce all'autore di un software la sua proprietà intellettuale, ma consente la modifica, la ridistribuzione o la rivendita del software da parte di terzi, a condizione che il codice sorgente sia incluso nel software. La GPL è la licenza nata dal progetto **GNU** (GNU is Not UNIX), che è stato determinante per la creazione di Linux. Questo implica: @@ -219,15 +233,15 @@ Una distribuzione Linux eccelle per: * **Computer centrali**: Banche, assicurazioni, industria, ecc. * **Sistemi integrati**: Router, Internet box, SmartTV, ecc. -Linux è una scelta adatta per l'hosting di database o siti Web, o per mail server, DNS o firewall. In breve, Linux può fare qualsiasi cosa, il che spiega la quantità di distribuzioni specifiche. +Linux è una scelta adatta per ospitare database o siti web, oppure come server di posta, DNS o firewall. In breve, Linux può fare praticamente tutto, il che spiega la quantità di distribuzioni specifiche. ## Shell ### Generalità -La **shell**, conosciuta anche come _command interface_, consente agli utenti di inviare comandi al sistema operativo. Oggi è meno visibile dopo l'implementazione delle interfacce grafiche, ma rimane un mezzo privilegiato sui sistemi Linux che non dispongono tutti di interfacce grafiche e i cui servizi non sempre hanno un'interfaccia di impostazione. +La **shell**, conosciuta anche come _command interface_, consente agli utenti di inviare comandi al sistema operativo. Oggi è meno visibile dopo l'implementazione delle interfacce grafiche, ma rimane un mezzo privilegiato sui sistemi Linux che non dispongono di interfacce grafiche e i cui servizi non sempre hanno un'interfaccia di impostazione. -Offre un vero e proprio linguaggio di programmazione che include strutture classiche (cicli, alternative) e componenti comuni (variabili, passaggio di parametri e sottoprogrammi). Alcuni esempi sono: +Offre un vero e proprio linguaggio di programmazione che include strutture classiche (cicli, alternative) e componenti comuni (variabili, passaggio di parametri e sottoprogrammi). Permette la creazione di script per automatizzare determinate azioni (backups, creazione di utenti, monitoraggio del sistema, etc.). Sono disponibili diversi tipi di shell, configurabili su una piattaforma o in base alle preferenze dell'utente. Alcuni esempi sono: @@ -251,62 +265,62 @@ Sono disponibili diversi tipi di shell, configurabili su una piattaforma o in ba :heavy_check_mark: Un sistema operativo è un insieme di programmi per la gestione delle risorse disponibili di un computer: -- [ ] Vero -- [ ] Falso +* [ ] Vero +* [ ] Falso :heavy_check_mark: Il sistema operativo è necessario per: -- [ ] Gestire la memoria fisica e virtuale -- [ ] Consentire l'accesso diretto alle periferiche -- [ ] Affidare la gestione dei compiti all'elaboratore -- [ ] Raccogliere informazioni sui programmi utilizzati o in uso +* [ ] Gestire la memoria fisica e virtuale +* [ ] Consentire l'accesso diretto alle periferiche +* [ ] Affidare la gestione dei compiti all'elaboratore +* [ ] Raccogliere informazioni sui programmi utilizzati o in uso :heavy_check_mark: Tra queste personalità, quali hanno partecipato allo sviluppo di UNIX? -- [ ] Linus Torvalds -- [ ] Ken Thompson -- [ ] Lionel Richie -- [ ] Brian Kernighan -- [ ] Andrew Stuart Tanenbaum +* [ ] Linus Torvalds +* [ ] Ken Thompson +* [ ] Lionel Richie +* [ ] Brian Kernighan +* [ ] Andrew Stuart Tanenbaum :heavy_check_mark: La nazionalità originaria di Linus Torvalds, creatore del kernel Linux, è: -- [ ] Svedese -- [ ] Finlandese -- [ ] Norvegese -- [ ] Fiamminga -- [ ] Francese +* [ ] Svedese +* [ ] Finlandese +* [ ] Norvegese +* [ ] Fiamminga +* [ ] Francese -:heavy_check_mark: Quale delle seguenti distribuzioni è la più vecchia: +:heavy_check_mark: Quale delle seguenti distribuzioni è la più antica: -- [ ] Debian -- [ ] Slackware -- [ ] RedHat -- [ ] Arch +* [ ] Debian +* [ ] Slackware +* [ ] RedHat +* [ ] Arch -:heavy_check_mark: Lo è il kernel di Linux: +:heavy_check_mark: Il kernel di Linux è: -- [ ] Multitasking -- [ ] Multiutente -- [ ] Multiprocessore -- [ ] Multi-core -- [ ] Multipiattaforma -- [ ] Aperto +* [ ] Multitasking +* [ ] Multiutente +* [ ] Multiprocessore +* [ ] Multi-core +* [ ] Multipiattaforma +* [ ] Aperto :heavy_check_mark: Il software libero è necessariamente open-source? -- [ ] Vero -- [ ] Falso +* [ ] Vero +* [ ] Falso :heavy_check_mark: Il software Open-Source è necessariamente gratuito? -- [ ] Vero -- [ ] Falso +* [ ] Vero +* [ ] Falso :heavy_check_mark: Quale delle seguenti non è una shell: -- [ ] Jason -- [ ] Jason-Bourne shell (jbsh) -- [ ] Bourne-Again shell (bash) -- [ ] C shell (csh) -- [ ] Korn shell (ksh) +* [ ] Jason +* [ ] Jason-Bourne shell (jbsh) +* [ ] Bourne-Again shell (bash) +* [ ] C shell (csh) +* [ ] Korn shell (ksh) diff --git a/docs/books/admin_guide/01-presentation.uk.md b/docs/books/admin_guide/01-presentation.uk.md index c88858cd29..050b0b3a1a 100644 --- a/docs/books/admin_guide/01-presentation.uk.md +++ b/docs/books/admin_guide/01-presentation.uk.md @@ -2,6 +2,8 @@ title: Введення в Linux --- + + # Знайомство з операційною системою Linux У цьому розділі ви дізнаєтеся про дистрибутиви GNU/Linux. @@ -10,15 +12,16 @@ title: Введення в Linux **Цілі**: В цьому розділі ви дізнаєтеся як: -:heavy_check_mark: Описати особливості та можливі архітектури операційної системи. -:heavy_check_mark: Перерахувати історію UNIX та GNU/Linux. -:heavy_check_mark: Обрати вірний дистрибутив Linux, який відповідає вашим вимогам. -:heavy_check_mark: Пояснити філософію безкоштовного програмного забезпечення та забезпечення з відкритим кодом. +:heavy_check_mark: Описати особливості та можливі архітектури операційної системи. +:heavy_check_mark: Перерахувати історію UNIX та GNU/Linux. +:heavy_check_mark: Обрати вірний дистрибутив Linux, який відповідає вашим вимогам. +:heavy_check_mark: Пояснити філософію безкоштовного програмного забезпечення та забезпечення з відкритим кодом. :heavy_check_mark: Знайти корисніть оболонки. :checkered_flag: **Загальні положення**, **linux**, **дистрибутиви** -**Знання**: :star: +**Знання**: :star: + **Складність**: :star: **Час для читання**: 10 хвилин @@ -36,11 +39,17 @@ Linux, UNIX, BSD, Windows, та MacOS це все **операційні сис У рамках цього управління ресурсами операційна система повинна: * Керувати **фізичною** або **віртуальною** пам'яттю. + * **Фізична пам'ять** складається з панелей оперативної пам'яті та кеш-пам'яті процесора, які використовуються для виконання програм. + * **Віртуальна пам’ять** – це місце на жорсткому диску (розділ **swap**), яке дозволяє розвантажувати фізичну пам'ять та зберігати поточний стан системи під час електричного вимкнення комп'ютера. + * Перехоплювати **доступ до периферійних пристроїв**. Програмне забезпечення рідко має прямий доступ до обладнання (за винятком відеокарт для дуже специфічних потреб). + * Надавати програмам належне **керування завданнями**. Операційна система відповідає за планування процесів, які займають процесор. + * **Захищати файли** від несанкціонованого доступу. + * **Збирати інформацію** про програми, які використовуються або виконуються. ![Робота операційної системи](images/operating_system.png) @@ -101,7 +110,7 @@ TODO: graphics with market share for servers and pc. Незважаючи на свою поширеність, Linux залишається відносно невідомою системою для широкої громадськості. Linux прихований у **смартфонах**, **телевізорах**, **інтернет-блоках** тощо. Майже **70% веб-сайтів** у світі розміщено на серверах Linux або UNIX! -Операційною системою Linux оснащено десь ** 3% персональних комп’ютерів** та більш ніж ** 82 % смартфонів **. Наприклад, операційна система **Android** використовує ядро Linux. +Операційною системою Linux оснащено десь ** 3% персональних комп’ютерів** та більш ніж ** 82% смартфонів **. Наприклад, операційна система **Android** використовує ядро Linux. @@ -110,12 +119,17 @@ TODO: graphics with market share for servers and pc. ### Архітектурний дизайн * **Ядро** - це перший програмний компонент. + * Це серце операційної системи Linux. * Воно керує апаратними ресурсами системи. * Інші компоненти програмного забезпечення повинні пройти через нього, щоб отримати доступ до обладнання. + * **Оболонка** - це утиліта, яка інтерпретує команди користувача та забезпечує їх виконання. + * Основні оболонки: оболонка Bourne, оболонка C, оболонка Korn і оболонка Bourne-Again (bash). + * **Програми** – це програми користувача, які включають до себе, але не обмежуються: + * Інтернет браузерами * Текстовими процесорами * Електронними таблицями @@ -158,8 +172,8 @@ Linux базується на визнаних стандартах, таких * Переносимість вартості. * Робити одну справу та робити це добре. * KISS: Keep It Simple Stupid (Бути найпростішим). -* «UNIX в основному проста операційна система, але ви повинні бути генієм, щоб зрозуміти її простоту» (__Денніс Річі__) -* «Unix зручний для користувача. Він просто не вибагливий щодо того, з якими користувачами він дружній» (__Стівен Кінг__) +* «UNIX в основному проста операційна система, але ви повинні бути генієм, щоб зрозуміти її простоту» (**Dennis Ritchie**) +* «Unix зручний для користувача. Він просто не вибагливий щодо того, з якими користувачами він дружній» (**Steven King**) ## Дистрибутиви GNU/Linux @@ -173,7 +187,7 @@ Linux базується на визнаних стандартах, таких Існує багато графічних середовищ, таких як **GNOME**, **KDE**, **LXDE**, **XFCE** тощо. Кожен знайде щось для себе, а їхня **ергономіка** не поступається системам Microsoft чи Apple. -Чому ж так мало ентузіазму щодо Linux, коли в цій системі практично **без вірусів**? Чи може це бути тому, що так багато редакторів (Adobe) і виробників (Nvidia) не є підтримують безплатні ігри та не надають версії свого програмного забезпечення чи __драйверів__ для GNU/Linux? Можливо, це страх змін, або труднощі з пошуком, де купити комп'ютер Linux, або занадто мало ігор, що поширюються під Linux. Принаймні це останнє виправдання не повинно бути істиною довго, з появою ігрового движка Steam для Linux. +Чому ж так мало ентузіазму щодо Linux, коли в цій системі практично **без вірусів**? Чи може це бути тому, що багато редакторів (Adobe) і виробників (Nvidia) не грають у безкоштовну гру та не надають версії свого програмного забезпечення чи **драйверів** для GNU/Linux? Можливо, це страх змін, або труднощі з пошуком, де купити комп'ютер Linux, або занадто мало ігор, що поширюються під Linux. Принаймні це останнє виправдання не повинно бути істиною довго, з появою ігрового движка Steam для Linux. ![Робочий стіл GNOME](images/01-presentation-gnome.png) @@ -251,62 +265,62 @@ Linux є вірним вибором для розміщення баз дани :heavy_check_mark: Операційна система - це набір програм для управління доступними ресурсами комп'ютера: -- [ ] Так -- [ ] Ні +* [ ] Так +* [ ] Ні :heavy_check_mark: Операційна система необхідна для: -- [ ] Керування фізичною та віртуальною пам’яттю -- [ ] Прямого доступу до периферійних пристроїв -- [ ] Передачі процесору субпідряду для керування завданнями -- [ ] Збору інформації про програми, які використовуються +* [ ] Керування фізичною та віртуальною пам’яттю +* [ ] Прямого доступу до периферійних пристроїв +* [ ] Передачі процесору субпідряду для керування завданнями +* [ ] Збору інформації про програми, які використовуються :heavy_check_mark: Серед цих особистостей, хто брав участь у розробці UNIX: -- [ ] Лінус Торвальдс -- [ ] Кен Томпсон -- [ ] Лайонел Річі -- [ ] Браян Керніган -- [ ] Ендрю Стюарт Таненбаум +* [ ] Лінус Торвальдс +* [ ] Кен Томпсон +* [ ] Лайонел Річі +* [ ] Браян Керніган +* [ ] Ендрю Стюарт Таненбаум :heavy_check_mark: Громадянство Лінуса Торвальдса, творця ядра Linux: -- [ ] Швецьке -- [ ] Фінське -- [ ] Норвезьке -- [ ] Фламандське -- [ ] Французьке +* [ ] Швецьке +* [ ] Фінське +* [ ] Норвезьке +* [ ] Фламандське +* [ ] Французьке :heavy_check_mark: Який із наведених дистрибутивів є найстарішим: -- [ ] Debian -- [ ] Slackware -- [ ] Red Hat -- [ ] Arch +* [ ] Debian +* [ ] Slackware +* [ ] Red Hat +* [ ] Arch :heavy_check_mark: Ядро Linux: -- [ ] Багатозадачне -- [ ] Багатокористувацьке -- [ ] Багатопроцесорне -- [ ] Багатоядерне -- [ ] Для різних платформ -- [ ] Відкрите +* [ ] Багатозадачне +* [ ] Багатокористувацьке +* [ ] Багатопроцесорне +* [ ] Багатоядерне +* [ ] Для різних платформ +* [ ] Відкрите :heavy_check_mark: Чи обов’язково вільне програмне забезпечення має відкритий код? -- [ ] Так -- [ ] Ні +* [ ] Так +* [ ] Ні :heavy_check_mark: Чи обов’язково програмне забезпечення з відкритим кодом є безкоштовним? -- [ ] Так -- [ ] Ні +* [ ] Так +* [ ] Ні :heavy_check_mark: Що з наведеного не є оболонкою: -- [ ] Jason -- [ ] Jason-Bourne shell (jbsh) -- [ ] Bourne-Again shell (bash) -- [ ] C shell (csh) -- [ ] Korn shell (ksh) +* [ ] Jason +* [ ] Jason-Bourne shell (jbsh) +* [ ] Bourne-Again shell (bash) +* [ ] C shell (csh) +* [ ] Korn shell (ksh) diff --git a/docs/books/admin_guide/03-commands.it.md b/docs/books/admin_guide/03-commands.it.md index 63b55850b4..aadc9bc1e1 100644 --- a/docs/books/admin_guide/03-commands.it.md +++ b/docs/books/admin_guide/03-commands.it.md @@ -4,6 +4,7 @@ author: Antoine Le Morvan contributors: Steven Spencer, Aditya Putta, Franco Colussi, Grammaresque --- + # Comandi per gli Utenti Linux In questo capitolo imparerete i comandi di Linux e come utilizzarli. @@ -12,13 +13,13 @@ In questo capitolo imparerete i comandi di Linux e come utilizzarli. **Obiettivi** : In questo capitolo, i futuri amministratori Linux impareranno come: -: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: **Muoversi** all'interno dell'albero di sistema. +:heavy_check_mark: **Creare** un file di testo, **visualizzare** il suo contenuto e **modificarlo**. +:heavy_check_mark: **Utilizzare** i comandi più utili di Linux. :checkered_flag: **comandi utente**, **linux** -**Conoscenza**: :star: +**Conoscenza**: :star: **Complessità**: :star: **Tempo di lettura**: 40 minuti @@ -45,12 +46,15 @@ L'utente di un sistema Linux è definito nel file `/etc/passwd`, da: * Un identificatore numerico: **UID** (User Identifier). * Un identificatore di gruppo: **GID** (Group Identifier). * Un **interprete di comandi**, ad esempio una shell, che può essere diversa da un utente all'altro. -* Una **directory di connessione**, ad esempio la __directory home__. +* Una **directory di connessione**, ad esempio la **directory home**. In altri file l'utente sarà definito da: * Una **password**, che verrà crittografata prima di essere memorizzata (`/etc/shadow`). -* Un **prompt dei comandi**, o __prompt__ login, che sarà simboleggiato da un `#` per gli amministratori e da un `$` per gli altri utenti (`/etc/profile`). +* Un **prompt dei comandi**, o accesso **prompt**, simbolizzato da un + + * `#` per gli amministratori + * e da un `$` per gli altri utenti (`/etc/profile`). A seconda della politica di sicurezza implementata sul sistema, la password dovrà contenere un certo numero di caratteri e soddisfare determinati requisiti di complessità. @@ -58,7 +62,7 @@ Tra gli interpreti di comando esistenti, la **Bourne-Again Shell** (`/bin/bash`) La directory di accesso dell'utente è per convenzione memorizzata nella directory `/home` della workstation. Conterrà i dati personali dell'utente e i file di configurazione delle sue applicazioni. Per impostazione predefinita, al login, la directory di accesso è selezionata come directory corrente. -Un'installazione di tipo workstation (con interfaccia grafica) avvia questa interfaccia sul terminale 1. Essendo Linux multiutente, è possibile connettere più utenti più volte, su diversi **terminali fisici** (TTY) o **terminali virtuali** (PTS). I terminali virtuali sono disponibili in un ambiente grafico. Un utente passa da un terminale fisico a un altro usando Alt + Fx o dalla riga di comando utilizzando CTRL + Alt + Fx. +Un'installazione di tipo workstation (con interfaccia grafica) avvia questa interfaccia sul terminale 1. Essendo Linux multiutente, è possibile connettere più utenti più volte, su diversi **terminali fisici** (TTY) o **terminali virtuali** (PTS). I terminali virtuali sono disponibili all'interno di un ambiente grafico. Un utente passa da un terminale fisico a un altro utilizzando ++alt+"Fx"++ dalla riga di comando, o utilizzando ++ctrl+alt+"Fx"++. ### La shell @@ -72,7 +76,7 @@ Una volta che l'utente è collegato a una console, la shell visualizza il **prom * Visualizza il prompt dei comandi. * etc. -La sequenza chiave CTRL + C è usata per interrompere un comando in esecuzione. +La sequenza di tasti ++ctrl+c++ è utilizzata per interrompere un comando in esecuzione. L'uso di un comando segue generalmente questa sequenza: @@ -89,13 +93,13 @@ Le **opzioni abbreviate** iniziano con un trattino (`-l`), mentre le **opzioni l È possibile raggruppare alcune opzioni brevi insieme: ```bash -$ ls -l -i -a +ls -l -i -a ``` è equivalente a: ```bash -$ ls -lia +ls -lia ``` Dopo un'opzione possono esserci più argomenti: @@ -189,7 +193,7 @@ man passwd dirà all'amministratore le opzioni, etc, del comando passwd. Mentre: ```bash -$ man 5 passwd +man 5 passwd ``` lo informerà sui file relativi al comando. @@ -481,16 +485,16 @@ Le opzioni principali del comando `ls` sono: 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` | Come l'opzione -l, ma non elenca il proprietario. | -| `-h` | Visualizza le dimensioni dei file nel formato più appropriato (byte, kilobyte, megabyte, gigabyte, ...). `h` stà per Human Readable. Deve essere utilizzato con l'opzione -l. | -| `-s` | Visualizza la dimensione assegnata di ogni file, in blocchi. Nel sistema operativo GNU/Linux, "block" è l'unità di archiviazione più piccola nel file system, un blocco è uguale a 4096Byte. | -| `-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. | +| Opzione | Informazione | +| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-d` | Visualizza le informazioni di una directory invece di elencare i suoi contenuti. | +| `-g` | Come l'opzione -l, ma non elenca il proprietario. | +| `-h` | Visualizza le dimensioni dei file nel formato più appropriato (byte, kilobyte, megabyte, gigabyte, ...). `h` stà per Human Readable. Deve essere utilizzato con l'opzione -l. | +| `-s` | Visualizza la dimensione assegnata di ogni file, in blocchi. Nel comando `ls`, la dimensione predefinita di un singolo blocco è di 1024 byte. Nel sistema operativo GNU/Linux, il "blocco" è la più piccola unità di memoria del file system e, in generale, un blocco equivale a 4096 byte. Nel sistema operativo Windows, prendendo come esempio il file system NTFS, l'unità di memorizzazione più piccola è chiamata "Cluster". La definizione del nome dell'unità di archiviazione minima può variare a seconda dei diversi file system. | +| `-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. | * Descrizione delle colonne generate dall'esecuzione del comando `ls -lia`: @@ -550,7 +554,7 @@ $ ls -lhR /var/ | grep ^\- | grep -E "[1-9]*\.[0-9]*M" Naturalmente, si consiglia vivamente di utilizzare il comando `find`. ```bash -$ find /var -size +1M -a -size -1024M -a -type f -exec ls -lh {} \; +find /var -size +1M -a -size -1024M -a -type f -exec ls -lh {} \; ``` * Mostra i permessi di una cartella: @@ -570,14 +574,14 @@ drwxr-xr-x. 2 root root 4096 17 nov. 17:48 alternatives Il comando precedente visualizzerà il contenuto della cartella (all'interno) per impostazione predefinita. Per la cartella stessa, è possibile utilizzare l'opzione `-d`. ```bash -$ ls -ld /etc +ls -ld /etc drwxr-xr-x. 69 root root 4096 18 nov. 17:05 /etc ``` * Ordina per dimensione del file, prima il più grande: ```bash -$ ls -lhS +ls -lhS ``` * formato ora/data con `-l`: @@ -601,7 +605,7 @@ $ ls -dF /etc * Nascondi alcune estensioni: ```bash -$ ls /etc --hide=*.conf +ls /etc --hide=*.conf ``` ### comando `mkdir` @@ -615,7 +619,7 @@ mkdir [-p] directory [directory] [...] Esempio: ```bash -$ mkdir /home/rockstar/work +mkdir /home/rockstar/work ``` La directory "rockstar" deve essere presente per creare la directory "work". @@ -637,7 +641,7 @@ touch [-t date] file Esempio: ```bash -$ touch /home/rockstar/myfile +touch /home/rockstar/myfile ``` | Opzione | Informazione | @@ -657,7 +661,7 @@ Il comando `rmdir` elimina una directory vuota. Esempio: ```bash -$ rmdir /home/rockstar/work +rmdir /home/rockstar/work ``` | Opzione | Informazione | @@ -716,8 +720,9 @@ mv file [file ...] destination Esempi: ```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 -$ mv /home/rockstar/file1 /home/rockstar/file2 /tmp +mv /home/rockstar/file1 /home/rockstar/file2 + +mv /home/rockstar/file1 /home/rockstar/file2 /tmp ``` | Opzioni | Informazione | @@ -728,37 +733,37 @@ $ mv /home/rockstar/file1 /home/rockstar/file2 /tmp Alcuni casi concreti ti aiuteranno a capire le difficoltà che possono sorgere: ```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 +mv /home/rockstar/file1 /home/rockstar/file2 ``` Rinomina `file1` in `file2`. Se `file2` esiste già, sostituisci il contenuto del file con `file1`. ```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 /tmp +mv /home/rockstar/file1 /home/rockstar/file2 /tmp ``` Sposta `file1` e `file2` nella cartella `/tmp`. ```bash -$ mv file1 /repexist/file2 +mv file1 /repexist/file2 ``` Sposta `file1` in `repexist` e lo rinomina `file2`. ```bash -$ mv file1 file2 +mv file1 file2 ``` `file1` è rinominato con `file2`. ```bash -$ mv file1 /repexist +mv file1 /repexist ``` Se esiste la cartella di destinazione, `file1` viene spostato in `/repexist`. ```bash -$ mv file1 /wrongrep +mv file1 /wrongrep ``` Se la directory di destinazione non esiste, `file1` viene rinominato in `wrongrep` nella directory principale. @@ -774,7 +779,7 @@ cp file [file ...] destination Esempio: ```bash -$ cp -r /home/rockstar /tmp +cp -r /home/rockstar /tmp ``` | Opzioni | Informazione | @@ -792,19 +797,19 @@ cp file1 /repexist/file2 `file1` viene copiato in `/repexist` con il nome `file2`. ```bash -$ cp file1 file2 +cp file1 file2 ``` `file1` viene copiato come `file2` in questa cartella. ```bash -$ cp file1 /repexist +cp file1 /repexist ``` Se esiste la directory di destinazione, `file1` viene copiato in `/repexist`. ```bash -$ cp file1 /wrongrep +cp file1 /wrongrep ``` Se la directory di destinazione non esiste, `file1` è copiato sotto il nome `wrongrep` nella directory principale. @@ -862,7 +867,7 @@ I comandi specifici per `less` sono: | Invio | Sposta giù di una riga. | | Spazio | Sposta giù di una pagina. | | PgUp e PgDn | Sposta su o giù di una pagina. | -| gg e G | Passa alla prima e all'ultima pagina | +| g e G | Passa alla prima e all'ultima pagina | | `/text` | Cerca il testo. | | q | Chiude il comando`less`. | @@ -877,19 +882,19 @@ cat file1 [files] Esempio 1 - Visualizzazione del contenuto di un file in output standard: ```bash -$ cat /etc/passwd +cat /etc/passwd ``` Esempio 2 - Visualizzazione del contenuto di più file in output standard: ```bash -$ cat /etc/passwd /etc/group +cat /etc/passwd /etc/group ``` Esempio 3 - Combinare il contenuto di più file in un unico file utilizzando il reindirizzamento dell'output: ```bash -$ cat /etc/passwd /etc/group > usersAndGroups.txt +cat /etc/passwd /etc/group > usersAndGroups.txt ``` Esempio 4 - Visualizzazione della numerazione di linea: @@ -1017,7 +1022,7 @@ Alcuni esempi avanzati di utilizzazione del comando `sort`: Il comando `sort` permette anche di mescolare i valori con l'opzione `-R`: ```bash -$ sort -R /etc/passwd +sort -R /etc/passwd ``` * Ordinamento degli indirizzi IP @@ -1026,7 +1031,7 @@ Un amministratore di sistema si trova ben presto di fronte all'elaborazione di i Ecco un esempio con il file `dns-client.txt`: -``` +```text 192.168.1.10 192.168.1.200 5.1.150.146 @@ -1049,14 +1054,15 @@ Il comando `sort` sa come rimuovere i duplicati dall'output del file utilizzando Ecco un esempio con il file `colours.txt`: -``` +```text Red Green Blue Red Pink ``` -``` + +```text $ sort -u colours.txt Blue Green @@ -1070,7 +1076,7 @@ Il comando `sort` sa come riconoscere le dimensioni dei file, da comandi come `l Ecco un esempio con il file `size.txt`: -``` +```text 1.7G 18M 69K @@ -1136,7 +1142,7 @@ Se la cartella di ricerca non è specificata, il comando `find` effettuerà la r È possibile utilizzare l'opzione `-exec` del comando `find` per eseguire un comando su ogni riga del risultato: ```bash -$ find /tmp -name *.txt -exec rm -f {} \; +find /tmp -name *.txt -exec rm -f {} \; ``` Il comando precedente cerca tutti i file nella cartella `/tmp` denominati `*.txt` e li elimina. @@ -1203,16 +1209,17 @@ root:x:0:0:root:/root:/bin/bash | `-w` | Cerca la parola esatta. | Il comando `grep` restituisce la riga completa contenente la stringa cercata. + * Il carattere speciale `^` viene utilizzato per cercare una stringa all'inizio di una riga. -* Il carattere speciale `$` viene utilizzato per cercare una stringa alla fine di una riga. +* Il carattere speciale `$` cerca una stringa alla fine di una riga. -```bash -$ grep -w "^root" /etc/passwd -``` + ```bash + grep -w "^root" /etc/passwd + ``` !!! Note "Nota" - Questo comando è molto potente e si raccomanda vivamente di consultare il suo manuale. Ha numerosi derivati. + Questo comando è molto potente e si consiglia di consultarne il manuale. Ha molti derivati. È possibile cercare una stringa in un albero di file con l'opzione `-R`. @@ -1262,7 +1269,7 @@ $ find /home -name "test[123]*" !!! Warning "Attenzione" - Non confondete i meta-caratteri della shell con i meta-caratteri delle espressioni regolari. Il comando `grep` utilizza meta-caratteri di espressione regolare. + Non confondete i meta-caratteri della shell con i meta-caratteri delle espressioni regolari. Il comando `grep' utilizza meta-caratteri delle espressioni regolari. ## Reindirizzamenti e pipes @@ -1288,7 +1295,7 @@ Questi flussi puntano ai file delle periferiche, ma poiché tutto è un file in È possibile reindirizzare il flusso di input da un altro file con il carattere `<` o `<<`. Il comando leggerà il file invece della tastiera: ```bash -$ ftp -in serverftp << ftp-commands.txt +ftp -in serverftp << ftp-commands.txt ``` !!! Note "Nota" @@ -1341,13 +1348,13 @@ L'output standard può essere reindirizzato ad altri file usando il carattere `> Il semplice reindirizzamento `>` sovrascrive il contenuto del file di output: ```bash -$ date +%F > date_file +date +%F > date_file ``` Quando viene utilizzato il carattere `>>`, indica che il risultato del comando viene aggiunto al contenuto del file. ```bash -$ date +%F >> date_file +date +%F >> date_file ``` In entrambi i casi, il file viene creato automaticamente quando non esiste. @@ -1355,8 +1362,9 @@ In entrambi i casi, il file viene creato automaticamente quando non esiste. L'output di errore standard può anche essere reindirizzato ad un altro file. Questa volta sarà necessario specificare il numero del canale (che può essere omesso per i canali 0 e 1): ```bash -$ ls -R / 2> errors_file -$ ls -R / 2>> errors_file +ls -R / 2> errors_file + +ls -R / 2>> errors_file ``` ### Esempi di reindirizzamento @@ -1364,19 +1372,19 @@ $ ls -R / 2>> errors_file Reindirizzamento di 2 output verso 2 file: ```bash -$ ls -R / >> ok_file 2>> nok_file +ls -R / >> ok_file 2>> nok_file ``` Reindirizzamento di 2 output a un singolo file: ```bash -$ ls -R / >> log_file 2>&1 +$ ls -R / >> ok_file 2>> nok_file ``` Reindirizzamento del *stderr* a un "pozzo senza fondo" (`/dev/null`): ```bash -$ ls -R / 2>> /dev/null +ls -R / 2>> /dev/null ``` Quando entrambi i flussi di uscita vengono reindirizzati, nessuna informazione viene visualizzata sullo schermo. Per utilizzare sia il reindirizzamento dell'uscita che il mantenimento della visualizzazione, è necessario utilizzare il comando `tee`. @@ -1398,31 +1406,31 @@ I comandi particolarmente utilizzati dopo una pipe sono i filtri. Mostra solo l'inizio: ```bash -$ ls -lia / | head +ls -lia / | head ``` Mostra solo la fine: ```bash -$ ls -lia / | tail +ls -lia / | tail ``` Ordina il risultato: ```bash -$ ls -lia / | sort +ls -lia / | sort ``` Conta il numero di parole / caratteri: ```bash -$ ls -lia / | wc +ls -lia / | wc ``` Cerca una stringa nel risultato: ```bash -$ ls -lia / | grep fichier +ls -lia / | grep fichier ``` ## Punti Speciali @@ -1434,8 +1442,9 @@ Il comando `tee` viene utilizzato per reindirizzare l'output standard di un coma Viene combinato con la pipe `|` per ricevere come input l'output del comando da reindirizzare: ```bash -$ ls -lia / | tee fic -$ cat fic +ls -lia / | tee fic + +cat fic ``` L'opzione `-a` aggiunge al file invece di sovrascriverlo. @@ -1447,13 +1456,13 @@ L'uso di **alias** è un modo per chiedere alla shell di ricordare un particolar Per esempio: ```bash -$ ll +ll ``` sostituirà il comando: ```bash -$ ls -l +ls -l ``` Il comando `alias` elenca gli alias per la sessione corrente. Gli alias sono stabiliti per impostazione predefinita sulle distribuzioni Linux. Qui, gli alias per un server Rocky Linux: @@ -1476,7 +1485,7 @@ Per un uso permanente, devono essere creati nel: !!! Warning "Attenzione" - Particolare attenzione deve essere prestata quando si utilizzano alias che possono essere potenzialmente pericolosi! Ad esempio, un alias creato senza una conoscenza di base di amministratore: + Occorre prestare particolare attenzione all'uso degli alias, che possono essere potenzialmente pericolosi! Ad esempio, un alias creato all'insaputa dell'amministratore: ```bash alias cd='rm -Rf' @@ -1487,13 +1496,13 @@ Il comando `unalias` ti consente di eliminare gli alias. Per eliminare un singolo alias: ```bash -$ unalias ll +unalias ll ``` Per eliminare tutti gli alias: ```bash -$ unalias -a +unalias -a ``` Per disabilitare temporaneamente un alias, la combinazione è `\`. @@ -1501,7 +1510,7 @@ Per disabilitare temporaneamente un alias, la combinazione è `\`. Ad esempio se digitiamo: ```bash -$ type ls +type ls ``` potrebbe restituire quanto segue: @@ -1588,7 +1597,7 @@ Il carattere `;` concatena i comandi. Una volta che l'utente ha premuto INVIO, tutti i comandi verranno eseguiti in sequenza nell'ordine di immissione.

-
$ ls /; cd /home; ls -lia; cd /
+
ls /; cd /home; ls -lia; cd /
 

@@ -1669,4 +1678,4 @@ Una volta che l'utente ha premuto INVIO, tutti i comandi verranno ese
  • [ ] ls -R / 2> errors.log 2>&1
  • - + diff --git a/docs/books/admin_guide/03-commands.uk.md b/docs/books/admin_guide/03-commands.uk.md index 165cdb7d20..f8a4eec330 100644 --- a/docs/books/admin_guide/03-commands.uk.md +++ b/docs/books/admin_guide/03-commands.uk.md @@ -4,6 +4,7 @@ author: Antoine Le Morvan contributors: Steven Spencer, Aditya Putta, tianci li, Grammaresque, Ganna Zhyrnova --- + # Команди для користувачів Linux У цьому розділі ви дізнаєтеся про команди Linux і про те, як ними користуватися. @@ -12,13 +13,13 @@ contributors: Steven Spencer, Aditya Putta, tianci li, Grammaresque, Ganna Zhyrn **Цілі**: у цьому розділі майбутні адміністратори Linux дізнаються, як: -:heavy_check_mark: **Робити переміщення** в системному дереві. -:heavy_check_mark: **Створювати** текстовий файл, **відображати** його вміст і ** змінювати** його. +:heavy_check_mark: **Робити переміщення** в системному дереві. +:heavy_check_mark: **Створювати** текстовий файл, **відображати** його вміст і ** змінювати** його. :heavy_check_mark: **Використовувати** найкорисніші команди Linux. :checkered_flag: **команди користувача**, **linux** -**Знання**: :star: +**Знання**: :star: **Складність**: :star: **Час для читання**: 40 хвилин @@ -45,12 +46,15 @@ contributors: Steven Spencer, Aditya Putta, tianci li, Grammaresque, Ganna Zhyrn * Цифровий ідентифікатор: **UID** (ідентифікатор користувача). * Ідентифікатор групи: **GID** (ідентифікатор групи). * **Інтерпретатор команд**, наприклад, оболонка, яка може відрізнятися для різних користувачів. -* **Каталог підключення**, наприклад, __домашній каталог__. +* **Каталог підключення**, наприклад, **домашній каталог**. В інших файлах користувача буде визначено: * **Паролем**, який шифрується перед збереженням (`/etc/shadow`). -* **Командним рядком** або __запитом__ для входу, який позначається `#` для адміністратора та `$` для інших користувачів (`/etc/profile`). +* **Командний рядок** або **запит** для входу, який символізується + + * `#` для адміністраторів + * та `$` для інших користувачів (`/etc/profile`). Залежно від політики безпеки, реалізованої в системі, пароль потребуватиме певної кількості символів і відповідатиме певним вимогам до складності. @@ -58,7 +62,7 @@ contributors: Steven Spencer, Aditya Putta, tianci li, Grammaresque, Ganna Zhyrn Каталог входу користувача за замовченням зберігається в каталозі `/home` робочої станції. Він міститиме персональні дані користувача та конфігураційні файли його програм. За замовчуванням під час входу поточним каталогом обирається каталог входу. -Інсталяція типу робочої станції (з графічним інтерфейсом) запускає цей інтерфейс на терміналі 1. Оскільки Linux є багатокористувацьким, можна підключити кількох користувачів кілька разів на різних **фізичних терміналах** (TTY) або **віртуальних терміналах ** (PTS). Віртуальні термінали доступні в графічному середовищі. Користувач перемикається з одного фізичного терміналу на інший за допомогою Alt + Fx із командного рядка або за допомогою CTRL + Alt + Fx. +Інсталяція типу робочої станції (з графічним інтерфейсом) запускає цей інтерфейс на терміналі 1. Оскільки Linux є багатокористувацьким, можна підключити кількох користувачів кілька разів на різних **фізичних терміналах** (TTY) або **віртуальних терміналах ** (PTS). Віртуальні термінали доступні в графічному середовищі. Користувач перемикається з одного фізичного терміналу на інший за допомогою ++alt+"Fx"++ із командного рядка або за допомогою ++ctrl+alt+"Fx"++. ### Оболонка @@ -72,7 +76,7 @@ contributors: Steven Spencer, Aditya Putta, tianci li, Grammaresque, Ganna Zhyrn * Відображає командний рядок. * Тощо. -Послідовність клавіш CTRL + C використовується для переривання виконання команди. +Послідовність клавіш ++ctrl+c++ використовується для переривання виконання команди. Зазвичай команда використовується в такій послідовності: @@ -89,19 +93,19 @@ command [option(s)] [argument(s)] Можна групувати кілька коротких опцій разом: ```bash -$ ls -l -i -a +ls -l -i -a ``` еквівалентно до: ```bash -$ ls -lia +ls -lia ``` Після параметра може бути кілька аргументів: ```bash -$ ls -lia /etc /home /var +ls -lia /etc /home /var ``` У літературі термін «опція» еквівалентний терміну «параметр», який частіше використовується в програмуванні. Необов’язкова сторона параметра або аргументу позначається у квадратних дужках `[` і `]`. Якщо можливий більше ніж один варіант, вертикальна смуга, яка називається "канал", розділяє їх `[a|e|i]`. @@ -189,7 +193,7 @@ man passwd розповість адміністратору про команду passwd, її параметри тощо. Як : ```bash -$ man 5 passwd +man 5 passwd ``` повідомить його про файли, пов'язані з командою. @@ -481,16 +485,16 @@ $ ls /home Команда `ls`, однак, має багато варіантів (див. `man`): -| Опція | Опис | -| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `-d` | Відображає інформацію про каталог замість того, щоб показати його вміст. | -| `-g` | Як параметр -l, але не вказує власника. | -| `-h` | Відображає розміри файлу у найбільш доцільному форматі (байт, кілобайт, мегабайт, ...). `h` означає «читабельний». Потребує використання з -l опцією. | -| `-s` | Відображає розмір виділеного файлу в блоках. В операційній системі GNU/Linux «блок» — це найменша одиниця зберігання у файловій системі, один блок дорівнює 4096 байтам. | -| `-А` | Відображає усі файли у каталозі за винятком `.` і `..` | -| `-R` | Відображає вміст підкаталогів рекурсивно. | -| `-F` | Відображає тип файлів. Виводить `/` для каталогу, `*` для виконуваних файлів, `@` для символічного посилання, і нічого для текстового файлу. | -| `-X` | Сортує файли за їх розширеннями. | +| Опція | Опис | +| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-d` | Відображає інформацію про каталог замість того, щоб показати його вміст. | +| `-g` | Як параметр -l, але не вказує власника. | +| `-h` | Відображає розміри файлу у найбільш доцільному форматі (байт, кілобайт, мегабайт, ...). `h` означає «читабельний». Потребує використання з -l опцією. | +| `-s` | Відображає розмір виділеного файлу в блоках. У команді `ls` розмір окремого блоку за замовчуванням становить 1024 байти. В операційній системі GNU/Linux «блок» є найменшою одиницею зберігання у файловій системі, і загалом один блок дорівнює 4096 байтам. В операційній системі Windows, беручи за приклад файлову систему NTFS, її найменша одиниця зберігання називається «Кластер». Визначення мінімального імені одиниці зберігання може відрізнятися залежно від різних файлових систем. | +| `-А` | Відображає усі файли у каталозі за винятком `.` і `..` | +| `-R` | Відображає вміст підкаталогів рекурсивно. | +| `-F` | Відображає тип файлів. Виводить `/` для каталогу, `*` для виконуваних файлів, `@` для символічного посилання, і нічого для текстового файлу. | +| `-X` | Сортує файли за їх розширеннями. | * Опис стовпців, згенерованих виконанням команди `ls -lia`: @@ -550,7 +554,7 @@ $ ls -lhR /var/ | grep ^\- | grep -E "[1-9]*\.[0-9]*M" Звичайно, ми рекомендуємо використовувати команду `find`. ```bash -$ find /var -size +1M -a size -1024M -type f -exec -lh {} \; +find /var -size +1M -a -size -1024M -a -type f -exec ls -lh {} \; ``` * Показати права на папку: @@ -570,14 +574,14 @@ drwxr-xr-x. 2 корінь з 4096 17 Новин. 17:48 альтернатив Наведена вище команда відобразить вміст папки (всередині) за замовчуванням. Для самої папки, ви можете використовувати опцію `-d`. ```bash -$ ls -ld /etc +ls -ld /etc drwxr-xr-x. 69 root root 4096 18 nov. 17:05 /etc ``` * Сортувати за розміром файлу, спочатку найбільший: ```bash -$ ls -lhS +ls -lhS ``` * формат часу /дати з `-l`: @@ -601,7 +605,7 @@ $ ls -dF /etc * Приховати деякі розширення: ```bash -$ ls /etc --hide=*.conf +ls /etc --hide=*.conf ``` ### Команда `mkdir` @@ -615,7 +619,7 @@ mkdir [-p] каталог [directory] [...] Наприклад: ```bash -$ mkdir /home/rockstar/work +mkdir /home/rockstar/work ``` Має існувати каталог "rockstar", щоб створити каталог "work". @@ -637,7 +641,7 @@ touch [-t date] file Наприклад: ```bash -$ touch /home/rockstar/myfile +touch /home/rockstar/myfile ``` | Опція | Опис | @@ -657,7 +661,7 @@ $ touch /home/rockstar/myfile Наприклад: ```bash -$ rmdir /home/rockstar/work +rmdir /home/rockstar/work ``` | Опція | Опис | @@ -716,8 +720,9 @@ $ rm -f -- -hard-hard Приклад: ```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 -$ mv /home/rockstar/file1 /home/rockstar/file2 /tmp +mv /home/rockstar/file1 /home/rockstar/file2 + +mv /home/rockstar/file1 /home/rockstar/file2 /tmp ``` | Опції | Опис | @@ -728,37 +733,37 @@ $ mv /home/rockstar/file1 /home/rockstar/file2 /tmp Кілька конкретних випадків допоможуть вам зрозуміти труднощі, що можуть виникнути: ```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 +mv /home/rockstar/file1 /home/rockstar/file2 ``` Перейменовує `file1` на `file2`. Якщо `file2` вже існує, замінити вміст файлу на `file1`. ```bash -$ mv /home/rockstar/file1 /home/rockstar/file2 /tmp +mv /home/rockstar/file1 /home/rockstar/file2 /tmp ``` Переміщення `file1` і `file2` до папки `/tmp`. ```bash -$ mv file1 /repexist/file2 +mv file1 /repexist/file2 ``` Переміщує `file1` у `repexist` і перейменовує його на `file2`. ```bash -$ mv file1 file2 +mv file1 file2 ``` `file1` перейменовано на `file2`. ```bash -$ mv file1 /repexist +mv file1 /repexist ``` Якщо цільовий каталог існує, `file1` переміщується до `/repexist`. ```bash -$ mv file1 /wrongrep +mv file1 /wrongrep ``` Якщо цільовий каталог не існує, `file1` буде перейменовано на `wrongrep` у кореневому каталозі. @@ -774,7 +779,7 @@ cp file [file ...] destination Наприклад: ```bash -$ cp -r /home/rockstar /tmp +cp -r /home/rockstar /tmp ``` | Опції | Опис | @@ -792,19 +797,19 @@ cp file1 /repexist/file2 `file1` скопійовано до `/repexist` під назвою `file2`. ```bash -$ cp file1 file2 +cp file1 file2 ``` `file1` копіюється як `file2` у цю теку. ```bash -$ cp file1 /repexist +cp file1 /repexist ``` Якщо цільовий каталог існує, `file1` копіюється в `/repexist`. ```bash -$ cp file1 /wrongrep +cp file1 /wrongrep ``` Якщо директорії призначення не існує, `file1` копіюється під назвою `wrongrep` в кореневий каталог. @@ -862,7 +867,7 @@ less file1 [files] | Enter | Посунути вниз на один рядок. | | Space | Посунути на одну сторінку. | | PgUp і PgDn | Посунути вгору або вниз одну сторінку. | -| gg і G | Посунути на перші та останні сторінки | +| g та G | Посунути на перші та останні сторінки | | `/text` | Пошук тексту. | | q | Закриває команду `less`. | @@ -877,19 +882,19 @@ cat file1 [files] Приклад 1. Відображення вмісту файлу в стандартному виводі: ```bash -$ cat /etc/passwd +cat /etc/passwd ``` Приклад 2. Відображення вмісту кількох файлів у стандартному виводі: ```bash -$ cat /etc/passwd /etc/group +cat /etc/passwd /etc/group ``` Приклад 3. Об’єднання вмісту кількох файлів в один файл за допомогою переспрямування виводу: ```bash -$ cat /etc/passwd /etc/group > usersAndGroups.txt +cat /etc/passwd /etc/group > usersAndGroups.txt ``` Приклад 4 - Відображення нумерації рядків: @@ -1017,7 +1022,7 @@ polkitd:x:998:996:User for polkitd:/sbin/nologin Команда `sort` також дозволяє перетасувати значення за допомогою параметра `-R`: ```bash -$ sort -R /etc/passwd +sort -R /etc/passwd ``` * Сортування IP-адрес @@ -1026,7 +1031,7 @@ $ sort -R /etc/passwd Ось приклад з файлом `dns-client.txt`: -``` +```text 192.168.1.10 192.168.1.200 5.1.150.146 @@ -1049,14 +1054,15 @@ $ sort -nr dns-client.txt Ось приклад із файлом `colours.txt`: -``` +```text Red Green Blue Red Pink ``` -``` + +```text $ sort -u colours.txt Blue Green @@ -1070,7 +1076,7 @@ Red Приклад з файлом `size.txt`: -``` +```text 1.7G 18M 69K @@ -1136,7 +1142,7 @@ wc [-l] [-m] [-w] файл [files] Можна використати опцію `-exec` команди `find`, щоб виконати команду в кожному рядку результату: ```bash -$ find /tmp -name *.txt -exec rm -f {} \; +find /tmp -name *.txt -exec rm -f {} \; ``` Попередня команда шукає всі файли в каталозі `/tmp` під назвою `*.txt` і видаляє їх. @@ -1203,12 +1209,13 @@ root:x:0:0:root:/bin/bash | `-w` | Пошук точного слова. | Команда `grep` повертає повний рядок, що містить рядок, який ви шукаєте. + * Спеціальний символ `^` використовується для пошуку рядка на початку рядка. * Спеціальний символ `$` шукає рядок в кінці рядка. -```bash -$ grep -w "^root" /etc/passwd -``` + ```bash + grep -w "^root" /etc/passwd + ``` !!! Note "Примітка" @@ -1288,7 +1295,7 @@ $ find /home -name "test[123]*" Можна перенаправити вхідний потік з іншого файлу за допомогою символу `<` або `<<`. Команда прочитає файл замість клавіатури: ```bash -$ ftp -in serverftp << ftp-commands.txt +ftp -in serverftp << ftp-commands.txt ``` !!! Note "Примітка" @@ -1329,9 +1336,9 @@ STOP ```bash $ wc -l .bash_profile -27. ash_profile # кількість рядків слідує імені файлу -$ wc -l < . ash_profile -27 # повертає тільки кількість рядків +27 .bash_profile # the number of lines is followed by the file name +$ wc -l < .bash_profile +27 # returns only the number of lines ``` ### Перенаправлення виводу @@ -1341,13 +1348,13 @@ $ wc -l < . ash_profile Просте переспрямування `>` перезаписує вміст вихідного файлу: ```bash -$ date +%F > date_file +date +%F > date_file ``` Якщо використовується символ `>>`, це вказує на те, що вихідний результат команди додається до вмісту файлу. ```bash -$ date +%F >> date_file +$ date +%F > date_file ``` В обох випадках файл створюється автоматично, коли він не існує. @@ -1355,8 +1362,9 @@ $ date +%F >> date_file Стандартний вивід помилки також може бути перенаправлений в інший файл. Цього разу буде необхідно вказати номер каналу (який може бути опущений для каналів 0 і 1): ```bash -$ ls -R / 2> errors_file -$ ls -R / 2>> errors_file +ls -R / 2> errors_file + +ls -R / 2>> errors_file ``` ### Приклади перенаправлення @@ -1364,19 +1372,19 @@ $ ls -R / 2>> errors_file Перенаправлення 2 виходів у 2 файли: ```bash -$ ls -R / >> ok_file 2>> nok_file +ls -R / >> ok_file 2>> nok_file ``` Перенаправлення 2 виходів в один файл: ```bash -$ ls -R / >> log_file 2>&1 +ls -R / >> log_file 2>&1 ``` -Переспрямування *stderr* до «бездонної ями» (`/dev/null`): +Переспрямування _stderr_ до «бездонної ями» (`/dev/null`): ```bash -$ ls -R / 2>> /dev/null +ls -R / 2>> /dev/null ``` Коли обидва вихідні потоки перенаправляються, інформація на екрані не відображається. Щоб використовувати як переспрямування виводу, так і зберегти відображення, вам доведеться використати команду `tee`. @@ -1398,31 +1406,31 @@ $ ls -R / 2>> /dev/null Відображати лише початок: ```bash -$ ls -lia / | head +ls -lia / | head ``` Відобразити тільки кінець: ```bash -$ ls -lia / | tail +ls -lia / | tail ``` Сортувати результат: ```bash -$ ls -lia / | sort +ls -lia / | sort ``` Порахувати кількість слів/символів: ```bash -$ ls -lia / | wc +ls -lia / | wc ``` Шукати рядок в результаті: ```bash -$ ls -lia / | grep fichier +ls -lia / | grep fichier ``` ## Особливі моменти @@ -1434,8 +1442,9 @@ $ ls -lia / | grep fichier Він поєднується з каналом `|`, щоб отримати як вхідні дані команди, яку потрібно перенаправити: ```bash -$ ls -lia / | tee fic -$ cat fic +ls -lia / | tee fic + +cat fic ``` Параметр `-a` додає до файлу, а не перезаписує його. @@ -1447,13 +1456,13 @@ $ cat fic Наприклад: ```bash -$ ll +ll ``` замінить команду: ```bash -$ ls -l +ls -l ``` Команда `alias` містить список псевдонімів для поточного сеансу. У дистрибутивах Linux псевдоніми встановлюються за замовчуванням. Тут псевдоніми для сервера Rocky: @@ -1476,7 +1485,7 @@ alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-ti !!! warning "Важливо" - Слід бути особливо обережним при використанні псевдонімів, які можуть бути потенційно небезпечними! Наприклад, псевдонім, створений без знань адміністратора: + Псевдоніми визначені лише тимчасово на час сеансу користувача! Наприклад, псевдонім, створений без знань адміністратора: ```bash alias cd='rm -Rf' @@ -1487,13 +1496,13 @@ alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-ti Щоб видалити один псевдонім: ```bash -$ unalias ll +unalias ll ``` Щоб видалити всі псевдоніми: ```bash -$ unalias -a +unalias -a ``` Щоб тимчасово вимкнути псевдонім, використовуйте комбінацію `\<alias name>`. @@ -1501,7 +1510,7 @@ $ unalias -a Наприклад, якщо ми робимо: ```bash -$ type ls +type ls ``` може повернути наступне: @@ -1513,10 +1522,10 @@ ls is an alias to « ls -rt » Тепер, коли це відомо, ми можемо побачити результати використання псевдоніма або одноразового вимкнення за допомогою `\`, виконавши наступне: ```bash -$ ls file* # order by time -file3.txt file2.txt file1.txt -$ \ls file* # order by name -file1.txt file2.txt file3.txt file3.txt +$ ls file* # order by time +file3.txt file2.txt file1.txt +$ \ls file* # order by name +file1.txt file2.txt file3.txt ``` ### Псевдоніми та корисні функції @@ -1588,7 +1597,7 @@ none on /proc/sys/fs/binfmt_misc type binfmt_misc (r Усі команди запускатимуться послідовно в порядку введення, коли користувач натисне ENTER.

    -
    $ ls /; cd /home; ls -lia; cd /
    +
    ls /; cd /home; ls -lia; cd /
     

    @@ -1669,4 +1678,4 @@ none on /proc/sys/fs/binfmt_misc type binfmt_misc (r
  • [ ] ls -R / 2> errors.log 2>&1
  • - + diff --git a/docs/books/admin_guide/04-advanced-commands.it.md b/docs/books/admin_guide/04-advanced-commands.it.md index 189661009c..8e1fb603bb 100644 --- a/docs/books/admin_guide/04-advanced-commands.it.md +++ b/docs/books/admin_guide/04-advanced-commands.it.md @@ -10,13 +10,11 @@ I comandi avanzati offrono una maggiore personalizzazione e controlli in situazi **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 utili non trattati nel capitolo precedente. :heavy_check_mark: alcuni comandi avanzati. :checkered_flag: **comandi utente**, **Linux** -**Conoscenza**: :star: -**Complessità**: :star: :star: :star: +**Conoscenza**: :star: **Complessità**: :star: :star: :star: **Tempo di lettura**: 20 minuti @@ -26,9 +24,9 @@ I comandi avanzati offrono una maggiore personalizzazione e controlli in situazi Il comando `uniq` è un comando molto potente, usato con il comando `sort`, soprattutto per l'analisi dei file di registro. Ti consente di ordinare e visualizzare le voci rimuovendo i duplicati. -Per illustrare come funziona il comando `uniq`, usiamo un file `firstnames.txt` contenente un elenco di nomi primi: +Per illustrare il funzionamento del comando `uniq`, utilizziamo un file `firstnames.txt` contenente un elenco di nomi: -``` +```text antoine xavier steven @@ -45,7 +43,7 @@ steven Senza argomenti, il comando `uniq` non visualizza le righe identiche che si susseguono nel file `firstnames.txt`: -``` +```bash $ sort firstnames.txt | uniq antoine patrick @@ -55,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 righe che compaiono almeno due volte nel file, utilizzare l'opzione `-d`: -``` +```bash $ sort firstnames.txt | uniq -d antoine steven @@ -71,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 @@ -84,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 @@ -92,7 +90,7 @@ $ sort firstnames.txt | uniq -c 2 xavier ``` -``` +```bash $ sort firstnames.txt | uniq -cd 3 antoine 2 steven @@ -107,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 @@ -116,9 +114,9 @@ xargs 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'input dell'utente, vale a dire: +Il comando `xargs` attende un input dallo standard input **stdin**. Sono state inserite tre linee. La fine dell'input dell'utente è specificata in `xargs` dalla sequenza di tasti ++ctrl+d++. `xargs` esegue quindi il comando predefinito `echo` seguito dai tre argomenti corrispondenti all'input dell'utente, vale a dire: -``` +```bash $ echo "use" "of" "xargs" use of xargs ``` @@ -127,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 @@ -142,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 argomenti multipli, come nel caso del comando `find`? -``` +```bash $ xargs find /var/log -name *.old *.log @@ -151,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 @@ -177,7 +175,7 @@ $ xargs -L 1 find /var/log -name Per specificare entrambi gli argomenti sulla stessa riga, utilizzare l'opzione `-n 1`: -``` +```bash $ xargs -n 1 find /var/log -name *.old *.log /var/log/dmesg.old @@ -195,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 @@ -206,8 +204,8 @@ La caratteristica speciale del comando `xargs` è che posiziona l'argomento di i Utilizzando l'esempio del comando `cp`, per copiare un elenco di file in una directory, questo elenco di file verrà aggiunto alla fine del comando... ma ciò che il comando `cp` si aspetta alla fine del comando è la destinazione. Per farlo, si può usare l'opzione `-I` per inserire gli argomenti di input in un punto diverso dalla fine della riga. -``` -$ find /var/log -type f -name "*.log" | xargs -I % cp % /root/backup +```bash +find /var/log -type f -name "*.log" | xargs -I % cp % /root/backup ``` L'opzione `-I` consente di specificare un carattere (il carattere `%` nell'esempio precedente) in cui verranno inseriti i file di input di `xargs`. @@ -220,50 +218,51 @@ Il pacchetto `yum-utils` è una raccolta di utilità, realizzate per `yum` da va Mentre `yum` è stato sostituito da `dnf` in Rocky Linux 8, il nome del pacchetto è rimasto `yum-utils`, sebbene possa essere installato anche come `dnf-utils`. Queste sono le classiche utilities YUM implementate come shims CLI sopra a DNF per mantenere la retrocompatibilità con `yum-3`. -Ecco alcuni esempi di utilizzo: +Ecco alcuni esempi di queste utilità. -* comando `repoquery` +### Comando `repoquery` Il comando `repoquery` viene utilizzato per interrogare i pacchetti nel repository. Esempi di utilizzo: - * Visualizza le dipendenze di un pacchetto (può essere un pacchetto software che è stato installato o non è stato installato), equivalente a `dnf deplist ` - ``` - repoquery --requires - ``` - - * Visualizza i file forniti da un pacchetto installato (non funziona per i pacchetti che non sono installati), Equivalente a `rpm -ql ` - - ``` - $ 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 - … - ``` - -* comando `yumdownloader`: +* Visualizzare le dipendenze di un pacchetto (può essere un pacchetto software che è stato installato o non installato), equivalente a `dnf deplist ` + +```bash +repoquery --requires +``` + +* Mostra i file forniti da un pacchetto installato (non funziona per i pacchetti che non sono installati), equivalente a `rpm -ql ` + +```bash +$ 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 +… +``` + +### Comando `yumdownloader` Il comando `yumdownloader` scarica i pacchetti RPM dai repository. Equivalente a `dnf scaricare --downloadonly --downloaddir ./ package-name` @@ -273,9 +272,9 @@ Il comando `yumdownloader` scarica i pacchetti RPM dai repository. Equivalente Esempio: `yumdownloader` scaricherà il pacchetto rpm _repoquery_ e tutte le sue dipendenze: -``` +```bash $ yumdownloader --destdir /var/tmp --resolve samba -o +or $ dnf download --downloadonly --downloaddir /var/tmp --resolve samba ``` @@ -294,17 +293,33 @@ Il pacchetto `psmisc` contiene utilità per la gestione dei processi di sistema: Esempi: -``` -Questo comando è molto utile per creare rapidamente un repository locale di alcuni rpm! -``` - -``` +```bash +$ 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}] +``` + +```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 ``` @@ -322,13 +337,13 @@ Esempi: * Visualizza la fine del file `/etc/passwd` ogni 5 secondi: -``` -$ watch -n 5 tail -n 3 /etc/passwd +```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 @@ -338,12 +353,88 @@ sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin * Monitoraggio del numero di file in una cartella: -``` -$ watch -n 1 'ls -l | wc -l' +```bash +watch -n 1 'ls -l | wc -l' ``` * Mostra un orologio: +```bash +watch -t -n 1 date +``` + +## Comando `install` + +Contrariamente a quanto potrebbe suggerire il nome, il comando `install` non viene usato per installare nuovi pacchetti. + +Questo comando combina la copia dei file (`cp`) e la creazione di cartelle (`mkdir`), con la gestione dei diritti (`chmod`, `chown`) e altre utili funzionalità (come i backup). + +```bash +install source dest +install -t directory source [...] +install -d directory +``` + +Opzioni: + +| Opzioni | Osservazioni                           | +| -------------------------- | -------------------------------------------------------------------- | +| `-b` o `--backup[=suffix]` | crea un backup del file di destinazione. | +| `-d`     | tratta gli argomenti come nomi di cartelle.               | +| `-D`     | crea tutti i componenti principali, prima di copiare SOURCE in DEST. | +| `-g` e `-o`     | imposta la proprietà.               | +| `-m`     | imposta le autorizzazioni.               | +| `-p`     | preservare i timestamp dei file sorgente.               | +| `-t` | copia tutti gli argomenti di origine nella directory. | + +!!! note "Nota" + + Esistono opzioni per la gestione del contesto SELinux (vedere la pagina del manuale). + +Esempi: + +Creare una cartella con l'opzione `-d`: + +```bash +install -d ~/samples +``` + +Copiare un file da una posizione di origine in una cartella: + +```bash +install src/sample.txt ~/samples/ ``` -$ watch -t -n 1 date + +Questi due ordini si sarebbero potuti eseguire con un unico comando: + +```bash +$ install -v -D -t ~/samples/ src/sample.txt +install: creating directory '~/samples' +'src/sample.txt' -> '~/samples/sample.txt' +``` + +Questo comando fa già risparmiare tempo, ora combiniamolo con la gestione dei proprietari, dei gruppi di proprietari e dei diritti: + +```bash +sudo install -v -o rocky -g users -m 644 -D -t ~/samples/ src/sample.txt +``` + + !!! note "Nota" + + In questo caso è necessario `sudo` per apportare modifiche alle proprietà. + +È anche possibile creare un backup dei file esistenti grazie all'opzione `-b`: + +```bash +$ install -v -b -D -t ~/samples/ src/sample.txt +'src/sample.txt' -> '~/samples/sample.txt' (archive: '~/samples/sample.txt~') +``` + +Come si può vedere, il comandodi `install` crea un file di backup con una tilde `~` aggiunta al nome del file originale. + +Il suffisso può essere specificato grazie all'opzione `-S`: + +```bash +$ install -v -b -S ".bak" -D -t ~/samples/ src/sample.txt +'src/sample.txt' -> '~/samples/sample.txt' (archive: '~/samples/sample.txt.bak') ``` diff --git a/docs/books/admin_guide/06-users.it.md b/docs/books/admin_guide/06-users.it.md index 74beccb343..62c71e5da3 100644 --- a/docs/books/admin_guide/06-users.it.md +++ b/docs/books/admin_guide/06-users.it.md @@ -13,7 +13,7 @@ In questo capitolo imparerai come gestire gli utenti. :heavy_check_mark: aggiungere, eliminare o modificare un **utente** ; :heavy_check_mark: comprendere i file associati agli utenti e ai gruppi e scoprire come gestirli; :heavy_check_mark: cambiare il *proprietario* o il *proprietario del gruppo* di un file; -:heavy_check_mark: *sicuro* account utente; +:heavy_check_mark: *proteggere* un account utente; :heavy_check_mark: cambiare identità. :checkered_flag: **utenti** @@ -38,8 +38,8 @@ Gruppo diversi dal gruppo primario sono chiamati **gruppi supplementari**. I gruppi e gli utenti sono gestiti dai loro identificatori numerici unici `GID` e `UID`. -* `UID`: _User IDentifier_. ID utente unico. -* `GID`: _Group IDentifier_. Identificatore di gruppo unico. +* `UID`: _User IDentifier_. ID utente univoco. +* `GID`: _Group IDentifier_. Identificatore di gruppo univoco. Sia UID che GID sono riconosciuti dal kernel, il che significa che il Super Admin non è necessariamente l'utente **root**, purché l'utente **uid=0** sia il Super Admin. @@ -57,6 +57,12 @@ I file relativi agli utenti/gruppi sono: Dovresti sempre usare i comandi di amministrazione invece di modificare manualmente i file. +!!! Note "Nota" + + Alcuni comandi in questo capitolo richiedono i diritti di amministratore. + Per convenzione, si specifica il comando `sudo` quando i comandi devono essere eseguiti con diritti di amministratore. + Affinché gli esempi funzionino correttamente, verificare che l'account utilizzato abbia il permesso di utilizzare il comando `sudo`. + ## Gestione del gruppo File modificati, righe aggiunte: @@ -67,14 +73,15 @@ File modificati, righe aggiunte: ### comando `groupadd` Il comando `groupadd` aggiunge un gruppo al sistema. -``` + +```bash groupadd [-f] [-g GID] group ``` Esempio: -``` -$ sudo groupadd -g 1012 GroupeB +```bash +sudo groupadd -g 1012 GroupeB ``` | Opzione | Descrizione | @@ -90,7 +97,7 @@ Regole di denominazione del gruppo: !!! Note "Nota" - Sotto **Debian**, l'amministratore dovrebbe usare, tranne che negli script destinati ad essere portabili su tutte le distribuzioni Linux, i comandi `addgroup` e `delgroup` come specificato nel `man`: + In **Debian**, l'amministratore dovrebbe usare, tranne che negli script destinati a essere trasferiti a tutte le distribuzioni Linux, i comandi `addgroup` e `delgroup` come specificato in `man`: ``` $ man addgroup @@ -105,15 +112,16 @@ Regole di denominazione del gruppo: Il comando `groupmod` consente di modificare un gruppo esistente sul sistema. -``` +```bash groupmod [-g GID] [-n nom] group ``` Esempio: -``` -$ sudo groupmod -g 1016 GroupP -$ sudo groupmod -n GroupC GroupB +```bash +sudo groupmod -g 1016 GroupP + +sudo groupmod -n GroupC GroupB ``` | Opzione | Osservazioni | @@ -125,22 +133,22 @@ $ sudo groupmod -n GroupC GroupB Dopo la modifica, i file appartenenti al gruppo hanno un `GID` sconosciuto. Devono essere riassegnati al nuovo `GID`. -``` -$ sudo find / -gid 1002 -exec chgrp 1016 {} \; +```bash +sudo find / -gid 1002 -exec chgrp 1016 {} \; ``` ### comando `groupdel` -Il comando `groupdel` si usa per eliminare un gruppo esistente sul sistema. +Il comando `groupdel` viene utilizzato per eliminare un gruppo esistente sul sistema. -``` +```bash groupdel group ``` Esempio: -``` -$ sudo groupdel GroupC +```bash +sudo groupdel GroupC ``` !!! Tip "Suggerimento" @@ -153,17 +161,16 @@ $ sudo groupdel GroupC Esempi: ```bash - Shell > useradd testa - Shell > id testa - uid=1000(testa) gid=1000(testa) group=1000(testa) - Shell > groupdel testa - groupdel: cannot remove the primary group of user 'testa' - - Shell > groupadd -g 1001 testb - Shell > usermod -G testb root - Shell > id root - uid=0(root) gid=0(root) group=0(root),1001(testb) - Shell > groupdel testb + $ sudo useradd test + $ id test + uid=1000(test) gid=1000(test) group=1000(test) + $ sudo groupdel test + groupdel: cannot remove the primary group of user 'test' + + $ sudo usermod -g users -G test test + $ id test + uid=1000(test) gid=100(users) group=100(users),1000(test) + $ sudo groupdel testb ``` !!! Tip "Suggerimento" @@ -172,7 +179,7 @@ $ sudo groupdel GroupC !!! Tip "Suggerimento" - Ogni gruppo ha un `GID` unico. Un gruppo può essere utilizzato da più utenti come gruppo supplementare. Per convenzione, il GID del super amministratore è 0. Il GIDS riservato ad alcuni servizi o processi sono 201~999, che sono chiamati gruppi di sistema o gruppi di utenti pseudo. Il GID per gli utenti è solitamente maggiore o uguale a 1000. Questi sono relativi a /etc/login.defs, di cui parleremo più tardi. + Ogni gruppo ha un `GID` univoco. Un gruppo può essere utilizzato da più utenti come gruppo supplementare. Per convenzione, il GID del super amministratore è 0. I GIDS riservati ad alcuni servizi o processi sono 201~999, chiamati gruppi di sistema o pseudo gruppi di utenti. Il GID per gli utenti è solitamente maggiore o uguale a 1000. Questi sono relativi a /etc/login.defs, di cui parleremo più tardi. ```bash # Comment line ignored @@ -203,9 +210,9 @@ $ sudo groupdel GroupC ### file `/etc/group` -Questo file contiene le informazioni del Gruppo (divise da `:`). +Questo file contiene le informazioni sul gruppo (separate da `:`). -``` +```bash $ sudo tail -1 /etc/group GroupP:x:516:patrick (1) (2)(3) (4) @@ -222,9 +229,9 @@ GroupP:x:516:patrick ### file `/etc/gshadow` -Questo file contiene le informazioni di sicurezza sui gruppi (divisi da `:`). +Questo file contiene le informazioni di sicurezza sui gruppi (separate da `:`). -``` +```bash $ sudo grep GroupA /etc/gshadow GroupA:$6$2,9,v...SBn160:alain:rockstar (1) (2) (3) (4) @@ -239,7 +246,7 @@ GroupA:$6$2,9,v...SBn160:alain:rockstar Il nome del gruppo in **/etc/group** e **/etc/gshadow** deve corrispondere uno a uno, cioè ogni riga del file **/etc/group** deve avere una riga 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 è bloccata. In questo modo, nessun utente può utilizzare la password per accedere al gruppo (poiché i membri del gruppo non ne hanno bisogno). ## Gestione utenti @@ -258,10 +265,10 @@ Un utente è definito come segue nel file `/etc/passwd`: Esistono tre tipi di utenti: * **root(uid=0)**: l'amministratore di sistema; -* **system users(uid è uno da 201~999)**: Utilizzato dal sistema per gestire i diritti di accesso alle applicazioni; +* **system users(uid è uno dei 201~999)**: Utilizzato dal sistema per gestire i diritti di accesso alle applicazioni; * **utente normale (uid>=1000)**: Altro account per accedere al sistema. -File modificati, righe aggiunte: +File modificati e righe aggiunte: * `/etc/passwd` * `/etc/shadow` @@ -270,14 +277,14 @@ File modificati, righe aggiunte: Il comando `useradd` è usato per aggiungere un utente. -``` +```bash useradd [-u UID] [-g GID] [-d directory] [-s shell] login ``` Esempio: -``` -$ sudo useradd -u 1000 -g 1013 -d /home/GroupC/carine carine +```bash +sudo useradd -u 1000 -g 1013 -d /home/GroupC/carine carine ``` | Opzione | Descrizione | @@ -292,11 +299,11 @@ $ sudo useradd -u 1000 -g 1013 -d /home/GroupC/carine carine | `-M` | Non crea la home directory dell'utente. | | `-r` | Crea un account di sistema. | -Alla creazione, l'account non ha una password ed è bloccato. +Alla sua creazione, l'account non ha una password ed è bloccato. Per sbloccare l'account è necessario assegnare una password. -Quando il comando `useradd` non ha opzioni, appare: +Quando si richiama il comando `useradd` senza alcuna opzione, vengono impostate le seguenti impostazioni predefinite per il nuovo utente: * Crea una home directory con lo stesso nome; * Crea un gruppo primario con lo stesso nome; @@ -310,16 +317,16 @@ Quando il comando `useradd` non ha opzioni, appare: `/etc/login.defs` e `/etc/default/useradd` ```bash -Shell > useradd test1 +$ sudo useradd test1 -Shell > tail -n 1 /etc/passwd +$ tail -n 1 /etc/passwd test1:x:1000:1000::/home/test1:/bin/bash -Shell > tail -n 1 /etc/shadow +$ tail -n 1 /etc/shadow test1:!!:19253:0:99999:7 ::: -Shell > tail -n 1 /etc/group ; tail -n 1 /etc/gshadow +$ tail -n 1 /etc/group ; tail -n 1 /etc/gshadow test1:x:1000: test1:!:: ``` @@ -334,41 +341,41 @@ Regole di denominazione dell'account: !!! Warning "Attenzione" - L'albero delle home directory deve essere creato tranne che per l'ultima directory. + L'albero delle home directory deve essere già stato creato tranne che 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. +L'ultima directory viene creata dal comando `useradd`, che sfrutta l'opportunità per copiare i file da `/etc/skel` al suo interno. -**Un utente può appartenere a diversi gruppi oltre al proprio gruppo primario.** +**Un utente può appartenere a diversi gruppi oltre a quello principale.** Esempio: -``` -$ sudo useradd -u 1000 -g GroupA -G GroupP,GroupC albert +```bash +sudo useradd -u 1000 -g GroupA -G GroupP,GroupC albert ``` !!! Note "Nota" - Sotto **Debian**, dovrai specificare l'opzione `-m` per forzare la creazione della directory di login 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 in `man`, tranne che negli script destinati a essere trasferiti a tutte le distribuzioni Linux: + In **Debian**, è necessario specificare l'opzione `-m` per forzare la creazione della directory di login 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 in `man`, tranne che negli script destinati ad essere trasferiti a tutte le distribuzioni Linux: ``` $ man useradd DESCRIPTION - **useradd** is a low level utility for adding users. On Debian, administrators should usually use **adduser(8)** + **useradd** is a low-level utility for adding users. On Debian, administrators should usually use **adduser(8)** instead. ``` -#### Valori predefiniti per la creazione dell'utente. +#### Valore predefinito per la creazione di un utente Modifica del file `/etc/default/useradd`. -``` +```bash useradd -D [-b directory] [-g group] [-s shell] ``` Esempio: -``` -$ sudo useradd -D -g 1000 -b /home -s /bin/bash +```bash +sudo useradd -D -g 1000 -b /home -s /bin/bash ``` | Opzione | Descrizione | @@ -382,16 +389,16 @@ $ sudo useradd -D -g 1000 -b /home -s /bin/bash ### comando `usermod` -Il comando `usermod` permette di modificare un utente. +Il comando `usermod` consente di modificare un utente. -``` +```bash usermod [-u UID] [-g GID] [-d directory] [-m] login ``` Esempio: -``` -$ sudo usermod -u 1044 carine +```bash +sudo usermod -u 1044 carine ``` Opzioni identiche al comando `useradd`. @@ -410,43 +417,44 @@ Opzioni identiche al comando `useradd`. Per essere modificato, un utente deve essere disconnesso e non avere processi in corso. -Dopo aver cambiato l'identificatore, i file appartenenti all'utente hanno un `UID` sconosciuto . Deve essere riassegnato il nuovo `UID`. +Dopo la modifica dell'identificatore, i file appartenenti all'utente hanno un `UID` sconosciuto. Deve essere riassegnato al nuovo `UID`. -Dove `1000` è il vecchio `UID` e `1044` quello nuovo. Gli esempi sono i seguenti: +Dove `1000` è il vecchio `UID` e `1044` è il nuovo. Gli esempi sono i seguenti: -``` -$ sudo find / -uid 1000 -exec chown 1044: {} \; +```bash +sudo find / -uid 1000 -exec chown 1044: {} \; ``` Blocco e sblocco dell'account utente, gli esempi sono i seguenti: -``` -Shell > usermod -L test1 -Shell > grep test1 /etc/shadow +```bash +$ usermod -L test1 +$ grep test1 /etc/shadow test1:!$6$n.hxglA.X5r7X0ex$qCXeTx.kQVmqsPLeuvIQnNidnSHvFiD7bQTxU7PLUCmBOcPNd5meqX6AEKSQvCLtbkdNCn.re2ixYxOeGWVFI0:19259:0:99999:7 ::: -Shell > usermod -U test1 +$ usermod -U test1 ``` La differenza tra l'opzione `-aG` e l'opzione `-G` può essere spiegata dal seguente esempio: ```bash -Shell > useradd test1 -Shell > passwd test1 -Shell > groupadd groupA ; groupadd groupB ; groupadd groupC ; groupadd groupD -Shell > id test1 +$ sudo useradd test1 +$ sudo passwd test1 +$ sudo groupadd groupA ; sudo groupadd groupB ; sudo groupadd groupC ; sudo groupadd groupD +$ id test1 uid=1000(test1) gid=1000(test1) groups=1000(test1) -Shell > gpasswd -a test1 groupA -Shell > id test1 +$ sudo gpasswd -a test1 groupA +$ id test1 uid=1000(test1) gid=1000(test1) groups=1000(test1),1002(groupA) -Shell > usermod -G groupB,groupC test1 -Shell > id test1 -uid=1000(test1) gid=1000(test1) gorups=1000(test1),1003(groupB),1004(groupC) +$ sudo usermod -G groupB,groupC test1 +$ id test1 +uid=1000(test1) gid=1000(test1) groups=1000(test1),1003(groupB),1004(groupC) -Shell > usermod -aG groupD test1 +$ sudo usermod -aG groupD test1 +$ id test1 uid=1000(test1) gid=1000(test1) groups=1000(test1),1003(groupB),1004(groupC),1005(groupD) ``` @@ -454,8 +462,8 @@ uid=1000(test1) gid=1000(test1) groups=1000(test1),1003(groupB),1004(groupC),100 Il comando `userdel` consente di eliminare l'account di un utente. -``` -$ sudo userdel -r carine +```bash +sudo userdel -r carine ``` | Opzione | Descrizione | @@ -466,13 +474,13 @@ $ sudo userdel -r carine Per essere eliminato, un utente deve essere disconnesso e non avere processi in esecuzione. -Il comando `userdel` rimuove le righe corrispondenti in `/etc/passwd`, `/ etc/shadow`, `/etc/group`, `/etc/gshadow`. Come accennato in precedenza, `userdel -r` cancellerà anche il corrispondente gruppo primario dell'utente. +Il comando `userdel` rimuove le righe corrispondenti in `/etc/passwd`, `/etc/shadow`, `/etc/group`, `/etc/gshadow`. Come detto in precedenza, `userdel -r` cancellerà anche il corrispondente gruppo primario dell'utente. ### file `/etc/passwd` 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) @@ -489,7 +497,8 @@ root:x:0:0:root:/root:/bin/bash ### file `/etc/shadow` Questo file contiene le informazioni di sicurezza degli utenti (separate da `:`). -``` + +```bash $ sudo tail -1 /etc/shadow root:$6$...:15399:0:99999:7 ::: @@ -514,10 +523,10 @@ Per la conversione della data e dell'ora, fare riferimento al seguente formato d ```bash # Il timestamp viene convertito in una data, "17718" indica il timestamp da inserire. -Shell > date -d "1970-01-01 17718 days" +$ date -d "1970-01-01 17718 days" -# La data è convertita in un timestamp, "2018-07-06" indica la data da compilare. -Shell > echo $(($(date --date="2018-07-06" +%s)/86400+1)) +# La data viene convertita in un timestamp, "2018-07-06" indica la data da compilare. +$ echo $(($(date --date="2018-07-06" +%s)/86400+1)) ``` ## Proprietari dei file @@ -533,14 +542,17 @@ Il gruppo primario dell'utente che crea il file è, per impostazione predefinita #### comando `chown` Il comando `chown` consente di cambiare i proprietari di un file. -``` + +```bash chown [-R] [-v] login[:group] file ``` Esempi: -``` -$ sudo chown root myfile -$ sudo chown albert:GroupA myfile + +```bash +sudo chown root myfile + +sudo chown albert:GroupA myfile ``` | Opzione | Descrizione | @@ -548,47 +560,48 @@ $ sudo chown albert:GroupA myfile | `-R` | Cambia ricorsivamente i proprietari della directory e di tutti i file in essa contenuti. | | `-v` | Visualizza le modifiche. | -Per cambiare solo l'utente proprietario: +Per modificare solo l'utente proprietario: -``` -$ sudo chown albert file +```bash +sudo chown albert file ``` Per modificare solo il gruppo proprietario: -``` -$ sudo chown :GroupA file +```bash +sudo chown :GroupA file ``` Modifica dell'utente e del gruppo proprietario: -``` -$ sudo chown albert:GroupA file +```bash +sudo chown albert:GroupA file ``` Nell'esempio seguente, il gruppo assegnato sarà il gruppo primario dell'utente specificato. -``` -$ sudo chown albert: file +```bash +sudo chown albert: file ``` Cambia il proprietario e il gruppo di tutti i file in una directory -``` -$ sudo chown -R albert:GroupA /dir1 +```bash +sudo chown -R albert:GroupA /dir1 ``` ### comando `chgrp` Il comando `chgrp` consente di cambiare il gruppo proprietario di un file. -``` +```bash chgrp [-R] [-v] group file ``` Esempio: -``` -$ sudo chgrp group1 file + +```bash +sudo chgrp group1 file ``` | Opzione | Descrizione | @@ -600,29 +613,29 @@ $ sudo chgrp group1 file È possibile applicare a un file un proprietario e un gruppo di proprietari prendendo come riferimento quelli di un altro file: -``` +```bash chown [options] --reference=RRFILE FILE ``` Per esempio: -``` +```bash chown --reference=/etc/groups /etc/passwd ``` -## Gestione degli ospiti +## Gestione degli utenti ### comando `gpasswd` Il comando `gpasswd` permette di gestire un gruppo. -``` -gpasswd [-a login] [-A login] [-d login] [-M login] group +```bash +gpasswd [option] group ``` Esempi: -``` +```bash $ sudo gpasswd -A alain GroupA [alain]$ gpasswd -a patrick GroupA ``` @@ -636,7 +649,7 @@ $ sudo gpasswd -A alain GroupA Il comando `gpasswd -M` agisce come una modifica, non come un'aggiunta. -``` +```bash # gpasswd GroupeA New Password: Re-enter new password: @@ -650,60 +663,60 @@ Re-enter new password: Il comando `id` visualizza i nomi del gruppo di un utente. -``` +```bash id USER ``` Esempio: -``` +```bash $ sudo id alain uid=1000(alain) gid=1000(GroupA) groupes=1000(GroupA),1016(GroupP) ``` ### comando `newgrp` -Il comando `newgrp` può selezionare un gruppo, dai gruppi supplementari dell'utente, come nuovo gruppo primario **temporaneo**. Il comando `newgrp` ogni volta che viene cambiato il gruppo primario di un utente, crea una nuova **child shell** (child process). Fai attenzione! **child shell** e **sub shell** sono diverse. +Il comando `newgrp` può selezionare un gruppo, dai gruppi supplementari dell'utente, come nuovo gruppo primario **temporaneo**. Il comando `newgrp` ogni volta che viene cambiato il gruppo primario di un utente, crea una nuova **child shell** (child process). Fate attenzione! **child shell** e **sub shell** sono diverse. -``` +```bash newgrp [secondarygroups] ``` Esempio: -``` -Shell > useradd test1 -Shell > passwd test1 -Shell > groupadd groupA ; groupadd groupB -Shell > usermod -G groupA,groupB test1 -Shell > id test1 +```bash +$ sudo useradd test1 +$ sudo passwd test1 +$ sudo groupadd groupA ; sudo groupadd groupB +$ sudo usermod -G groupA,groupB test1 +$ id test1 uid=1000(test1) gid=1000(test1) groups=1000(test1),1001(groupA),1002(groupB) -Shell > echo $SHLVL ; echo $BASH_SUBSHELL +$ echo $SHLVL ; echo $BASH_SUBSHELL 1 0 -Shell > su - test1 -Shell > touch a.txt -Shell > ll +$ su - test1 +$ touch a.txt +$ ll -rw-rw-r-- 1 test1 test1 0 10月 7 14:02 a.txt -Shell > echo $SHLVL ; echo $BASH_SUBSHELL +$ echo $SHLVL ; echo $BASH_SUBSHELL 1 0 # Generate a new child shell -Shell > newgrp groupA -Shell > touch b.txt -Shell > ll +$ newgrp groupA +$ touch b.txt +$ ll -rw-rw-r-- 1 test1 test1 0 10月 7 14:02 a.txt -rw-r--r-- 1 test1 groupA 0 10月 7 14:02 b.txt -Shell > echo $SHLVL ; echo $BASH_SUBSHELL +$ echo $SHLVL ; echo $BASH_SUBSHELL 2 0 # You can exit the child shell using the `exit` command -Shell > exit -Shell > logout -Shell > whoami +$ exit +$ logout +$ whoami root ``` @@ -713,15 +726,16 @@ root Il comando `passwd` viene utilizzato per gestire una password. -``` +```bash passwd [-d] [-l] [-S] [-u] [login] ``` Esempi: -``` -Shell > passwd -l albert -Shell > passwd -n 60 -x 90 -w 80 -i 10 patrick +```bash +sudo passwd -l albert + +sudo passwd -n 60 -x 90 -w 80 -i 10 patrick ``` | Opzione | Descrizione | @@ -736,25 +750,25 @@ Shell > passwd -n 60 -x 90 -w 80 -i 10 patrick | `-w DAYS` | Definisce il tempo di avviso prima della scadenza. Cambiamento permanente. Solo per root (uid=0). | | `-i DAYS` | Definisce il ritardo prima della disattivazione quando la password scade. Cambiamento permanente. Solo per root (uid=0). | -Usare `password -l`, cioè aggiungere "!!" all'inizio del campo della password dell'utente corrispondente a `/etc/shadow`. +Utilizzare `password -l`, cioè aggiungere "!!" all'inizio del campo password dell'utente corrispondente nel file `/etc/shadow`. Esempio: * Alain cambia la sua password: -``` +```bash [alain]$ passwd ``` * root cambia la password di Alain -``` -$ sudo passwd alain +```bash +sudo passwd alain ``` !!! Note "Nota" - Il comando `passwd` è disponibile per gli utenti per modificare la loro password (è richiesta la vecchia password). L'amministratore può modificare le password di tutti gli utenti senza restrizioni. + Il comando `passwd` è a disposizione degli utenti per cambiare la propria password (viene richiesta la vecchia password). L'amministratore può modificare le password di tutti gli utenti senza limitazioni. Dovranno rispettare le restrizioni di sicurezza. @@ -764,8 +778,8 @@ Questo può essere fatto passando la password al comando `passwd`. Esempio: -``` -$ sudo echo "azerty,1" | passwd --stdin philippe +```bash +sudo echo "azerty,1" | passwd --stdin philippe ``` !!! Warning "Attenzione" @@ -776,14 +790,14 @@ $ sudo echo "azerty,1" | passwd --stdin philippe Il comando `chage` modifica le informazioni sulla scadenza della password utente. -``` +```bash chage [-d date] [-E date] [-I days] [-l] [-m days] [-M days] [-W days] [login] ``` Esempio: -``` -$ sudo chage -m 60 -M 90 -W 80 -I 10 alain +```bash +sudo chage -m 60 -M 90 -W 80 -I 10 alain ``` | Opzione | Descrizione | @@ -798,11 +812,11 @@ $ sudo chage -m 60 -M 90 -W 80 -I 10 alain Esempi: -``` +```bash # Il comando `chage` offre anche una modalità interattiva. $ sudo chage philippe -# L'opzione `-d` costringe la password a essere cambiata al login. +# L'opzione `-d' forza la modifica della password all'accesso. $ sudo chage -d 0 philippe ``` @@ -824,7 +838,7 @@ File di configurazione: ### file `/etc/default/useradd` -Questo file contiene le impostazioni predefinite dei dati. +Questo file contiene le impostazioni predefinite dei valori. !!! Tip "Suggerimento" @@ -832,7 +846,7 @@ Questo file contiene le impostazioni predefinite dei dati. Questo file è modificato dal comando `useradd -D` (`useradd -D` inserito senza nessun'altra opzione visualizza il contenuto del file `/etc/default/useradd`). -``` +```bash Shell > grep -v ^# /etc/default/useradd GROUP=100 HOME=/home @@ -853,9 +867,9 @@ CREATE_MAIL_SPOOL=yes | `SKEL` | Definisce la struttura della directory di login. | | `CREATE_MAIL_SPOOL` | Definisce la creazione della cassetta postale in `/var/spool/mail/`. | -Se non si ha bisogno di un gruppo primario con lo stesso nome quando si creano gli utenti, si può fare così: +Se non si ha bisogno di un gruppo primario con lo stesso nome quando si creano gli utenti, si può fare in questo modo: -``` +```bash Shell > useradd -N test2 Shell > id test2 uid=1001(test2) gid=100(users) groups=100(users) @@ -888,15 +902,15 @@ ENCRYPT_METHOD SHA512 `UMASK 022`: Ciò significa che il permesso di creare un file è 755 (rwxr-xr-x). Tuttavia, per motivi di sicurezza, GNU/Linux non prevede il permesso **x** per i file appena creati; questa restrizione si applica a root (uid=0) e agli utenti ordinari (uid>=1000). Per esempio: -``` +```bash Shell > touch a.txt Shell > ll -rw-r--r-- 1 root root 0 Oct 8 13:00 a.txt ``` -`HOME_MODE 0700`: I permessi della directory home di un utente ordinario. Non funziona per la directory home di root. +`HOME_MODE 0700`: I permessi della directory home di un utente ordinario. Non si applica alla directory home di root. -``` +```bash Shell > ll -d /root dr-xr-x---. 10 root root 4096 Oct 8 13:12 /root @@ -906,7 +920,7 @@ drwx------ 2 test1 test1 4096 Oct 8 13:10 /home/test1/ `USERGROUPS_ENAB yes`: "Quando si elimina un utente con il comando `userdel -r`, viene eliminato anche il gruppo primario corrispondente." Perché? Questo è il motivo. -### directory `/etc/skel` +### `/etc/skel` directory Quando viene creato un utente, vengono creati la sua home directory e i suoi file di ambiente. I file della directory `/etc/skel/` sono i modelli di file necessari per creare gli utenti. @@ -924,13 +938,13 @@ Tutti i file e le directory collocati in questa directory saranno copiati nell'a Il comando `su` consente di cambiare l'identità dell'utente connesso. -``` +```bash su [-] [-c command] [login] ``` Esempi: -``` +```bash $ sudo su - alain [albert]$ su - root -c "passwd alain" ``` @@ -946,31 +960,31 @@ Gli utenti standard dovranno digitare la password per la nuova identità. !!! Tip "Suggerimento" - È possibile utilizzare il comando `exit`/`logout` per far uscire gli utenti che sono stati attivati. Si noti che dopo il cambio di utente non esiste una nuova `child shell` o `sub shell`, ad esempio: + You can use the `exit`/`logout` command to exit users who have been switched. Si noti che dopo il cambio di utente non esiste una nuova `child shell` o `sub shell`, ad esempio: ``` - Shell > whoami + $ whoami root - Shell > echo $SHLVL ; echo $BASH_SUBSHELL + $ echo $SHLVL ; echo $BASH_SUBSHELL 1 0 - Shell > su - test1 - Shell > echo $SHLVL ; echo $BASH_SUBSHELL + $ su - test1 + $ echo $SHLVL ; echo $BASH_SUBSHELL 1 0 ``` Attenzione! `su` e `su -` sono diversi, come mostrato nell'esempio seguente: -``` -Shell > whoami +```bash +$ whoami test1 -Shell > su root -Shell > pwd +$ su root +$ pwd /home/test1 -Shell > env +$ env ... USER=test1 PWD=/home/test1 @@ -980,14 +994,14 @@ LOGNAME=test1 ... ``` -``` -Shell > whoami +```bash +$ whoami test1 -Shell > su - root -Shell > pwd +$ su - root +$ pwd /root -Shell > env +$ env ... USER=root PWD=/root diff --git a/docs/books/learning_rsync/01_rsync_overview.fr.md b/docs/books/learning_rsync/01_rsync_overview.fr.md new file mode 100644 index 0000000000..6dcd1ecc06 --- /dev/null +++ b/docs/books/learning_rsync/01_rsync_overview.fr.md @@ -0,0 +1,60 @@ +--- +title: description succincte de rsync +author: tianci li +contributors: Steven Spencer, Ganna Zhyrnova +update: 2022-03-08 +--- + +# Sauvegarde + +Qu'est-ce qu'une sauvegarde ? + +La sauvegarde fait référence à la duplication des données dans le système de fichiers ou dans la base de données. En cas d'erreur ou de catastrophe, les données effectives du système peuvent être restaurées en temps utile et de façon normale. + +Quelles sont les méthodes de sauvegarde ? + +* Sauvegarde complète : désigne une copie unique de tous les fichiers, dossiers ou données du disque dur ou de la base de données. (Avantages : le meilleur, peut récupérer les données plus rapidement. Inconvénients : prendre plus d'espace sur le disque dur.) +* Sauvegarde incrémentale : fait référence à la sauvegarde des données mise à jour après la dernière sauvegarde complète ou la dernière sauvegarde incrémentale. Le processus est ainsi, comme une sauvegarde complète le premier jour ; une sauvegarde des données récemment ajoutées le deuxième jour, par opposition à une sauvegarde complète ; le troisième jour, une sauvegarde des données nouvellement ajoutées sur la base du deuxième jour, relatif au lendemain. +* Sauvegarde différentielle : Se réfère à la sauvegarde des fichiers modifiés après la sauvegarde complète. Par exemple, une sauvegarde complète le premier jour ; une sauvegarde des nouvelles données le deuxième jour ; une sauvegarde des nouvelles données du deuxième jour au troisième jour; et une sauvegarde de toutes les nouvelles données du deuxième jour au quatrième jour le quatrième jour, et ainsi de suite. +* Sauvegarde sélective : Se réfère à la sauvegarde d'une partie du système. +* Sauvegarde froide : désigne la sauvegarde lorsque le système est en état d'arrêt ou de maintenance. Les données sauvegardées sont exactement les mêmes que celles du système durant cette période. +* Sauvegarde à chaud : se rapporte à la sauvegarde lorsque le système est en fonctionnement normal. Comme les données du système sont mises à jour à tout moment, les données sauvegardées ont un certain retard par rapport aux données réelles du système. +* Sauvegarde à distance : désigne la sauvegarde des données dans un autre endroit géographique pour éviter la perte de données et l'interruption de service causée par le feu, les catastrophes naturelles, le vol, etc. + +## rsync en bref + +Sur un serveur, nous avons sauvegardé la première partition sur la seconde partition, qui est communément appelée « sauvegarde locale ». Les outils de sauvegarde spécifiques sont `tar` , `dd` , `dump` , `cp` , etc. Bien que les données soient sauvegardées sur ce serveur, si le matériel ne démarre pas correctement, les données ne seront pas récupérées. Afin de résoudre ce problème de la sauvegarde locale, nous avons introduit un autre type de sauvegarde --- "la sauvegarde distante". + +Certaines personnes diront, ne puis-je pas simplement utiliser la commande `tar` ou `cp` sur le premier serveur et envoyer les données au second serveur via `scp` ou `sftp` ? + +Dans un environnement de production, la quantité de données est relativement importante. Tout d'abord, `tar` ou `cp` consomme beaucoup de temps et réduit les performances du système. La transmission via `scp` ou `sftp` occupe également beaucoup de bande passante réseau, ce qui n'est pas autorisé dans un environnement de production réel. Deuxièmement, ces commandes ou outils doivent être saisis manuellement par l'administrateur et doivent être combinés avec le crontab de la tâche planifiée. Cependant, le temps défini par crontab n'est pas facile à saisir, et il n'est pas approprié que les données soient sauvegardées si le temps est trop court ou trop long. + +Par conséquent, il doit y avoir une sauvegarde des données dans l'environnement de production qui doit satisfaire aux exigences suivantes : + +1. Sauvegardes transmises sur le réseau +2. Synchronisation des fichiers de données en temps réel +3. Moins d'occupation des ressources du système et plus d'efficacité + +`rsync` semble répondre aux besoins ci-dessus. Il utilise le contrat de licence GNU open source. C'est un outil de sauvegarde incrémentielle rapide. La dernière version est 3.2.3 (2020-08-06). Vous pouvez consulter le [site officiel](https://rsync.samba.org/) pour plus d'informations. + +En termes de support de plate-forme, la plupart des systèmes UNIX ou apparentés sont supportés, qu'il s'agisse de GNU/Linux ou de BSD par exemple. En outre, il y a des logiciels similaires à `rsync` sous la plate-forme Windows, comme cwRsync par exemple. + +L'original `rsync` a été maintenu par le programmeur australien Andrew Tridgell (affiché dans la figure 1 ci-dessous), et maintenant il a été maintenu par Wayne Davison (affiché sur la figure 2 ci-dessous) pour maintenance, vous pouvez aller à [ l'adresse du projet github ](https://github.com/WayneD/rsync) pour obtenir les informations que vous voulez. + +![ Andrew Tridgell ](images/Andrew_Tridgell.jpg) ![ Wayne Davison ](images/Wayne_Davison.jpg) + +!!! note "Note" + + **rsync lui-même n'est qu'un outil de sauvegarde incrémentiel et n'a pas la fonction de synchronisation des données en temps réel (il doit être complété par d'autres programmes). En outre, la synchronisation est à sens unique. Si vous voulez réaliser une synchronisation bidirectionnelle, vous devrez envisager d'autres outils.** + +### Principes et fonctionnalités de base + +Comment `rsync` fait-il une sauvegarde avec la synchronisation des données à sens unique ? + +Le cœur de `rsync` est son algorithme **Checksum**. Si vous êtes intéressé, vous pouvez aller à [Comment fonctionne Rsync](https://rsync.samba.org/how-rsync-works.html) et [L'algorithme rsync](https://rsync.samba.org/tech_report/) pour plus d'informations. Cette section dépasse la compétence de l'auteur et ne sera pas trop couverte. + +Les caractéristiques de `rsync` sont les suivantes : + +* L'ensemble du répertoire peut être mis à jour récursivement ; +* Peut retenir sélectivement les attributs de synchronisation de fichiers, tels que le lien dur, le lien logiciel, le propriétaire, le groupe, les permissions correspondantes, le temps de modification, etc. et peut conserver certains attributs ; +* Prise en charge de deux protocoles pour la transmission, l'un est le protocole ssh, l'autre est le protocole rsync diff --git a/docs/gemstones/htop.fr.md b/docs/gemstones/htop.fr.md new file mode 100644 index 0000000000..239d0ee26e --- /dev/null +++ b/docs/gemstones/htop.fr.md @@ -0,0 +1,102 @@ +--- +title: htop - Gestion des Processus +author: tianci li +contributors: Steven Spencer +date: 2021-10-16 +tags: + - htop + - processus +--- + +# htop - Gestion des Processus + +## Installation de `htop` +Chaque administrateur système favorise certaines des commandes les plus couramment utilisées. Dans cet article, l'auteur recommande `htop` comme alternative à la commande `top`. Pour utiliser la commande `htop`, en général, vous devez d'abord l'installer. + +``` bash +# Installation epel source (also called repository) +dnf -y install epel-release +# Generate cache +dnf makecache +# Install htop +dnf -y install htop +``` + +## Utilisation de `htop` +Vous n'avez qu'à taper `htop` dans le terminal et l'interface interactive est la suivante : + +``` +0[ ||| 3%] Tasks: 22, 46thr, 174 kthr 1 running +1[ | 1%] Load average: 0.00 0.00 0.05 +Mem[ ||||||| 197M/8G] Uptime: 00:31:39 +Swap[ 0K/500M] +PID USER PRI NI VIRT RES SHR S CPU% MEM% TIME+ Command(merged) +... +``` + +F1Help F2Setup F3Search F4Filter F5Tree F6SortBy F7Nice F8Nice+ F9Kill F10Quit + +### Description de la partie supérieure + +* Les 0 et 1 indiquent le numéro des cœurs de la CPU et le pourcentage indique le taux d'occupation d'un seul cœur (le taux d'occupation total de la CPU peut également être affiché) + * Les différentes couleurs de la barre de progression indiquent le pourcentage de différents types de processus : + + | Couleur | Observation | Noms affichés avec d'autres styles | + | ------- | ------------------------------------------------------------------------- | ---------------------------------- | + | Bleu | Pourcentage de CPU utilisé par les processus de faible priorité | low | + | Vert | Pourcentage de CPU du processus appartenant à des utilisateurs ordinaires | | + | Rouge | Pourcentage de CPU utilisé par les processus du système | sys | + | Cyan | Pourcentage du temps de CPU Steal Time | vir | + +* Tasks: 22, 46thr, 174 kthr 1 running. Dans notre exemple, cela signifie que notre machine actuelle a 24 tâches, qui sont divisés en 14 threads, dont un seul processus est en cours d'exécution, "kthr" indique le nombre de kernel-threads. +* Mem décrit la charge de mémoire. Les couleurs permettent de distinguer le type d'occupation de la mémoire : + + | Couleur | Observation | Noms affichés | + | ------------ | -------------------------------------------------------------- | ------------- | + | Bleu | Pourcentage de mémoire consommée par le tampon | buffers | + | Vert | Pourcentage de mémoire consommée par la zone mémoire | used | + | Jaune/Orange | Pourcentage de mémoire consommée par la zone de cache | cache | + | Magenta | Pourcentage de mémoire occupée par la zone de mémoire partagée | shared | + +* Swap information. + + | Couleur | Observation | Noms affichés | + | ------------ | ------------------------------------------ | ------------- | + | Vert | Pourcentage de cache utilisé sur le disque | used | + | Jaune/Orange | Pourcentage de cache - swap - utilisé | cache | + +* Charge moyenne, les trois valeurs représentent respectivement la charge moyenne du système au cours de la dernière minute, des 5 dernières minutes et des 15 dernières minutes +* Uptime signifie le temps écoulé depuis le démarrage du système + +### Description du processus + +* **PID - Numéro d'identification du processus** +* USER - Le propriétaire du processus +* PRI - la priorité du processus du point de vue du noyau Linux +* NI - la priorité du processus de réinitialisation par l'utilisateur normal ou bien root +* VIRT - Mémoire virtuelle consommée par un processus +* **RES - Mémoire physique consommée par un processus** +* SHR - Mémoire partagée consommée par un processus +* S - L'état actuel du processus Z (processus zombie). Un trop grand nombre de processus zombies affectera les performances de la machine. +* **CPU% - Pourcentage de CPU consommé par chaque processus** +* MEM% - Pourcentage de mémoire consommée par chaque processus +* TIME+ - Indique le temps d'exécution depuis le démarrage du processus +* Command - La commande correspondant au processus + +### Description des raccourcis +Dans l'interface interactive, appuyez sur le bouton F1 pour voir la description de la touche de raccourci correspondante. + +* Les touches de direction haut, bas, gauche et droite peuvent faire défiler l'interface interactive, et ++space++ peuvent marquer le processus correspondant, qui est marqué en jaune. +* Les boutons ++N++, ++P++, ++M++ et ++T++ respectivement PID, CPU%, MEM%, TIME+ sont utilisés pour le tri. Bien sûr, vous pouvez également utiliser la souris pour effectuer un tri ascendant ou descendant d'un certain champ. + +### Autres utilisations courantes +Pour gérer le processus, utilisez le bouton ++F9++ pour envoyer différents signaux. La liste des signaux peut être affichée avec la commande `kill -l`. Les plus couramment utilisées sont : + +| Signal | Observation | +| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Arrête immédiatement le processus qui redémarre après avoir relu le fichier de configuration | +| 9 | Utilisé pour mettre fin immédiatement à l'exécution du programme, pour terminer le processus de force, similaire à la fin forcée dans la barre des tâches de la fenêtre | +| 15 | Le signal par défaut pour la commande kill. Parfois, si un problème s'est produit dans le processus et que le processus ne peut pas être terminé normalement avec ce signal, on peut essayer le signal 9 | + +## Conclusion +`htop` est beaucoup plus facile à utiliser que la commande `top` qui fait partie du système, il est plus intuitif et améliore grandement l'utilisation au quotidien. C'est pourquoi c'est habituellement la première chose que l'auteur installe après l'installation du système d'exploitation. diff --git a/docs/gemstones/mtr.de.md b/docs/gemstones/mtr.de.md index 49b86b4746..ff70e82621 100644 --- a/docs/gemstones/mtr.de.md +++ b/docs/gemstones/mtr.de.md @@ -1,7 +1,7 @@ --- title: mtr - Netzwerk-Diagnose author: tianci li -contributors: Steven Spencer +contributors: Steven Spencer, Neel Chauhan date: 2021-10-20 --- @@ -61,4 +61,11 @@ HOST: li Loss% Snt Last Avg Best Wrst StDev * StDev - Varianz (Stabilität) ## Tastaturkürzel -p - pause; d - switch display mode; n - turn on/off DNS; r - reset all counters; j - toggle delay display information; y - switch IP information; q - quit. + +* ++p++ - Pause +* ++d++ - Display-Modus umschalten +* ++n++ - DNS ein-/ausschalten +* ++r++ - Alle Zähler zurücksetzen +* ++j++ - Anzeigeinformationen zur Verzögerung umschalten +* ++y++ - IP-Information umschalten +* ++q++ - `mtr` beenden diff --git a/docs/gemstones/mtr.fr.md b/docs/gemstones/mtr.fr.md index 606d112e44..dd7bf72312 100644 --- a/docs/gemstones/mtr.fr.md +++ b/docs/gemstones/mtr.fr.md @@ -1,7 +1,7 @@ --- title: mtr - Logiciel d'Analyse de Réseau author: tianci li -contributors: Steven Spencer +contributors: Steven Spencer, Neel Chauhan date: 2021-10-20 --- @@ -61,4 +61,11 @@ HOST: li Loss% Snt Last Avg Best Wrst StDev * StDev - variance (stabilité) ## Racourcis de clavier -p - pause; d - switch display mode; n - turn on/off DNS; r - reset all counters; j - toggle delay display information; y - switch IP information; q - quit. + +* ++p++ - Pause +* ++d++ - display - mode d'affichage +* ++n++ - Activer/désactiver le DNS +* ++r++ - Remettre tous les compteurs à zéro +* ++j++ - Activer/désactiver les informations d'affichage du délai +* ++y++ - Informations IP +* ++q++ - Quitter `mtr` diff --git a/docs/guides/backup/rsnapshot_backup.it.md b/docs/guides/backup/rsnapshot_backup.it.md index 40ea3f55f3..2a0182064c 100644 --- a/docs/guides/backup/rsnapshot_backup.it.md +++ b/docs/guides/backup/rsnapshot_backup.it.md @@ -242,7 +242,7 @@ Rimuovere il commento: `logfile /var/log/rsnapshot` -Infine, passate alla sezione `### BACKUP POINTS / SCRIPTS ###` e aggiungere le directory che si desidera aggiungere nella sezione `# LOCALHOST`, ricordando di usare TAB anziché SPAZIO tra gli elementi! +Infine, passate alla sezione `### BACKUP POINTS / SCRIPTS ###` e aggiungere le directory che si desidera aggiungere nella sezione `# LOCALHOST`, ricordando di usare ++tab++ anziché ++spazio++ tra gli elementi! Per ora scrivete le vostre modifiche (`SHIFT :wq!` per `vi`) e uscite dal file di configurazione.