• LINUX > les utilisateurs (user), les groupes (group) et les permissions

      LES UTILISATEURS (user)

      Liste des utilisateurs

      cat /etc/passwd
      root:x:0:0:root:/root:/bin/bash
      daemon:x:1:1:daemon:/usr/sbin:/bin/sh
      ...
      proxy:x:13:13:proxy:/bin:/bin/sh
      toto:x:1000:1000:toto:/home/toto:/bin/sh 
      messagebus:x:104:106::/var/run/dbus:/bin/false

       

      Pour comprendre en détail ces lignes : format du fichier passwd.

       

      id toto
      uid=1000(toto) gid=1000(tata) groups=1000(tata),4(adm),27(sudo)

       

      Créer un user

      sudo useradd -c "blabla" -s /bin/bash -m -G groupe1,groupe2 toto

       

      -c "blabla" pour créer un commentaire du user dans /etc/passwd

      -s /bin/bash indique le shell

      -m pour créer son dossier dans le /home (en fait, copier la structure du modèle du sdossier /etc/skel )

      -G pour indiquer dans quel(s) groupe(s) le user appartiendra

       

      Modifier un user

       

      ajjouter un user dans un(des) groupe(s) :

      usermod -aG groupe1,groupe2 toto

       

      modifier le mot de passe :

      passwd toto

       

      supprimer le mot de passe :

      passwd -d toto

       

       

      supprimer un utilisateur

      sudo userdel toto -r

       

      -r pour supprimer son dossier dans /home

      LES GROUPES (groups)

      Liste des groupes

      cat /etc/group

       

      Créer un groupe

      sudo groupadd groupe1

       

      Modifier un groupe

       

      ajouter un user dans un groupe

      usermod -aG groupe1,groupe2 toto

       

      enlever un utilisateur d’un groupe

      sudo gpasswd -d toto groupe1

       

      supprimer un groupe

      sudo groupdel groupe1

       

      valable que si plus aucun utilisateur n’est dans le groupe groupe1.

      PERMISSIONS

      Afficher les permissions des fichiers :

       

      ls -l

       

      Les droits d’accès apparaissent alors comme une liste de 10 symboles. :

       

      drwxr-xr-x toto groupe1

       

      rwx droits pour le propriétaire (toto)

      rwx droits pour le groupe (groupe1)

      rwx droits pour les autres

       

      - fichier, d répertoire, l lien

       

      chown www-data:www-data /var/www

      chmod 744 /var/www

      changer le propriétaire

      chown (change owner) permet de changer le propriétaire du fichier :

       

      sudo chown waters fichier

       

      fichier appartient maintenant à l’utilisateur waters.

       

      On peut changer le propriétaire et le groupe en même temps :

       

      sudo chown waters:pinkfloyd fichier

       

      fichier appartient alors à l’utilisateur waters et au groupe pinkfloyd.

      changer le groupe

      chgrp (change group) permet de changer le groupe auquel appartient le fichier (seuls sudo ou le propriétaire ) :

       

      sudo chgrp pinkfloyd fichier

       

      fichier appartient maintenant au groupe pinkfloyd. Tous les membres du groupe pinkfloyd auront accès à ce fichier selon les permissions du groupe.

      changer les permissions

      chmod (change mode) permet de modifier les permissions sur un fichier.

       

      - de manière OCTALE :

       

      chmod 740 fichier

       

      r= 4, w=2, x=1

       

      - de manière LITTÉRAIRE :

       

      À qui s’applique le changement : u (user) - g (group) - o (others) - a (all)

      La modification que l’on veut faire : + ajouter ; - supprimer ; = affectation

      Le droit que l’on veut modifier : r read ; w write ; x execute ; X eXécution, pour les répertoires (qu’ils aient déjà une autorisation d’exécution ou pas) et les fichiers qui ont déjà une autorisation d’exécution pour l’une des catégories d’utilisateurs. Nous allons voir plus bas dans la partie des traitements récursifs l’intérêt du X.

       

      enlever le droit d’écriture pour les autres :

       

      chmod o-w fichier

       

      ajouter le droit d’exécution à tout le monde :

       

      chmod a+x fichier

       

      On peut aussi combiner plusieurs actions en même temps :

       

      chmod u+rwx,g+rx-w,o+r-wx fichier

      Récursivement

      Avec l’option -R

       

      chmod -R 750 monDossier

      donnera tous les droits au propriétaire, les droits de lecture et exécution au groupe et aucuns droits aux autres…

      Exemple d’application en traitant de façon différentiée les répertoires et les fichiers

      les répertoires doivent avoir la permission x pour pouvoir être ouverts, la permission x est inutile pour les fichiers non exécutables et peut être gênante pour les fichiers textes (txt, html…) car dans ce cas lorsqu’on les ouvre on aura à chaque fois un message demandant si on veut les ouvrir ou les lancer (comme exécutable). Bref le droit x est à réserver aux seuls fichiers qui sont vraiment des exécutables.

       

      Application 1 :


      Soit un répertoire monrep, contenant des sous-répertoires et des fichiers. Les droits sont drwx—— (700) pour les répertoires et -rw—— (600) pour les fichiers.

      On veut ajouter récursivement les mêmes droits (resp. rwx et rw) pour le groupe. C’est à dire que veut aboutir à la situation suivante : drwxrwx— (770) pour les répertoires et -rw-rw—- (660) pour les fichiers.

      chmod -R 770 monrep : les fichiers vont avoir les droits d’exécution → mauvais

      chmod -R 660 monrep : les répertoires n’auront plus les droits d’exécution → catastrophique

      chmod -R g+rwx monrep : les fichiers vont avoir les droits d’exécution → mauvais

      chmod -R g+rwX monrep : seuls les répertoires (et les fichiers déjà exécutables) auront les droits d’exécution → BIEN

       

      Application 2 :

      Imaginons que précédemment on ait lancé la commande chmod -R 770 monrep. La situation est la suivante : les droits sont drwxrwx— (770) pour les répertoires et -rwxrwx—- (770) pour les fichiers.

      On désire supprimer les droits d’exécution uniquement sur les fichiers. C’est à dire que veut aboutir à la situation suivante : drwxrwx— (770) pour les répertoires et -rw-rw—- (660) pour les fichiers.

      Comme chmod s’applique à la fois aux fichiers et répertoires, nous allons jongler avec x et X. Il faut enlever x puis ajouter X.

      Si on lance chmod -R u-x+X,g-x+X monrep cela n’aura aucun effet car X concerne à la fois les répertoires ET les fichiers qui ont un x quelque part. Donc si u-x enlève le premier x (ce qui donne -rw-rwx—), la suite +X va aussitôt remettre un x car il reste un x (celui du groupe !).

      Donc il faut d’abord enlever tous les x : u-x,g-x avant de les remettre (sera fait uniquement pour les répertoires cette fois) ce qui donne finalement :

      chmod -R u-x,g-x,u+X,g+X monrep
      Il est à noter que seuls le propriétaire du fichier ainsi que le super-utilisateur ont la possibilité de modifier les permissions sur un fichier. (Un membre du groupe propriétaire ne peut pas changer les permissions sur un fichier.) Quand l’utilisateur actuel n’est pas le propriétaire actuel du fichier, il sera nécessaire de faire précéder la commande par sudo, puisqu’elle devra être effectuée avec les droits d’administration.
      Notez aussi que pour modifier les propriétaires et les permissions sur un fichier qui lui appartient, un utilisateur doit absolument disposer de la permission d’écriture sur ce fichier. S’il ne dispose uniquement que de la permission de lecture, il ne pourra effectuer aucun changement de droits d’accès sur ce fichier.

      Deux autres options bien pratiques :

      • Pour afficher un message si et seulement si les permissions ont changé :
      chmod -c <option> <fichier>
      • Pour travailler récursivement sur tous les fichiers d’un répertoire et de ses sous-répertoires :
      chmod -R repertoire

      Droits spéciaux

      Les droits sont parfois spécifiés avec 4 chiffres : file_mode=0777. Ce premier chiffre ajouté devant permet de définir :

      ls -l /usr/bin
      -rwsr-xr-x  1 root   root     155008 févr. 10  2014 sudo*
      -rwxr-sr-x  1 root   ssh      284784 mai   12  2014 ssh-agent*

       

      s permet à un utilisateur d’exécuter le programme avec les droits du propriétaire, c’est ainsi que sudo nous permet d’exécuter des commandes en "root". idem pour le groupe.

       

      le Sticky permet de restreindre la suppression d’un fichier ou répertoire à son seul propriétaire. C’est le cas de /tmp :

       

      ls -ld /t*/
      drwxrwxrwt   2 root root  4096 nov.  28 13:17 tmp/

       

      le t au lieu du x nous informe que ce répertoire ne peut être supprimé que par l’utilisateur root.

      Comme pour les autres permissions, on peut cumuler les activations en additionnant le code pour chacun, ainsi pour activer le sticky bit et le GroupID sur le script toto.sh :

       

      chmod 3777 toto.sh

       

      chown

      ls -l test.txt
      -rw-r--r--  1 toto toto  127 2011-06-26 20:02 test.txt
      chown mimi test.txt
      ls -l test.txt
      -rw-r--r-- 1 mimi toto 127 2011-06-26 20:02 test.txt

      Changer de groupe

      -R affecte le nouveau propriétaire et/ou un nouveau groupe à tous les sous-dossiers et fichiers contenus dans un répertoire.Par exemple le répertoire toto contient un dossier et trois fichiers:

       

      ls -l
      -rw-r--r-- 1 toto toto      31 2011-06-26 20:32 123.mp3
      -rw-r--r-- 1 toto toto       6 2011-06-26 20:32 abc.jpg
      drwxr-xr-x 2 toto toto    4096 2011-06-26 20:33 document
      -rw-r--r-- 1 mimi travail  127 2011-06-26 20:02 test.txt
      chown -R mimi:travail .
      ls -l
      -rw-r--r-- 1 mimi travail   31 2011-06-26 20:32 123.mp3
      -rw-r--r-- 1 mimi travail    6 2011-06-26 20:32 abc.jpg
      drwxr-xr-x 2 mimi travail 4096 2011-06-26 20:33 document
      -rw-r--r-- 1 mimi travail  127 2011-06-26 20:02 test.txt

      Modifier l’UID d’un utilisateur

      Comment modifier l’identifiant d’un utilisateur linux

      usermod permet de modifier un utilisateur. La commande id permet de connaitre l’identifiant d’un utilisateur.

       

      id toto
      uid=1000(toto) [...]
      sudo usermod -u 666 toto
      id toto
      uid=666(toto) [...]
      Ne pas oublier de déplacer les fichiers de l'utilisateur find / -uid 1000 -exec chown 1001 {} \; Sur les systèmes qui le permettent Sur les autres on peut s'en sortir avec une commande style :
      ls -Rla / | grep :1000: | chown 1001 `awk -F ":" {print $1}` (à la louche, et en faisant attention a ne pas avoir de gid = 1000) Et pour les OS qui ne permettent pas le faire un ls -R je ne vois pas d'autre solution qu'un script ...
       

      Add User To Group

      Deux sortes de groupes : Primary et Secondary.

      useradd pour ajouter un user dans un groupe déjà existant. If group does not exist, create it :
      useradd -G {group-name} username

       

      First login as a root user (make sure group developers exists), enter:

       

      groupadd pinkfloyd

       

      Vérifier si toto existe déjà :
      grep ^toto /etc/passwd

      useradd -G pinkfloyd toto

       

      Setup password for user vivek:
      # passwd toto

       

      Ensure that user added properly to group developers:

      id toto
      uid=1122(toto) gid=1125(toto) groups=1125(kingcrimson),1124(pinkfloyd)

       

      -G add user to a list of supplementary groups. Each group is separated from the next by a comma, with no intervening whitespace. For example, add user jerry to groups admins, ftp, www, and developers, enter:
      # useradd -G admins,ftp,www,developers jerry

      Add a new user to primary group

      # useradd -g pinkfloyd toto
      # id tony

      Sample outputs:

      uid=1123(toto) gid=1124(pinkfloyd) groups=1124(pinkfloyd)

       

      -g add user to initial login group (primary group). The group name must exist. A group number must refer to an already existing group.

      Add a existing user to existing group

      Add toto to ftp supplementary/secondary group with the usermod using the -a option ~ i.e. add the user to the supplemental group(s). Use only with -G option:
      # usermod -a -G ftp toto
      In this example, change tony user’s primary group to www, enter:
      # usermod -g www toto

      usermod command options summary

      Option Purpose
      -a Add the user to the supplementary group(s). Use only with the -G option.
      -g GROUP
      Use this GROUP as the default group.
      -G GRP1,GRP2 Add the user to GRP1,GRP2 secondary group.

      A note about security

      If you add or delete user to existing group, you must change the owner of any crontab files or at jobs manually. You must make any changes involving NIS on the NIS server too.

       

      Create a New Group

      groupadd replacing new_group with the name of the group you want to create. You’ll need to use sudo with this command as well (or, on Linux distributions that don’t use sudo, you’ll need to run the su command on its own to gain elevated permissions before running the command).

       

      sudo groupadd monnouveaugroupe

      Add an Existing User Account to a Group

      To add an existing user account to a group on your system, use the usermod command, replacing examplegroup with the name of the group you want to add the user to andexampleusername with the name of the user you want to add.

      usermod -a -G examplegroup exampleusername

      For example, to add the user geek to the group sudo , use the following command:

      sudo usermod -a -G sudo geek

      Change a User’s Primary Group

      While a user account can be part of multiple groups, one of the groups is always the “primary group” and the others are “secondary groups”. The user’s login process and files and folders the user creates will be assigned to the primary group.

      To change the primary group a user is assigned to, run the usermod command, replacingexamplegroup with the name of the group you want to be the primary and exampleusernamewith the name of the user account.

      usermod -g groupname username

      Note the -g here. When you use a lowercase g, you assign a primary group. When you use an uppercase -G , as above, you assign a new secondary group.

      View the Groups a User Account is Assigned To

      To view the groups the current user account is assigned to, run the groups command. You’ll see a list of groups.

      groups

      To view the numerical IDs associated with each group, run the id command instead:

      id

      To view the groups another user account is assigned to, run the groups command and specfy the name of the user account.

      groups exampleusername

      You can also view the numerical IDs associated with each group by running the id command and specifying a username.

      id exampleusername

      The first group in the groups list or the group shown after “gid=” in the id list is the user account’s primary group. The other groups are the secondary groups. So, in the screenshot below, the user account’s primary group is example.

      Create a New User and Assign a Group in One Command

      You may sometimes want to create a new user account that has access to a particular resource or directory, like a new FTP user. You can specify the groups a user account will be assigned to while creating the user account with the useradd command, like so:

      useradd -G examplegroup exampleusername

      For example, to create a new user account named jsmith and assign that account to the ftp group, you’d run:

      useradd -G ftp jsmith

      You’ll want to assign a password for that user afterwards, of course:

      passwd jsmith

      ajouter un user à plusieurs groupes

      usermod -a -G group1,group2,group3 nomUser
      usermod -a -G ftp,sudo,example toto

      Voir les groupes

      getent group
      root:x:0:
      daemon:x:1:
      bin:x:2:
      sys:x:3:
      adm:x:4:syslog,waters
      pinkfloyd:x:1000:waters

      How to set the group that new files will be created with?

      I’m doing a bash shell script and I want to change the default group that new files are created as. I know you use umask to change the permissions. Is there something for the group?

      The newgrp command is used to change the current group ID during a login session.

      New directories created in that session will have the group ID set by the command.

      newgrp(1)

       

      I’m a member of the group, so why is it asking me for a password? It doesn’t like my password! – Michael Feb 12 ’13 at 4:25

       

      also, if i run "newgrp <group>" as root (e.g. running a script with newgrp in it using sudo), it dump me into a root shell. – Michael Feb 12 ’13 at 4:28

       

      This is not what newgrp should be used for. What happens if you forget to use to use newgrp outside of the script? How will the script handle the new shell that newgrp creates. @mark40′s answer is better. – noel May 20 ’13 at 12:53

      16

      Is this really considered an answer? It’s a link. – mcont Dec 24 ’14 at 11:14

      Can’t help upvoting because that’s interesting information. I still think @mark4o’s answer should be the correct one. – Teekin Apr 28 ’17 at 12:34

       

      There are a couple ways to do this:

      You can change the default group for all files created in a particular directory by setting the setgid flag on the directory (chmod g+s _dir_). New files in the directory will then be created with the group of the directory (set using chgrp <group> <dir>). This applies to any program that creates files in the directory.

       

      Note that this is automagically inherited for new subdirectories (as of Linux 3.10), however, if sub-directories were already present, this change won’t be applied to them (use the -R flag for that).

       

      If the setgid flag is not set, then the default group will be set to the current group id of the creating process. Although this can be set using the newgrp command, that creates a new shell that is difficult to use within a shell script. If you want to execute a particular command (or set of commands) with the changed group, use the command sg <group> <command>.

       

      sg is not a POSIX standard command but is available on Linux.

       

      Set default group for user when they create new files?

       

      I often find myself chown-ing files as I created them through SSH and they are owned by jm:jm for example.

       

      Then to allow Apache to access it, I need to for example do chown jm:www-data.

       

      I am sure I can specify that when I create files, instead of using the group under my name, specify another?

       

      Or is there a better way of managing users/groups?

      permissions users

      If you want all new files in a particular directory to be owned by a particular group, just apply the setgid bit on it:

       

      chgrp www-data /some/dir

      chmod g+s /some/dir

       

      If you have an existing tree of directories that you want to apply this behaviour to, you can do so with find:

       

      find /some/dir -type d -exec chgrp www-data {} +

      find /some/dir -type d -exec chmod g+s {} +

       

      (if the directories are already owned by the relevant group, then you can omit the first command in both of these examples).

       

       

      --

       

      Specify default group and permissions for new files in a certain directory

       

      I have a certain directory in which there is a project shared by multiple users. These users use SSH to gain access to this directory and modify/create files.

       

      This project should only be writeable to a certain group of users: lets call it "mygroup". During an SSH session, all files/directories created by the current user should by default be owned by group "mygroup" and have group-writeable permissions.

       

      I can solve the permissions problem with umask:

       

      $ cd project

      $ umask 002

      $ touch test.txt

       

      File "test.txt" is now group-writeable, but still belongs to my default group ("mislav", same as my username) and not to "mygroup". I can chgrp recursively to set the desired group, but I wanted to know is there a way to set some group implicitly like umask changes default permissions during a session.

       

      This specific directory is a shared git repo with a working copy and I want git checkout and git reset operations to set the correct mask and group for new files created in the working copy. The OS is Ubuntu Linux.

       

      Update: a colleague suggests I should look into getfacl/setfacl of POSIX ACL but the solution below combined with umask 002 in the current session is good enough for me and is much more simple.

      unix permissions umask posix chgrp

       

      In order to have all files under a given directory inherit group rights, you need to use the setgid bit on your directory. See this link.

       

      $ mkdir test

      $ sudo chown raphink.staff test

      $ ls -lhd test

      drwxr-xr-x 2 raphink staff 4.0K 2009-12-21 16:19 test

      $ sudo chmod g+s test # Set the setgid bit

      $ ls -lhd test

      drwxr-sr-x 2 raphink staff 4.0K 2009-12-21 16:21 test

      $ touch test/foo

      $ ls -lh test

      total 0

      -rw-r--r-- 1 raphink staff 0 2009-12-21 16:23 foo

       

      Thanks. Interesting that I didn’t find this by googling – mislav Dec 21 ’09 at 22:13

       

      If you want to do this with an existing folder, you need to make sure the setgid bit is enabled for all subfolders as well. However, you don’t need it on files, and you probably don’t want it on files either. Here is how to set it for all subfolders recursively.

       

      find /path/to/base/dir -type d -exec chmod g+s {} +

       

      I cannot find the source back, but using setgid to solve this issue for bare git repositories, which I assume is your case, is deprecated, and can cause issues in some cases.

       

      Git can take care of all this via the core.sharedRepository flag. I had the same issue and solved it as follows:

       

      Assuming repogroup is your group, and you have cd to the repo directory:

       

      First change the shared flag to group:

       

      git config core.sharedRepository group

       

      Note: here you must use the keyword group, not the group name. This is equivalent to creating the bare repository with option --shared=group.

       

      Then change the group for the whole repository:

       

      chgrp -R repogroup .

       

      To make sure that existing directories are group-writable (g+w), and existing executables also become group-executables (g+X) you also need to:

       

      chmod -R g+wX .

       

      Once you have done this, git will honor the shared=group flag and take care of group permissions in the following, both for existing and new files, so you’ll never need again to umask or chgrp.

       

      --

      How to set default file permissions for all folders/files in a directory?

       

      I want to set a folder such that anything created within it (directories, files) inherit default permissions and group.

      Lets call the group "media". And also, the folders/files created within the directory should have g+rw automatically.

      Isn’t that controlled by the user creating the new file/folder, and his umask? – Wadih M. Aug 27 ’10 at 15:02

      umask does relate to permissions but I do not believe it does anything with setting a default group that is not the user him/herself.

       

      From the article:

       

      chmod g+s <directory>  //set gid
      setfacl -d -m g::rwx /<directory>  //set group to rwx default
      setfacl -d -m o::rx /<directory>   //set other

       

      Next we can verify:

       

      getfacl /<directory>

       

      Output:

       

      # file: ../<directory>/
      # owner: <user>
      # group: media
      # flags: -s-
      user::rwx
      group::rwx
      other::r-x
      default:user::rwx
      default:group::rwx
      default:other::r-x

       

      Yay for the sticky bit!

       

      Lets not confuse gid with sticky bit.

       

      g+s will ensure that new content in the directory will inherit the group ownership. setfacl only changes the chmod, in your case sets the permission to o=rx – Steen Schütt Feb 12 ’14 at 12:28

       

       

      Note that ACL must be enabled (included as one of the mount options for the mounted file system) for the file permissions to be inherited. – sg23 Oct 21 ’14 at 19:29

       

      You might want to consider using ‘X’ instead so it will only set execute permission on directories not files setfacl -d -m g::rwX /<directory>

       

      This is an addition to Chris’ answer, it’s based on my experience on my Arch Linux rig.

       

      Using the default switch (-d) and the modify switch (-m) will only modify the the default permissions but leave the existing ones intact:

       

      setfacl -d -m g::rwx /<directory>

       

      If you want to change folder’s entire permission structure including the existing ones (you’ll have to do an extra line and make it recursive -R:

       

      setfacl -R -m g::rwx /<directory>

       

      eg.

       

      setfacl -R -m g::rwx /home/limited.users/<directory> // gives group read,write,exec permissions for currently existing files and folders, recursively
      setfacl -R -m o::x /home/limited.users/<directory> //revokes read and write permission for everyone else in existing folder and subfolders
      setfacl -R -d -m g::rwx /home/limited.users/<directory> // gives group rwx permissions by default, recursively
      setfacl -R -d -m o::--- /home/limited.users/<directory> //revokes read, write and execute permissions for everyone else.

       

      (CREDIT to markdwite in comments for the synthax of the revoke all privileges line)

       

      To revoke group privileges (as an example): sudo setfacl -d -m g::— /path – markdwhite Jan 26 ’17 at 8:53

       

      is that just a typo specifying setfacl -R -m g::rwx /<directory> twice in your answer? – Shane Rowatt Sep 2 ’17 at 11:05

       

      Add yourself/logged user to www-data group, so we can work with files created by www-data server

       

      sudo usermod -a -G www-data $USER

       

      Needs to restart/relogin so the newly added group takes effect

       

      cd /var/www

       

      Add www-data as group member of html folder, and your user as owner, so we own it as well as a group member

       

      sudo chown -R $USER:www-data html

       

      Put your username in place of USER

       

      Set read,write,execute permission as required, (ugo) u=user, g=group, o=others

       

      sudo chmod 750 html

       

      Set the GID of html, now, newly created files in html will inherit ownership permissions:

       

      sudo chmod g+s html

       

      This creates the default rules for newly created files/dirs within the html directory and sub directories.

       

      sudo setfacl -R -d -m u::rwX -m g::rX -m o::000 html

       

      Make SELinux if installed, ignore www-data context requirement so it lets allows write permissions

       

      sudo setsebool -P httpd_unified 1

       

      list directory to see new permissions applied

       

      ls -ld html

       

      Returns this

       

      drwxrwsr-x+ 3 html www-data

       

      The trailing + signify that ACL, Access Control List, is set on the directory.

       

      --

       

       

      --

 

Aucun commentaire

 

Laissez un commentaire