Linux用户和组


每一个用户都有一个唯一的登录名称和一个相关联的数字标识,这个数字标识也就是我们常说的UID。每个用户既可以是一个组的成员也可以隶属于多个其他组的成员。但每一个组也都有一个唯一的名称和数字标识,这个数字标识就是我们常说的GID。


设计用户和组的IDs的主要目的有两个:一是确定系统资源隶属哪个系统用户;二是当进程访问这些系统资源时应该授予什么样的权限控制。例如,每一个文件都是属于一个特定用户和组,每一个进程都有一些用户和组IDs以确定谁拥有该进程和这些进程访问文件时所具有的什么样的权限。


本章节中,我们将探讨一些系统文件,如/etc/passwd、/etc/groupd等。这些文件里定义了系统的用户和组的信息。然后会介绍一些库函数来从这些文件中检索用户信息。结束时,我们还会介绍crypt()函数,它是用来加密和认证登录密码的。


系统的密码文件是/etc/passwd,里面包含了用户的账户信息,一行表示一个用户。每一行由半角的分号分隔共有7个字段,如

1
lavenliu:x:1000:1000:Laven Liu: /home/lavenliu : /bin/bash

   

下面按顺序逐一说明每个字段的含义:

1
2
3
4
5
6
7
    1. 用户名           - lavenliu
    2. 加密的密码       - x
    3. 用户UID          - 1000
    4. 用户GID          - 1000
    5. 用户说明         - Laven Liu
    6. 用户家目录       - /home/lavenliu
    7. 用户登录的shell  - /bin/bash


getpwnam函数的简单使用,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[root@python users_groups]# cat my_getpwnam.c 
#include <stdio.h>
#include <stdlib.h>
#include <pwd.h>
 
 
int  main( int  argc,  char  *argv[])
{
     struct  passwd *pwd;
 
     if  (argc < 2) {
         printf ( "Usage: %s <username>\n" , argv[0]);
         exit (1);
     }
     
     pwd = getpwnam(argv[1]);
     if  (pwd == NULL) {
         printf ( "could not get %s record\n" , argv[1]);
         exit (1);
     else  {
         printf ( "find [ %s ] record, the following is the info:\n" , argv[1]);
         printf ( "Username: %s\n" , pwd->pw_name);
         printf ( "Uid     : %ld\n" , ( long )pwd->pw_uid);
         printf ( "Shell   : %s\n" , pwd->pw_shell);
     }
     
     return  0;
}


编译并运行,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@python users_groups] # gcc -g -o my_getpwnam my_getpwnam.c 
[root@python users_groups] # ./my_getpwnam 
Usage: . /my_getpwnam  <username>
 
[root@python users_groups] # ./my_getpwnam root
find  [ root ] record, the following is the info:
Username: root
Uid     : 0
Shell   :  /bin/bash
[root@python users_groups] # ./my_getpwnam www
could not get www record
 
[root@python users_groups] # ./my_getpwnam lavenliu
find  [ lavenliu ] record, the following is the info:
Username: lavenliu
Uid     : 500
Shell   :  /bin/bash
 
[root@python users_groups] # ./my_getpwnam taoqi
find  [ taoqi ] record, the following is the info:
Username: taoqi
Uid     : 517
Shell   :  /bin/bash