Table des matières

Version : 2023.01

Dernière mise-à-jour : 2023/07/14 10:56

LCF902 - Gestion des Utilisateurs et les Archives

Contenu du Module

Présentation

A faire : Afin de mettre en pratique les exemples dans ce cours, vous devez vous connecter à votre système en tant que root grâce à la commande su - et le mot de passe fenestros.

La bonne gestion des utilisateurs passe par une bonne stratégie de groupes. En effet, chaque utilisateur est affecté à un groupe principal mais il peut aussi être membre d'un ou de plusieurs groupes secondaires.

Comme dans d'autres systèmes d'exploitation, sous Linux il est préférable de donner les droits d'accès aux groupes et non aux utilisateurs individuels.

Les bases de données utilisées pour stocker les informations des utilisateurs et des groupes sont stipulées dans le fichier /etc/nsswitch.conf. Dans notre cas les entrées passwd, shadow et group indique le mot clef files. Ceci indique l'utilisation des fichiers suivants en tant que base de données :

/etc/nsswitch.conf sous RHEL 8

[root@centos8 ~]# cat /etc/nsswitch.conf
# Generated by authselect on Mon Apr 19 11:54:28 2021
# Do not modify this file manually.

# If you want to make changes to nsswitch.conf please modify
# /etc/authselect/user-nsswitch.conf and run 'authselect apply-changes'.
#
# Note that your changes may not be applied as they may be
# overwritten by selected profile. Maps set in the authselect
# profile takes always precedence and overwrites the same maps
# set in the user file. Only maps that are not set by the profile
# are applied from the user file.
#
# For example, if the profile sets:
#     passwd: sss files
# and /etc/authselect/user-nsswitch.conf contains:
#     passwd: files
#     hosts: files dns
# the resulting generated nsswitch.conf will be:
#     passwd: sss files # from profile
#     hosts: files dns  # from user file

passwd:     sss files systemd
group:      sss files systemd
netgroup:   sss files
automount:  sss files
services:   sss files
...
shadow:     files sss
...

Dans ce fichier :

Interrogation des Bases de Données

La commande getent est utilisée pour interroger les bases de données. Elle prend la forme suivante :

getent base-de-données clef

Par exemple pour rechercher l'utilisateur dans la base de données des utilisateurs, il convient d'utiliser la commande suivante :

[root@centos8 ~]# getent passwd trainee
trainee:x:1000:1000:trainee:/home/trainee:/bin/bash

Pour rechercher quels utilisateurs appartiennent à quels groupes, il convient d'utiliser la commande suivante :

[root@centos8 ~]# getent group mail
mail:x:12:

L'utilisation de la commande getent sans spécifier une clef imprime à l'écran le contenu de la base de données :

[root@centos8 ~]# getent passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin
systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
polkitd:x:998:996:User for polkitd:/:/sbin/nologin
unbound:x:997:994:Unbound DNS resolver:/etc/unbound:/sbin/nologin
libstoragemgmt:x:996:993:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
cockpit-ws:x:995:991:User for cockpit-ws:/nonexisting:/sbin/nologin
sssd:x:994:990:User for sssd:/:/sbin/nologin
setroubleshoot:x:993:989::/var/lib/setroubleshoot:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
chrony:x:992:988::/var/lib/chrony:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
trainee:x:1000:1000:trainee:/home/trainee:/bin/bash
cockpit-wsinstance:x:991:987:User for cockpit-ws instances:/nonexisting:/sbin/nologin
rngd:x:990:986:Random Number Generator Daemon:/var/lib/rngd:/sbin/nologin
gluster:x:989:985:GlusterFS daemons:/run/gluster:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
dnsmasq:x:983:983:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin

Les Fichiers /etc/group et /etc/gshadow

Pour lister les groupes existants sur le système, saisissez la commande suivante :

[root@centos8 ~]# cat /etc/group
root:x:0:
bin:x:1:
daemon:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mem:x:8:
kmem:x:9:
wheel:x:10:
cdrom:x:11:
mail:x:12:
man:x:15:
dialout:x:18:
floppy:x:19:
games:x:20:
tape:x:33:
video:x:39:
ftp:x:50:
lock:x:54:
audio:x:63:
users:x:100:
nobody:x:65534:
dbus:x:81:
utmp:x:22:
utempter:x:35:
input:x:999:
kvm:x:36:qemu
render:x:998:
systemd-journal:x:190:
systemd-coredump:x:997:
systemd-resolve:x:193:
tss:x:59:
polkitd:x:996:
printadmin:x:995:
unbound:x:994:
libstoragemgmt:x:993:
ssh_keys:x:992:
cockpit-ws:x:991:
sssd:x:990:
setroubleshoot:x:989:
sshd:x:74:
chrony:x:988:
slocate:x:21:
tcpdump:x:72:
trainee:x:1000:
cockpit-wsinstance:x:987:
rngd:x:986:
gluster:x:985:
qemu:x:107:
rpc:x:32:
rpcuser:x:29:
saslauth:x:76:
libvirt:x:984:
radvd:x:75:
dnsmasq:x:983:
screen:x:84:

Important : Notez que la valeur du GID du groupe root est toujours de 0. Notez que sous RHEL / CentOS 8, les GID des utilisateurs normaux commencent à 1000 et les GID des comptes système sont inclus entre 1 et 99 et entre 201 et 999.

Dans ce fichier, chaque ligne est constituée de 4 champs :

Pour consulter le fichier /etc/gshadow, saisissez la commande suivante :

[root@centos8 ~]# cat /etc/gshadow
root:::
bin:::
daemon:::
sys:::
adm:::
tty:::
disk:::
lp:::
mem:::
kmem:::
wheel:::
cdrom:::
mail:::
man:::
dialout:::
floppy:::
games:::
tape:::
video:::
ftp:::
lock:::
audio:::
users:::
nobody:::
dbus:!::
utmp:!::
utempter:!::
input:!::
kvm:!::qemu
render:!::
systemd-journal:!::
systemd-coredump:!::
systemd-resolve:!::
tss:!::
polkitd:!::
printadmin:!::
unbound:!::
libstoragemgmt:!::
ssh_keys:!::
cockpit-ws:!::
sssd:!::
setroubleshoot:!::
sshd:!::
chrony:!::
slocate:!::
tcpdump:!::
trainee:!::
cockpit-wsinstance:!::
rngd:!::
gluster:!::
qemu:!::
rpc:!::
rpcuser:!::
saslauth:!::
libvirt:!::
radvd:!::
dnsmasq:!!::
screen:!::

Chaque ligne est constituée de 4 champs :

Afin de vérifier les fichiers /etc/group et /etc/gshadow pour des erreurs éventuelles, saisissez la commande suivante :

[root@centos8 ~]# grpck -r
[root@centos8 ~]# 

Dans le cas où vos fichiers ne comportent pas d'erreurs, vous vous retrouverez retourné au prompt.

Important : L'option -r permet la vérification des erreurs sans le modifier.

Dans le cas où il est nécessaire de régénérer un des deux fichiers, il convient d'utiliser une des deux commandes suivantes :

Les Fichiers /etc/passwd et /etc/shadow

