现在的位置: 首页 > 综合 > 正文

UNIX环境高级编程读书笔记(五)—系统文件和信息 (1)

2014年09月21日 ⁄ 综合 ⁄ 共 2395字 ⁄ 字号 评论关闭

 

一、etc/passwd文件

 

1

名称:

getpwuid/getpwnam

功能:

Getpassword file entry

头文件:

#include <pwd.h>

函数原形:

struct passwd *getpwuid(uid_t uid);

struct passwd *getpwnam(const char *name);

参数:

Uid   用户id 

返回值:

若成功则返回指针,若出错则返回NULL

Getpwuid函数由ls(1)程序使用,它将i节点中的数值用户id映射为用户登录名。在键入登录名时,getpwnam函数由login(1)程序使用。

 

这些系统信息都是在/ect/passwd文件中读出的。里面记录着许多用户登录信息。

用户名                  char *pw_name

加密口令                char *pw_passwd

数值用户ID              uid_t pw_uid

数值组ID                gid_t pw_gid

注释字段                char *pw_gecos

初始工作目录            char *pw_dir

初始shell                char *pw_shell

用户访问类              char *pw_class

下次更改口令时间        time_t pw_chang

帐户到期时间            time_t pw_expire

 

下面是显示当前用户信息的例子:

/*5_1.c*/

#include <sys/types.h>

#include <pwd.h>

#include <unistd.h>

 

main()

{

struct passwd *ptr;

 

if((ptr=getpwuid(getuid()))<0)

    perror(“error”);

printf(“name:%s/n”,ptr->pw_name);

printf(“uid:%d/n”,ptr->pw_uid);

printf(“gid:%d/n”,ptr->pw_gid);

}

上面的程序用到了函数getuid来获取当前用户的数值id.

 

2.

名称:

getpwent/setpwent/endpwent

功能

get password file entry

头文件

#include <pwd.h>

#include <sys/types.h>

函数原形

struct passwd *getpwent(void);

void setpwent(void);

void endpwent(void);

参数:

返回值:

若成功则返回指针,若出错则返回NULL

 

3个函数可以查看/ect/passwd文件中的所有信息。也就是可以用这几个函数来查看系统所有的注册用户的信息。调用getpwent时,它返回口令文件中的下一个记录项。函数setpwent反绕它所使用的文件。Endpwent则关闭这些文件。下面是一个例子用来列出系统的所有用户.

/*5_2.c*/

#include <stdio.h>

#include <pwd.h>

 

int main()

{

struct passwd *pwd;

setpwent();

while((pwd=getpwent())!=NULL)

{

    printf(“uid:%d/n”,pwd->pw_uid);

    printf(“name:%s/n”,pwd->pw_name);

}

endpwent();

}

 

在程序开始处调用setpwent是自我保护性的措施,以便在调用getpwent打开有关文件情况下,反绕有关文件使他们定位到文件开始处。在使用getpwent查完口令文件后,一定要调用endpwent关闭这些文件.getpwent知道什么时候它应打开它所使用的文件(第一次被调用时),但是它并不知道何时关闭这些文件。

 

3.

名称:

getspnam/getspent/setspent/endspent

功能:

encrypted password file routines

头文件:

#include <shadow.h>

函数原形:

struct spwd *getspent();

struct spwd *getspnam(char *name);

void setspent();

void endspent();

参数:

name   用户名

返回值:

若成功则返回指针,若出错则返回NULL

 

加密口令是经单向加密算法处理过的用户口令副本。现在,某些系统将加密口令存放在另一个通常称为阴影口令的文件中。该文件包含的字段有。

用户登录名                       char *sp_namp

加密口令                         char *sp_pwdp

上次更改口令以来经过的时间       long sp_lstchg

经过多少天后容许更改             int sp_min

要求更改声音剩余天数             int sp_max

到期警告天数                     int sp_warn

帐户不活动以前尚余天数           int sp_inact

帐户到期天数                     int sp_expir

保留                             unsigned int sp_flag

 

/*5_3.c*/

#include <shadow.h>

#include <stdio.h>

 

main()

{
    struct spwd *pwd;

 

setspent();

while((pwd=getspent())!=NULL)

{

    printf(“name:%s/n”,pwd->sp_namp);

    printf(“name:%s/n”,pwd->sp_pwdp);

}

endpwent();

}

 

抱歉!评论已关闭.