Important : Notez que la règle la plus libérale concernant les noms d'utilisateurs sous Linux limite la longueur à 32 caractères et permet l'utilisation de majuscules, de minuscules, de nombres (sauf au début du nom) ainsi que la plupart des caractères de ponctuation. Ceci dit, certains utilitaires, tel useradd interdisent l'utilisation de majuscules et de caractères de ponctuation mais permettent l'utilisation des caractères _, . ainsi que le caractère $ à la fin du nom (ATTENTION : dans le cas de samba, un nom d'utilisateur se terminant par $ est considéré comme un compte machine). Qui plus est, certains utilitaires limitent la longueur du nom à 8 caractères.

Pour lister les comptes utilisateur existants sur le système, saisissez la commande suivante :

[root@centos8 ~]# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin
systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
polkitd:x:998:996:User for polkitd:/:/sbin/nologin
unbound:x:997:994:Unbound DNS resolver:/etc/unbound:/sbin/nologin
libstoragemgmt:x:996:993:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
cockpit-ws:x:995:991:User for cockpit-ws:/nonexisting:/sbin/nologin
sssd:x:994:990:User for sssd:/:/sbin/nologin
setroubleshoot:x:993:989::/var/lib/setroubleshoot:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
chrony:x:992:988::/var/lib/chrony:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
trainee:x:1000:1000:trainee:/home/trainee:/bin/bash
cockpit-wsinstance:x:991:987:User for cockpit-ws instances:/nonexisting:/sbin/nologin
rngd:x:990:986:Random Number Generator Daemon:/var/lib/rngd:/sbin/nologin
gluster:x:989:985:GlusterFS daemons:/run/gluster:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
dnsmasq:x:983:983:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin

Important : Notez que la valeur de l'UID de root est toujours de 0. Notez que sous RHEL / CentOS 8, les UID des utilisateurs normaux commencent à 1000 et les UID des comptes système sont inclus entre 1 et 99 et entre 201 et 999.

Chaque ligne est constituée de 7 champs :

Pour consulter le fichier /etc/shadow, saisissez la commande suivante :

[root@centos8 ~]# cat /etc/shadow
root:$6$9Sa1IumuSlJc8EBg$8jGU/4xGCXy64QuBSMyKOC6/FWs41rdY5tzF5/7yHG6FRS2Y2eOJIcst1JbcvNoqMPDU4lpZ6THW97jwGuQNf1::0:99999:7:::
bin:*:18264:0:99999:7:::
daemon:*:18264:0:99999:7:::
adm:*:18264:0:99999:7:::
lp:*:18264:0:99999:7:::
sync:*:18264:0:99999:7:::
shutdown:*:18264:0:99999:7:::
halt:*:18264:0:99999:7:::
mail:*:18264:0:99999:7:::
operator:*:18264:0:99999:7:::
games:*:18264:0:99999:7:::
ftp:*:18264:0:99999:7:::
nobody:*:18264:0:99999:7:::
dbus:!!:18390::::::
systemd-coredump:!!:18390::::::
systemd-resolve:!!:18390::::::
tss:!!:18390::::::
polkitd:!!:18390::::::
unbound:!!:18390::::::
libstoragemgmt:!!:18390::::::
cockpit-ws:!!:18390::::::
sssd:!!:18390::::::
setroubleshoot:!!:18390::::::
sshd:!!:18390::::::
chrony:!!:18390::::::
tcpdump:!!:18390::::::
trainee:$6$p4HOAHX7UAzw1nQh$VZL12Lye.mR8v1IP2e4f0PCW8DzHj2MMAaA7r2ZLoTnQN7Ziskce3bo/xTMu1bXZm5GebJjSw7.X5tABVNoJ2/::0:99999:7:::
cockpit-wsinstance:!!:18736::::::
rngd:!!:18736::::::
gluster:!!:18736::::::
qemu:!!:18736::::::
rpc:!!:18736:0:99999:7:::
rpcuser:!!:18736::::::
saslauth:!!:18736::::::
radvd:!!:18736::::::
dnsmasq:!!:18736::::::

Chaque ligne est constituée de 8 champs :

Afin de vérifier les fichiers /etc/passwd et /etc/shadow pour des erreurs éventuelles, saisissez la commande suivante :

[root@centos8 ~]# pwck -r
user 'cockpit-ws': directory '/nonexisting' does not exist
user 'cockpit-wsinstance': directory '/nonexisting' does not exist
user 'rngd': directory '/var/lib/rngd' does not exist
user 'saslauth': directory '/run/saslauthd' does not exist
pwck: no changes

Important : Les erreurs ci-dessus ne sont pas importantes. Elles sont dues au fait que les répertoires de connexion de certains comptes systèmes ne sont pas créés par le système lors de la création des comptes et ceci justement pour éviter la possibilité qu'un pirate ou un hacker puisse se connecter au système en utilisant le compte concerné. Encore une fois, l'option -r permet la vérification des erreurs dans sans le modifier.

Dans le cas où il est nécessaire de régénérer un des deux fichiers, il convient d'utiliser une des deux commandes suivantes :

Commandes

Groupes

groupadd

Cette commande est utilisée pour créer un groupe.

Options de la commande
[root@centos8 ~]# groupadd --help
Usage: groupadd [options] GROUP

Options:
  -f, --force                   exit successfully if the group already exists,
                                and cancel -g if the GID is already used
  -g, --gid GID                 use GID for the new group
  -h, --help                    display this help message and exit
  -K, --key KEY=VALUE           override /etc/login.defs defaults
  -o, --non-unique              allow to create groups with duplicate
                                (non-unique) GID
  -p, --password PASSWORD       use this encrypted password for the new group
  -r, --system                  create a system account
  -R, --root CHROOT_DIR         directory to chroot into
  -P, --prefix PREFIX_DIR       directory prefix

Important : Il est possible de créer plusieurs groupes ayant le même GID.

Important : Notez l'option -r qui permet la création d'un groupe système.

groupdel

Cette commande est utilisée pour supprimer un groupe.

Options de la commande
[root@centos8 ~]# groupdel --help
Usage: groupdel [options] GROUP

Options:
  -h, --help                    display this help message and exit
  -R, --root CHROOT_DIR         directory to chroot into
  -P, --prefix PREFIX_DIR       prefix directory where are located the /etc/* files
  -f, --force                   delete group even if it is the primary group of a user

groupmod

Cette commande est utilisée pour modifier un groupe existant.

Options de la commande
[root@centos8 ~]# groupmod --help
Usage: groupmod [options] GROUP

Options:
  -g, --gid GID                 change the group ID to GID
  -h, --help                    display this help message and exit
  -n, --new-name NEW_GROUP      change the name to NEW_GROUP
  -o, --non-unique              allow to use a duplicate (non-unique) GID
  -p, --password PASSWORD       change the password to this (encrypted)
                                PASSWORD
  -R, --root CHROOT_DIR         directory to chroot into
  -P, --prefix PREFIX_DIR       prefix directory where are located the /etc/* files

newgrp

Cette commande est utilisée pour modifier le groupe de l'utilisateur qui l'invoque.

Options de la commande
[root@centos8 ~]# newgrp --help
Usage: newgrp [-] [group]

gpasswd

Cette commande est utilisée pour modifier administrer le fichier /etc/group.

Options de la commande
[root@centos8 ~]# gpasswd --help
Usage: gpasswd [option] GROUP

Options:
  -a, --add USER                add USER to GROUP
  -d, --delete USER             remove USER from GROUP
  -h, --help                    display this help message and exit
  -Q, --root CHROOT_DIR         directory to chroot into
  -r, --delete-password         remove the GROUP's password
  -R, --restrict                restrict access to GROUP to its members
  -M, --members USER,...        set the list of members of GROUP
  -A, --administrators ADMIN,...
                                set the list of administrators for GROUP
Except for the -A and -M options, the options cannot be combined.

Utilisateurs

useradd

Cette commande est utilisée pour ajouter un utilisateur.

Les codes retour de la commande useradd sont :

Code Retour Description
1 Impossible de mettre à jour le fichier /etc/passwd
2 Syntaxe invalide
3 Option invalide
4 L'UID demandé est déjà utilisé
6 Le groupe spécifié n'existe pas
9 Le nom d'utilisateur indiqué existe déjà
10 Impossible de mettre à jour le fichier /etc/group
12 Impossible de créer le répertoire personnel de l'utilisateur
13 Impossible de créer le spool mail de l'utilisateur
Options de la commande
[root@centos8 ~]# useradd --help
Usage: useradd [options] LOGIN
       useradd -D
       useradd -D [options]

Options:
  -b, --base-dir BASE_DIR       base directory for the home directory of the
                                new account
  -c, --comment COMMENT         GECOS field of the new account
  -d, --home-dir HOME_DIR       home directory of the new account
  -D, --defaults                print or change default useradd configuration
  -e, --expiredate EXPIRE_DATE  expiration date of the new account
  -f, --inactive INACTIVE       password inactivity period of the new account
  -g, --gid GROUP               name or ID of the primary group of the new
                                account
  -G, --groups GROUPS           list of supplementary groups of the new
                                account
  -h, --help                    display this help message and exit
  -k, --skel SKEL_DIR           use this alternative skeleton directory
  -K, --key KEY=VALUE           override /etc/login.defs defaults
  -l, --no-log-init             do not add the user to the lastlog and
                                faillog databases
  -m, --create-home             create the user's home directory
  -M, --no-create-home          do not create the user's home directory
  -N, --no-user-group           do not create a group with the same name as
                                the user
  -o, --non-unique              allow to create users with duplicate
                                (non-unique) UID
  -p, --password PASSWORD       encrypted password of the new account
  -r, --system                  create a system account
  -R, --root CHROOT_DIR         directory to chroot into
  -P, --prefix PREFIX_DIR       prefix directory where are located the /etc/* files
  -s, --shell SHELL             login shell of the new account
  -u, --uid UID                 user ID of the new account
  -U, --user-group              create a group with the same name as the user
  -Z, --selinux-user SEUSER     use a specific SEUSER for the SELinux user mapping

Important : Il est possible de créer plusieurs utilisateurs ayant le même UID.

Important : Notez l'option -r qui permet la création d'un compte système. Dans ce cas la commande useradd ne crée pas de répertoire personnel.

userdel

Cette commande est utilisée pour supprimer un utilisateur.

Options de la commande
[root@centos8 ~]# userdel --help
Usage: userdel [options] LOGIN

Options:
  -f, --force                   force some actions that would fail otherwise
                                e.g. removal of user still logged in
                                or files, even if not owned by the user
  -h, --help                    display this help message and exit
  -r, --remove                  remove home directory and mail spool
  -R, --root CHROOT_DIR         directory to chroot into
  -P, --prefix PREFIX_DIR       prefix directory where are located the /etc/* files
  -Z, --selinux-user            remove any SELinux user mapping for the user

Important : Notez que lors de la suppression d'un utilisateur, l'UID associé avec ce compte peut être réutilisé. Le nombre maximum de comptes était de 65 536 avec le noyau 2.2.x. Avec les noyaux récents, cette limite passe à plus de 4,2 Milliards.

usermod

Cette commande est utilisée pour modifier un utilisateur existant.

Options de la commande
[root@centos8 ~]# usermod --help
Usage: usermod [options] LOGIN

Options:
  -c, --comment COMMENT         new value of the GECOS field
  -d, --home HOME_DIR           new home directory for the user account
  -e, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE
  -f, --inactive INACTIVE       set password inactive after expiration
                                to INACTIVE
  -g, --gid GROUP               force use GROUP as new primary group
  -G, --groups GROUPS           new list of supplementary GROUPS
  -a, --append                  append the user to the supplemental GROUPS
                                mentioned by the -G option without removing
                                the user from other groups
  -h, --help                    display this help message and exit
  -l, --login NEW_LOGIN         new value of the login name
  -L, --lock                    lock the user account
  -m, --move-home               move contents of the home directory to the
                                new location (use only with -d)
  -o, --non-unique              allow using duplicate (non-unique) UID
  -p, --password PASSWORD       use encrypted password for the new password
  -R, --root CHROOT_DIR         directory to chroot into
  -P, --prefix PREFIX_DIR       prefix directory where are located the /etc/* files
  -s, --shell SHELL             new login shell for the user account
  -u, --uid UID                 new UID for the user account
  -U, --unlock                  unlock the user account
  -v, --add-subuids FIRST-LAST  add range of subordinate uids
  -V, --del-subuids FIRST-LAST  remove range of subordinate uids
  -w, --add-subgids FIRST-LAST  add range of subordinate gids
  -W, --del-subgids FIRST-LAST  remove range of subordinate gids
  -Z, --selinux-user SEUSER     new SELinux user mapping for the user account

Important : Notez l'option -L qui permet de verrouiller un compte.

passwd

Cette commande est utilisée pour créer ou modifier le mot de passe d'un utilisateur.

Options de la commande
[root@centos8 ~]# passwd --help
Usage: passwd [OPTION...] <accountName>
  -k, --keep-tokens       keep non-expired authentication tokens
  -d, --delete            delete the password for the named account (root only); also removes password lock if any
  -l, --lock              lock the password for the named account (root only)
  -u, --unlock            unlock the password for the named account (root only)
  -e, --expire            expire the password for the named account (root only)
  -f, --force             force operation
  -x, --maximum=DAYS      maximum password lifetime (root only)
  -n, --minimum=DAYS      minimum password lifetime (root only)
  -w, --warning=DAYS      number of days warning users receives before password expiration (root only)
  -i, --inactive=DAYS     number of days after password expiration when an account becomes disabled (root only)
  -S, --status            report password status on the named account (root only)
      --stdin             read new tokens from stdin (root only)

Help options:
  -?, --help              Show this help message
      --usage             Display brief usage message

Important : Notez l'option -l qui permet de verrouiller un compte en plaçant le caractère ! devant le mot de passe crypté.

chage

La commande chage modifie le nombre de jours entre les changements de mot de passe et la date du dernier changement. Ces informations sont utilisées par le système pour déterminer si un utilisateur doit changer son mot de passe.

Options de la commande
[root@centos8 ~]# chage --help
Usage: chage [options] LOGIN

Options:
  -d, --lastday LAST_DAY        set date of last password change to LAST_DAY
  -E, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE
  -h, --help                    display this help message and exit
  -I, --inactive INACTIVE       set password inactive after expiration
                                to INACTIVE
  -l, --list                    show account aging information
  -m, --mindays MIN_DAYS        set minimum number of days before password
                                change to MIN_DAYS
  -M, --maxdays MAX_DAYS        set maximum number of days before password
                                change to MAX_DAYS
  -R, --root CHROOT_DIR         directory to chroot into
  -W, --warndays WARN_DAYS      set expiration warning days to WARN_DAYS

Configuration

La commande useradd est configurée par le fichier /etc/default/useradd. Pour consulter ce fichier, saisissez la commande suivante :

[root@centos8 ~]# cat /etc/default/useradd
# useradd defaults file
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes

Dans ce fichier, nous trouvons les directives suivantes :

Cette même information peut être visualisée en exécutant la commande useradd avec l'option -D :

[root@centos8 ~]# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes

Pour consulter la liste des fichiers dans /etc/skel, saisissez la commande suivante :

[root@centos8 ~]# ls -la /etc/skel
total 24
drwxr-xr-x.   2 root root   62 Apr 19 11:50 .
drwxr-xr-x. 106 root root 8192 Apr 20 10:17 ..
-rw-r--r--.   1 root root   18 Jul 21  2020 .bash_logout
-rw-r--r--.   1 root root  141 Jul 21  2020 .bash_profile
-rw-r--r--.   1 root root  376 Jul 21  2020 .bashrc

Important : Notez que sous RHEL / CentOS le fichier .bash_profile remplace le fichier .profile.

Pour connaître l'UID, le GID et l'appartenance aux groupes d'un utilisateur, il convient d'utiliser la commande id. Saisissez la commande suivante :

[root@centos8 ~]# id trainee
uid=1000(trainee) gid=1000(trainee) groups=1000(trainee)

Pour seulement connaître les groupes d'un utilisateur, il convient d'utiliser la commande groups. Saisissez la commande suivante :

[root@centos8 ~]# groups trainee
trainee : trainee

Les valeurs minimales de l'UID et du GID utilisés par défaut lors de la création d'un utilisateur sont stipulées dans le fichier /etc/login.defs :

...
#
# Min/max values for automatic uid selection in useradd
#
UID_MIN                  1000
UID_MAX                 60000
# System accounts
SYS_UID_MIN               201
SYS_UID_MAX               999

#
# Min/max values for automatic gid selection in groupadd
#
GID_MIN                  1000
GID_MAX                 60000
# System accounts
SYS_GID_MIN               201
SYS_GID_MAX               999
...

LAB #1 - Gérer les Utilisateurs et les Groupes

Créez maintenant trois groupes groupe1, groupe2 et groupe3. La valeur du GID du groupe groupe3 doit être de 1807 :

[root@centos8 ~]# groupadd groupe1; groupadd groupe2; groupadd -g 1807 groupe3

Créez maintenant trois utilisateurs fenestros1, fenestros2 et fenestros3. Les trois utilisateurs ont pour groupe principal groupe1, groupe2 et groupe3 respectivement. fenestros2 est aussi membre des groupes groupe1 et groupe3. fenestros1 à un GECOS de tux1 :

[root@centos8 ~]# useradd -g groupe2 fenestros2; useradd -g 1807 fenestros3; useradd -g groupe1 fenestros1
[root@centos8 ~]# usermod -G groupe1,groupe3 fenestros2
[root@centos8 ~]# usermod -c "tux1" fenestros1

En consultant votre fichier /etc/passwd, vous obtiendrez un résultat similaire à celui-ci:

[root@centos8 ~]# tail /etc/passwd
gluster:x:989:985:GlusterFS daemons:/run/gluster:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
dnsmasq:x:983:983:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin
fenestros2:x:1001:1002::/home/fenestros2:/bin/bash
fenestros3:x:1002:1807::/home/fenestros3:/bin/bash
fenestros1:x:1003:1001:tux1:/home/fenestros1:/bin/bash

En regardant votre fichier /etc/group, vous obtiendrez un résultat similaire à celui-ci:

[root@centos8 ~]# tail /etc/group
rpc:x:32:
rpcuser:x:29:
saslauth:x:76:
libvirt:x:984:
radvd:x:75:
dnsmasq:x:983:
screen:x:84:
groupe1:x:1001:fenestros2
groupe2:x:1002:
groupe3:x:1807:fenestros2

Créez le mot de passe fenestros pour le groupe3 :

[root@centos8 ~]# gpasswd groupe3
Changing the password for group groupe3
New Password: fenestros
Re-enter new password: fenestros 

Important : Notez que les mots de passe saisis ne seront pas visibles.

Consultez le fichier /etc/gshadow :

[root@centos8 ~]# tail /etc/gshadow
rpc:!::
rpcuser:!::
saslauth:!::
libvirt:!::
radvd:!::
dnsmasq:!!::
screen:!::
groupe1:!::fenestros2
groupe2:!::
groupe3:$6$c0nWuaO.7BveY$qZ907ORU.vEOhlYcka.VCL1Im0obgxJg8g3SvWnEA3YiZc9TB3CXEU/8nnNNAg5fBAhct7PNUXdPXwsSsY0Zg0::fenestros2

Important : Notez la présence du mot de passe crypté pour le groupe3.

Nommez maintenant fenestros1 administrateur du groupe3 :

[root@centos8 ~]# gpasswd -A fenestros1 groupe3

Consultez le fichier /etc/gshadow de nouveau :

[root@centos8 ~]# tail /etc/gshadow
rpc:!::
rpcuser:!::
saslauth:!::
libvirt:!::
radvd:!::
dnsmasq:!!::
screen:!::
groupe1:!::fenestros2
groupe2:!::
groupe3:$6$c0nWuaO.7BveY$qZ907ORU.vEOhlYcka.VCL1Im0obgxJg8g3SvWnEA3YiZc9TB3CXEU/8nnNNAg5fBAhct7PNUXdPXwsSsY0Zg0:fenestros1:fenestros2

Important : L'utilisateur fenestros1 peut maintenant administrer le groupe groupe3 en y ajoutant ou en y supprimant des utilisateurs à condition de connaître le mot de passe du groupe.

Essayez maintenant de supprimer le groupe groupe3 :

[root@centos8 ~]# groupdel groupe3
groupdel: cannot remove the primary group of user 'fenestros3'

Important : En effet, vous ne pouvez pas supprimer un groupe tant qu'un utilisateur le possède comme son groupe principal.

Supprimez donc l'utilisateur fenestros3 :

[root@centos8 ~]# userdel fenestros3

Ensuite essayez de supprimer le groupe groupe3 :

[root@centos8 ~]# groupdel groupe3

Important : Notez que cette fois-ci la commande est exécutée sans erreur.

Le fait de supprimer un utilisateur sans l'option -r implique que le répertoire personnel de l'utilisateur demeure sur le système.

Saisissez la commande suivante sous RHEL / CentOS 8 pour vérifier :

[root@centos8 ~]# ls -ld /home/fenestros3
drwx------. 2 1002 groupe3 62 Apr 20 14:28 /home/fenestros3

Pour supprimer les fichiers de cet utilisateur, il convient de saisir la commande suivante :

[root@centos8 ~]# find /home -user 1002 -exec rm -rf {} \;
find: ‘/home/fenestros3’: No such file or directory
[root@centos8 ~]# ls -ld /home/fenestros3
ls: cannot access '/home/fenestros3': No such file or directory

Important : La commande find est lancée d'une manière itérative. L'erreur est normale car quand la commande find ne trouve plus de fichiers à supprimer, elle s’arrête avec un code retour de 2.

Créez maintenant les mots de passe pour fenestros1 et fenestros2. Indiquez un mot de passe identique au nom du compte :

[root@centos8 ~]# passwd fenestros1
Changing password for user fenestros1.
New password: fenestros1
BAD PASSWORD: The password contains the user name in some form
Retype new password: fenestros1
passwd: all authentication tokens updated successfully.
[root@centos8 ~]# passwd fenestros2
Changing password for user fenestros2.
New password: fenestros2
BAD PASSWORD: The password contains the user name in some form
Retype new password: fenestros2
passwd: all authentication tokens updated successfully.

Important : Notez que les règles gouvernant l'utilisation des mots de passe ne sont pas appliqués aux utilisateurs créés par root. Notez aussi que les mots de passe saisis ne seront PAS visibles.

Outils classiques de sauvegarde

Préparation

Afin de poursuivre, il convient de créer une arborescence à sauvegarder :

[root@centos8 ~]# mkdir -p /test/repY; mkdir /test/repZ
[root@centos8 ~]# cd /test/repY; touch Y1 Y2 Y3
[root@centos8 repY]# cd /test/repZ; touch Z1 Z2
[root@centos8 repZ]# ls -lR /test
/test:
total 0
drwxr-xr-x. 2 root root 36 Jun  2 14:05 repY
drwxr-xr-x. 2 root root 26 Jun  2 14:05 repZ

/test/repY:
total 0
-rw-r--r--. 1 root root 0 Jun  2 14:05 Y1
-rw-r--r--. 1 root root 0 Jun  2 14:05 Y2
-rw-r--r--. 1 root root 0 Jun  2 14:05 Y3

/test/repZ:
total 0
-rw-r--r--. 1 root root 0 Jun  2 14:05 Z1
-rw-r--r--. 1 root root 0 Jun  2 14:05 Z2

La Commande tar

Présentation

Le programme tar a été originellement prévu pour sauvegarder sur des bandes magnétiques, d'où son nom issu de tape archiver.

La commande tar peut sauvegarder vers :

Options de la Commande

Les options de la commande tar sont :

[root@centos8 repZ]# tar --help
Usage: tar [OPTION...] [FILE]...
GNU 'tar' saves many files together into a single tape or disk archive, and can
restore individual files from the archive.

Examples:
  tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.
  tar -tvf archive.tar         # List all files in archive.tar verbosely.
  tar -xf archive.tar          # Extract all files from archive.tar.

 Local file name selection:

      --add-file=FILE        add given FILE to the archive (useful if its name
                             starts with a dash)
  -C, --directory=DIR        change to directory DIR
      --exclude=PATTERN      exclude files, given as a PATTERN
      --exclude-backups      exclude backup and lock files
      --exclude-caches       exclude contents of directories containing
                             CACHEDIR.TAG, except for the tag file itself
      --exclude-caches-all   exclude directories containing CACHEDIR.TAG
      --exclude-caches-under exclude everything under directories containing
                             CACHEDIR.TAG
      --exclude-ignore=FILE  read exclude patterns for each directory from
                             FILE, if it exists
      --exclude-ignore-recursive=FILE
                             read exclude patterns for each directory and its
                             subdirectories from FILE, if it exists
      --exclude-tag=FILE     exclude contents of directories containing FILE,
                             except for FILE itself
      --exclude-tag-all=FILE exclude directories containing FILE
      --exclude-tag-under=FILE   exclude everything under directories
                             containing FILE
      --exclude-vcs          exclude version control system directories
      --exclude-vcs-ignores  read exclude patterns from the VCS ignore files
      --no-null              disable the effect of the previous --null option
      --no-recursion         avoid descending automatically in directories
      --no-unquote           do not unquote input file or member names
      --no-verbatim-files-from   -T treats file names starting with dash as
                             options (default)
      --null                 -T reads null-terminated names; implies
                             --verbatim-files-from
      --recursion            recurse into directories (default)
  -T, --files-from=FILE      get names to extract or create from FILE
      --unquote              unquote input file or member names (default)
      --verbatim-files-from  -T reads file names verbatim (no escape or option
                             handling)
  -X, --exclude-from=FILE    exclude patterns listed in FILE

 File name matching options (affect both exclude and include patterns):

      --anchored             patterns match file name start
      --ignore-case          ignore case
      --no-anchored          patterns match after any '/' (default for
                             exclusion)
      --no-ignore-case       case sensitive matching (default)
      --no-wildcards         verbatim string matching
      --no-wildcards-match-slash   wildcards do not match '/'
      --wildcards            use wildcards (default)
      --wildcards-match-slash   wildcards match '/' (default for exclusion)

 Main operation mode:

  -A, --catenate, --concatenate   append tar files to an archive
  -c, --create               create a new archive
  -d, --diff, --compare      find differences between archive and file system
      --delete               delete from the archive (not on mag tapes!)
  -r, --append               append files to the end of an archive
  -t, --list                 list the contents of an archive
      --test-label           test the archive volume label and exit
  -u, --update               only append files newer than copy in archive
  -x, --extract, --get       extract files from an archive

 Operation modifiers:

      --check-device         check device numbers when creating incremental
                             archives (default)
  -g, --listed-incremental=FILE   handle new GNU-format incremental backup
  -G, --incremental          handle old GNU-format incremental backup
      --hole-detection=TYPE  technique to detect holes
      --ignore-failed-read   do not exit with nonzero on unreadable files
      --level=NUMBER         dump level for created listed-incremental archive
  -n, --seek                 archive is seekable
      --no-check-device      do not check device numbers when creating
                             incremental archives
      --no-seek              archive is not seekable
      --occurrence[=NUMBER]  process only the NUMBERth occurrence of each file
                             in the archive; this option is valid only in
                             conjunction with one of the subcommands --delete,
                             --diff, --extract or --list and when a list of
                             files is given either on the command line or via
                             the -T option; NUMBER defaults to 1
      --sparse-version=MAJOR[.MINOR]
                             set version of the sparse format to use (implies
                             --sparse)
  -S, --sparse               handle sparse files efficiently

 Overwrite control:

  -k, --keep-old-files       don't replace existing files when extracting,
                             treat them as errors
      --keep-directory-symlink   preserve existing symlinks to directories when
                             extracting
      --keep-newer-files     don't replace existing files that are newer than
                             their archive copies
      --no-overwrite-dir     preserve metadata of existing directories
      --one-top-level[=DIR]  create a subdirectory to avoid having loose files
                             extracted
      --overwrite            overwrite existing files when extracting
      --overwrite-dir        overwrite metadata of existing directories when
                             extracting (default)
      --recursive-unlink     empty hierarchies prior to extracting directory
      --remove-files         remove files after adding them to the archive
      --skip-old-files       don't replace existing files when extracting,
                             silently skip over them
  -U, --unlink-first         remove each file prior to extracting over it
  -W, --verify               attempt to verify the archive after writing it

 Select output stream:

      --ignore-command-error ignore exit codes of children
      --no-ignore-command-error   treat non-zero exit codes of children as
                             error
  -O, --to-stdout            extract files to standard output
      --to-command=COMMAND   pipe extracted files to another program

 Handling of file attributes:

      --atime-preserve[=METHOD]   preserve access times on dumped files, either
                             by restoring the times after reading
                             (METHOD='replace'; default) or by not setting the
                             times in the first place (METHOD='system')
      --clamp-mtime          only set time when the file is more recent than
                             what was given with --mtime
      --delay-directory-restore   delay setting modification times and
                             permissions of extracted directories until the end
                             of extraction
      --group=NAME           force NAME as group for added files
      --group-map=FILE       use FILE to map file owner GIDs and names
      --mode=CHANGES         force (symbolic) mode CHANGES for added files
      --mtime=DATE-OR-FILE   set mtime for added files from DATE-OR-FILE
  -m, --touch                don't extract file modified time
      --no-delay-directory-restore
                             cancel the effect of --delay-directory-restore
                             option
      --no-same-owner        extract files as yourself (default for ordinary
                             users)
      --no-same-permissions  apply the user's umask when extracting permissions
                             from the archive (default for ordinary users)
      --numeric-owner        always use numbers for user/group names
      --owner=NAME           force NAME as owner for added files
      --owner-map=FILE       use FILE to map file owner UIDs and names
  -p, --preserve-permissions, --same-permissions
                             extract information about file permissions
                             (default for superuser)
      --same-owner           try extracting files with the same ownership as
                             exists in the archive (default for superuser)
  -s, --preserve-order, --same-order
                             member arguments are listed in the same order as
                             the files in the archive
      --sort=ORDER           directory sorting order: none (default), name or
                             inode

 Handling of extended file attributes:

      --acls                 Enable the POSIX ACLs support
      --no-acls              Disable the POSIX ACLs support
      --no-selinux           Disable the SELinux context support
      --no-xattrs            Disable extended attributes support
      --selinux              Enable the SELinux context support
      --xattrs               Enable extended attributes support
      --xattrs-exclude=MASK  specify the exclude pattern for xattr keys
      --xattrs-include=MASK  specify the include pattern for xattr keys

 Device selection and switching:

  -f, --file=ARCHIVE         use archive file or device ARCHIVE
      --force-local          archive file is local even if it has a colon
  -F, --info-script=NAME, --new-volume-script=NAME
                             run script at end of each tape (implies -M)
  -L, --tape-length=NUMBER   change tape after writing NUMBER x 1024 bytes
  -M, --multi-volume         create/list/extract multi-volume archive
      --rmt-command=COMMAND  use given rmt COMMAND instead of rmt
      --rsh-command=COMMAND  use remote COMMAND instead of rsh
      --volno-file=FILE      use/update the volume number in FILE

 Device blocking:

  -b, --blocking-factor=BLOCKS   BLOCKS x 512 bytes per record
  -B, --read-full-records    reblock as we read (for 4.2BSD pipes)
  -i, --ignore-zeros         ignore zeroed blocks in archive (means EOF)
      --record-size=NUMBER   NUMBER of bytes per record, multiple of 512

 Archive format selection:

  -H, --format=FORMAT        create archive of the given format

 FORMAT is one of the following:

    gnu                      GNU tar 1.13.x format
    oldgnu                   GNU format as per tar <= 1.12
    pax                      POSIX 1003.1-2001 (pax) format
    posix                    same as pax
    ustar                    POSIX 1003.1-1988 (ustar) format
    v7                       old V7 tar format

      --old-archive, --portability
                             same as --format=v7
      --pax-option=keyword[[:]=value][,keyword[[:]=value]]...
                             control pax keywords
      --posix                same as --format=posix
  -V, --label=TEXT           create archive with volume name TEXT; at
                             list/extract time, use TEXT as a globbing pattern
                             for volume name

 Compression options:

  -a, --auto-compress        use archive suffix to determine the compression
                             program
  -I, --use-compress-program=PROG
                             filter through PROG (must accept -d)
  -j, --bzip2                filter the archive through bzip2
  -J, --xz                   filter the archive through xz
      --lzip                 filter the archive through lzip
      --lzma                 filter the archive through xz --format=lzma
      --lzop                 filter the archive through lzop
      --no-auto-compress     do not use archive suffix to determine the
                             compression program
  -z, --gzip, --gunzip, --ungzip   filter the archive through gzip
  -Z, --compress, --uncompress   filter the archive through compress

 Local file selection:

      --backup[=CONTROL]     backup before removal, choose version CONTROL
  -h, --dereference          follow symlinks; archive and dump the files they
                             point to
      --hard-dereference     follow hard links; archive and dump the files they
                             refer to
  -K, --starting-file=MEMBER-NAME
                             begin at member MEMBER-NAME when reading the
                             archive
      --newer-mtime=DATE     compare date and time when data changed only
  -N, --newer=DATE-OR-FILE, --after-date=DATE-OR-FILE
                             only store files newer than DATE-OR-FILE
      --one-file-system      stay in local file system when creating archive
  -P, --absolute-names       don't strip leading '/'s from file names
      --suffix=STRING        backup before removal, override usual suffix ('~'
                             unless overridden by environment variable
                             SIMPLE_BACKUP_SUFFIX)

 File name transformations:

      --strip-components=NUMBER   strip NUMBER leading components from file
                             names on extraction
      --transform=EXPRESSION, --xform=EXPRESSION
                             use sed replace EXPRESSION to transform file
                             names

 Informative output:

      --checkpoint[=NUMBER]  display progress messages every NUMBERth record
                             (default 10)
      --checkpoint-action=ACTION   execute ACTION on each checkpoint
      --full-time            print file time to its full resolution
      --index-file=FILE      send verbose output to FILE
  -l, --check-links          print a message if not all links are dumped
      --no-quote-chars=STRING   disable quoting for characters from STRING
      --quote-chars=STRING   additionally quote characters from STRING
      --quoting-style=STYLE  set name quoting style; see below for valid STYLE
                             values
  -R, --block-number         show block number within archive with each message
                            
      --show-defaults        show tar defaults
      --show-omitted-dirs    when listing or extracting, list each directory
                             that does not match search criteria
      --show-snapshot-field-ranges
                             show valid ranges for snapshot-file fields
      --show-transformed-names, --show-stored-names
                             show file or archive names after transformation
      --totals[=SIGNAL]      print total bytes after processing the archive;
                             with an argument - print total bytes when this
                             SIGNAL is delivered; Allowed signals are: SIGHUP,
                             SIGQUIT, SIGINT, SIGUSR1 and SIGUSR2; the names
                             without SIG prefix are also accepted
      --utc                  print file modification times in UTC
  -v, --verbose              verbosely list files processed
      --warning=KEYWORD      warning control
  -w, --interactive, --confirmation
                             ask for confirmation for every action

 Compatibility options:

  -o                         when creating, same as --old-archive; when
                             extracting, same as --no-same-owner

 Other options:

  -?, --help                 give this help list
      --restrict             disable use of some potentially harmful options
      --usage                give a short usage message
      --version              print program version

Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.

The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.
The version control may be set with --backup or VERSION_CONTROL, values are:

  none, off       never make backups
  t, numbered     make numbered backups
  nil, existing   numbered if numbered backups exist, simple otherwise
  never, simple   always make simple backups

Valid arguments for the --quoting-style option are:

  literal
  shell
  shell-always
  shell-escape
  shell-escape-always
  c
  c-maybe
  escape
  locale
  clocale

*This* tar defaults to:
--format=gnu -f- -b20 --quoting-style=escape --rmt-command=/etc/rmt
--rsh-command=/usr/bin/ssh

LAB #1 - Travailler avec la Commande tar

Vous allez maintenant sauvegarder votre dossier test ainsi que son contenu vers un fichier :

[root@centos8 repZ]# tar cvf /tmp/test.tar /test
tar: Removing leading `/' from member names
/test/
/test/repY/
/test/repY/Y1
/test/repY/Y2
/test/repY/Y3
/test/repZ/
/test/repZ/Z1
/test/repZ/Z2

Pour visualiser la table of contents de votre sauvegarde, utilisez la commande suivante :

[root@centos8 repZ]# tar tvf /tmp/test.tar
drwxr-xr-x root/root         0 2021-06-02 14:04 test/
drwxr-xr-x root/root         0 2021-06-02 14:05 test/repY/
-rw-r--r-- root/root         0 2021-06-02 14:05 test/repY/Y1
-rw-r--r-- root/root         0 2021-06-02 14:05 test/repY/Y2
-rw-r--r-- root/root         0 2021-06-02 14:05 test/repY/Y3
drwxr-xr-x root/root         0 2021-06-02 14:05 test/repZ/
-rw-r--r-- root/root         0 2021-06-02 14:05 test/repZ/Z1
-rw-r--r-- root/root         0 2021-06-02 14:05 test/repZ/Z2

Afin de créer une sauvegarde incrémentale, vous avez besoin de créer un fichier qui servira de référence de date :

[root@centos8 repZ]# touch /tmp/dateref

Modifiez maintenant deux des fichiers de votre arborescence test :

[root@centos8 repZ]# echo "CentOS est super \!" > /test/repY/Y1
[root@centos8 repZ]# echo "RHEL is wonderful \!" > /test/repZ/Z1

Pour procéder à votre sauvegarde incrémentale, vous devez sauvegarder uniquement les fichiers modifiés ou créés depuis la création de votre fichier /tmp/dateref.

Saisissez donc la commande suivante :

[root@centos8 repZ]# tar -cvf /tmp/incremental.tar -N /tmp/dateref /test
tar: Removing leading `/' from member names
/test/
/test/repY/
/test/repY/Y1
tar: /test/repY/Y2: file is unchanged; not dumped
tar: /test/repY/Y3: file is unchanged; not dumped
/test/repZ/
/test/repZ/Z1
tar: /test/repZ/Z2: file is unchanged; not dumped

Important - Notez l'utilisation de l'option -N avec l’argument /tmp/dateref qui permet d'identifier les fichiers modifiés ou créés depuis la création de /tmp/dateref.

Contrôlez maintenant le contenu de l'archive /tmp/incremental.tar :

[root@centos8 repZ]# tar tvf /tmp/incremental.tar
drwxr-xr-x root/root         0 2021-06-02 14:04 test/
drwxr-xr-x root/root         0 2021-06-02 14:05 test/repY/
-rw-r--r-- root/root        20 2021-06-02 14:08 test/repY/Y1
drwxr-xr-x root/root         0 2021-06-02 14:05 test/repZ/
-rw-r--r-- root/root        21 2021-06-02 14:09 test/repZ/Z1

Supprimez maintenant le contenu du répertoire test :

[root@centos8 repZ]# rm -rf /test/*

Important - Notez que le système vous permet de supprimer le répertoire /test/repZ, or vous vous situez dans ce même répertoire !

Afin de pouvoir restaurer les fichiers de votre première sauvegarde, placez-vous à la racine de votre système et restaurez le contenu de votre répertoire test en saisissant la commande tar suivante :

[root@centos8 repZ]# cd /
[root@centos8 /]# tar xvf /tmp/test.tar
test/
test/repY/
test/repY/Y1
test/repY/Y2
test/repY/Y3
test/repZ/
test/repZ/Z1
test/repZ/Z2

Constatez maintenant que l'opération s'est bien déroulée :

[root@centos8 /]# ls -lR /test
/test:
total 0
drwxr-xr-x. 2 root root 36 Jun  2 14:05 repY
drwxr-xr-x. 2 root root 26 Jun  2 14:05 repZ

/test/repY:
total 0
-rw-r--r--. 1 root root 0 Jun  2 14:05 Y1
-rw-r--r--. 1 root root 0 Jun  2 14:05 Y2
-rw-r--r--. 1 root root 0 Jun  2 14:05 Y3

/test/repZ:
total 0
-rw-r--r--. 1 root root 0 Jun  2 14:05 Z1
-rw-r--r--. 1 root root 0 Jun  2 14:05 Z2

Important - Notez qu'à ce stade les fichiers /test/repY/Y1 et /test/repZ/Z1 sont vides.

Restaurez maintenant votre archive incrémentale :

[root@centos8 /]# tar xvf /tmp/incremental.tar
test/
test/repY/
test/repY/Y1
test/repZ/
test/repZ/Z1

Constatez maintenant que l'opération s'est bien déroulée :

[root@centos8 /]# ls -lR /test
/test:
total 0
drwxr-xr-x. 2 root root 36 Jun  2 14:05 repY
drwxr-xr-x. 2 root root 26 Jun  2 14:05 repZ

/test/repY:
total 4
-rw-r--r--. 1 root root 20 Jun  2 14:08 Y1
-rw-r--r--. 1 root root  0 Jun  2 14:05 Y2
-rw-r--r--. 1 root root  0 Jun  2 14:05 Y3

/test/repZ:
total 4
-rw-r--r--. 1 root root 21 Jun  2 14:09 Z1
-rw-r--r--. 1 root root  0 Jun  2 14:05 Z2

Important - Notez que les fichiers /test/repY/Y1 et /test/repZ/Z1 sont maintenant non-vides.

La Commande GPL tar et la Compression

Dernièrement, la commande tar peut archiver en utilisant des algorithmes de compression :

Algorythme Option de la commande tar
gzip z
bzip2 j
lzma J

La Commande cpio

Présentation

La commande cpio (Copy Input To Output). cpio peut gérer les archives au format tar. La différence majeure entre tar et cpio est que ce dernier stocke les chemins d'accès aux fichiers sauvgardés en même temps que les fichiers eux-mêmes. Ceci implique que dans le cas où le chemin absolu a été spécifié lors de la sauvegarde, il est impossible de restaurer un fichier à un autre emplacement que son emplacement d'origine.

Vous allez utiliser maintenant le logiciel cpio pour effectuer les sauvegardes et restaurations.

Options de la Commande

Les options de la commande cpio sont :

[root@centos8 /]# cpio --help
Usage: cpio [OPTION...] [destination-directory]
GNU `cpio' copies files to and from archives

Examples:
  # Copy files named in name-list to the archive
  cpio -o < name-list [> archive]
  # Extract files from the archive
  cpio -i [< archive]
  # Copy files named in name-list to destination-directory
  cpio -p destination-directory < name-list

 Main operation mode:
  -i, --extract              Extract files from an archive (run in copy-in
                             mode)
  -o, --create               Create the archive (run in copy-out mode)
  -p, --pass-through         Run in copy-pass mode
  -t, --list                 Print a table of contents of the input

 Operation modifiers valid in any mode:

      --block-size=BLOCK-SIZE   Set the I/O block size to BLOCK-SIZE * 512
                             bytes
  -B                         Set the I/O block size to 5120 bytes
  -c                         Identical to "-H newc", use the new (SVR4)
                             portable format. If you wish the old portable
                             (ASCII) archive format, use "-H odc" instead.
  -C, --io-size=NUMBER       Set the I/O block size to the given NUMBER of
                             bytes
  -D, --directory=DIR        Change to directory DIR
      --force-local          Archive file is local, even if its name contains
                             colons
  -H, --format=FORMAT        Use given archive FORMAT
      --quiet                Do not print the number of blocks copied
  -R, --owner=[USER][:.][GROUP]   Set the ownership of all files created to the
                             specified USER and/or GROUP
  -v, --verbose              Verbosely list the files processed
  -V, --dot                  Print a "." for each file processed
  -W, --warning=FLAG         Control warning display. Currently FLAG is one of
                             'none', 'truncate', 'all'. Multiple options
                             accumulate.

 Operation modifiers valid in copy-in and copy-out modes

  -F, --file=[[USER@]HOST:]FILE-NAME
                             Use this FILE-NAME instead of standard input or
                             output. Optional USER and HOST specify the user
                             and host names in case of a remote archive
  -M, --message=STRING       Print STRING when the end of a volume of the
                             backup media is reached
      --rsh-command=COMMAND  Use COMMAND instead of rsh

 Operation modifiers valid only in copy-in mode:

  -b, --swap                 Swap both halfwords of words and bytes of
                             halfwords in the data. Equivalent to -sS
  -f, --nonmatching          Only copy files that do not match any of the given
                             patterns
  -I [[USER@]HOST:]FILE-NAME Archive filename to use instead of standard input.
                             Optional USER and HOST specify the user and host
                             names in case of a remote archive
  -n, --numeric-uid-gid      In the verbose table of contents listing, show
                             numeric UID and GID
  -r, --rename               Interactively rename files
  -s, --swap-bytes           Swap the bytes of each halfword in the files
  -S, --swap-halfwords       Swap the halfwords of each word (4 bytes) in the
                             files
      --to-stdout            Extract files to standard output

  -E, --pattern-file=FILE    Read additional patterns specifying filenames to
                             extract or list from FILE
      --only-verify-crc      When reading a CRC format archive, only verify the
                             checksum of each file in the archive, don't
                             actually extract the files

 Operation modifiers valid only in copy-out mode:

  -A, --append               Append to an existing archive.
      --device-independent, --reproducible
                             Create device-independent (reproducible) archives
      --ignore-devno         Don't store device numbers
  -O [[USER@]HOST:]FILE-NAME Archive filename to use instead of standard
                             output. Optional USER and HOST specify the user
                             and host names in case of a remote archive
      --renumber-inodes      Renumber inodes

 Operation modifiers valid only in copy-pass mode:

  -l, --link                 Link files instead of copying them, when
                             possible

 Operation modifiers valid in copy-in and copy-out modes:

      --absolute-filenames   Do not strip file system prefix components from
                             the file names
      --no-absolute-filenames   Create all files relative to the current
                             directory

 Operation modifiers valid in copy-out and copy-pass modes:

  -0, --null                 Filenames in the list are delimited by null
                             characters instead of newlines
  -a, --reset-access-time    Reset the access times of files after reading
                             them
  -L, --dereference          Dereference  symbolic  links  (copy  the files
                             that they point to instead of copying the links).

 Operation modifiers valid in copy-in and copy-pass modes:

  -d, --make-directories     Create leading directories where needed
  -m, --preserve-modification-time
                             Retain previous file modification times when
                             creating files
      --no-preserve-owner    Do not change the ownership of the files
      --sparse               Write files with large blocks of zeros as sparse
                             files
  -u, --unconditional        Replace all files unconditionally

  -?, --help                 give this help list
      --usage                give a short usage message
      --version              print program version

Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.

Report bugs to <bug-cpio@gnu.org>.

LAB #2 - Travailler avec la Commande cpio

Dans un premier temps, vous devez utiliser la commande find pour construire une liste de fichiers à sauvegarder :

[root@centos8 /]# find /test > /tmp/cpio.list
[root@centos8 /]# cat /tmp/cpio.list
/test
/test/repY
/test/repY/Y2
/test/repY/Y3
/test/repY/Y1
/test/repZ
/test/repZ/Z2
/test/repZ/Z1

Sauvegardez maintenant les fichiers et répertoires référencés par le fichier /tmp/cpio.list :

[root@centos8 /]# cpio -ov < /tmp/cpio.list > /tmp/test.cpio
/test
/test/repY
/test/repY/Y2
/test/repY/Y3
/test/repY/Y1
/test/repZ
/test/repZ/Z2
/test/repZ/Z1
1 block

Consultez maintenant la table of contents de votre sauvegarde :

[root@centos8 /]# cpio -it < /tmp/test.cpio
/test
/test/repY
/test/repY/Y2
/test/repY/Y3
/test/repY/Y1
/test/repZ
/test/repZ/Z2
/test/repZ/Z1
1 block

Supprimez maintenant le répertoire /test/repY et son contenu :

[root@centos8 /]# rm -rf /test/repY

Contrôlez le bon déroulement de la suppression :

[root@centos8 /]# ls -lR /test
/test:
total 0
drwxr-xr-x. 2 root root 26 Jun  2 14:05 repZ

/test/repZ:
total 4
-rw-r--r--. 1 root root 21 Jun  2 14:09 Z1
-rw-r--r--. 1 root root  0 Jun  2 14:05 Z2

Restaurez les fichiers supprimés :

[root@centos8 /]# cpio -ivdum "/test/repY/*" < /tmp/test.cpio
/test/repY/Y2
/test/repY/Y3
/test/repY/Y1
1 block

Important - Notez l'utilisation de la chaîne “/test/repY/*” qui permet de rechercher uniquement le répertoire repY ainsi que les fichiers Y1, Y2 et Y3 dans l'archive test.cpio.

Contrôlez le bon déroulement de la restauration :

[root@centos8 /]# ls -lR /test
/test:
total 0
drwxr-xr-x. 2 root root 36 Jun  2 14:17 repY
drwxr-xr-x. 2 root root 26 Jun  2 14:05 repZ

/test/repY:
total 4
-rw-r--r--. 1 root root 20 Jun  2 14:08 Y1
-rw-r--r--. 1 root root  0 Jun  2 14:05 Y2
-rw-r--r--. 1 root root  0 Jun  2 14:05 Y3

/test/repZ:
total 4
-rw-r--r--. 1 root root 21 Jun  2 14:09 Z1
-rw-r--r--. 1 root root  0 Jun  2 14:05 Z2

La Commande dd

Présentation

La commande dd n'est pas réellement une commande de sauvegarde.

La commande dd copie le fichier passé en entrée dans le fichier de sortie en limitant le nombre d'octets copiés par l'utilisation de deux options :

Options de la Commande

Les options de la commande dd sont :

[root@centos8 /]# dd --help
Usage: dd [OPERAND]...
  or:  dd OPTION
Copy a file, converting and formatting according to the operands.

  bs=BYTES        read and write up to BYTES bytes at a time (default: 512);
                  overrides ibs and obs
  cbs=BYTES       convert BYTES bytes at a time
  conv=CONVS      convert the file as per the comma separated symbol list
  count=N         copy only N input blocks
  ibs=BYTES       read up to BYTES bytes at a time (default: 512)
  if=FILE         read from FILE instead of stdin
  iflag=FLAGS     read as per the comma separated symbol list
  obs=BYTES       write BYTES bytes at a time (default: 512)
  of=FILE         write to FILE instead of stdout
  oflag=FLAGS     write as per the comma separated symbol list
  seek=N          skip N obs-sized blocks at start of output
  skip=N          skip N ibs-sized blocks at start of input
  status=LEVEL    The LEVEL of information to print to stderr;
                  'none' suppresses everything but error messages,
                  'noxfer' suppresses the final transfer statistics,
                  'progress' shows periodic transfer statistics

N and BYTES may be followed by the following multiplicative suffixes:
c =1, w =2, b =512, kB =1000, K =1024, MB =1000*1000, M =1024*1024, xM =M,
GB =1000*1000*1000, G =1024*1024*1024, and so on for T, P, E, Z, Y.

Each CONV symbol may be:

  ascii     from EBCDIC to ASCII
  ebcdic    from ASCII to EBCDIC
  ibm       from ASCII to alternate EBCDIC
  block     pad newline-terminated records with spaces to cbs-size
  unblock   replace trailing spaces in cbs-size records with newline
  lcase     change upper case to lower case
  ucase     change lower case to upper case
  sparse    try to seek rather than write the output for NUL input blocks
  swab      swap every pair of input bytes
  sync      pad every input block with NULs to ibs-size; when used
            with block or unblock, pad with spaces rather than NULs
  excl      fail if the output file already exists
  nocreat   do not create the output file
  notrunc   do not truncate the output file
  noerror   continue after read errors
  fdatasync  physically write output file data before finishing
  fsync     likewise, but also write metadata

Each FLAG symbol may be:

  append    append mode (makes sense only for output; conv=notrunc suggested)
  direct    use direct I/O for data
  directory  fail unless a directory
  dsync     use synchronized I/O for data
  sync      likewise, but also for metadata
  fullblock  accumulate full blocks of input (iflag only)
  nonblock  use non-blocking I/O
  noatime   do not update access time
  nocache   Request to drop cache.  See also oflag=sync
  noctty    do not assign controlling terminal from file
  nofollow  do not follow symlinks
  count_bytes  treat 'count=N' as a byte count (iflag only)
  skip_bytes  treat 'skip=N' as a byte count (iflag only)
  seek_bytes  treat 'seek=N' as a byte count (oflag only)

Sending a USR1 signal to a running 'dd' process makes it
print I/O statistics to standard error and then resume copying.

Options are:

      --help     display this help and exit
      --version  output version information and exit

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/dd>
or available locally via: info '(coreutils) dd invocation'

LAB #3 - Travailler avec la Commande dd

Vous allez utiliser maintenant le logiciel dd pour effectuer une sauvegarde de votre MBR et de la table des partitions.

Effectuez une sauvegarde de votre MBR qui se trouve dans les premiers 446 octets de votre disque /dev/sda :

[root@centos8 /]# dd if=/dev/sda of=/tmp/mbr.save bs=1 count=446
446+0 records in
446+0 records out
446 bytes copied, 0.00202127 s, 221 kB/s

Effectuez maintenant une sauvegarde de votre table des partitions qui se trouve dans les 64 octets après les 446 précédemment sauvegardés :

[root@centos8 /]# dd if=/dev/sda of=/tmp/tblpart.save bs=1 count=64 skip=446
64+0 records in
64+0 records out
64 bytes copied, 0.000409593 s, 156 kB/s

Important - Notez l'utilisation de l'option skip qui permet de positionner le début de la sauvegarde au 447ième octet.

Les Commandes dump et restore

Présentation

Les commandes dump et restore se basent sur le format d'enregistrement des données ( ext3 ). Pour cette raison il n'est pas possible de sauvegarder des répertoires à l'intérieur d'un système de fichiers mais uniquement des systèmes de fichiers complets.

Il est important de noter que le système de fichier ne doit pas être utilisé pendant le processus de dump. Pour cette raison il est normalement conseillé de démonter le système de fichiers.

Il existe 10 niveaux de dump possibles de 0 à 9. Lors d'un dump le niveau est spécifié. Chaque fois qu'un dump est effectué, cette information est sauvegardée dans le fichier /etc/dumpdates.

Par définition un dump de niveau 0 est une sauvegarde complète tandis que le dump de niveau 1 est une sauvegarde incrémentale.

Notez que les fichiers sont sauvegardés avec des nom relatifs. Ceci implique que vous devez vous positionner dans le système de fichiers lors de la restauration avec la commande restore.


Copyright © 2023 Hugh Norris.