通过c语言基础库从获取linux用户的基本信息。 1、使用struct passwd管理用户信息。 struct passwd { char *pw_name; char *pw_passwd; __uid_t pw_uid; __gid_t pw_gid; char *pw_gecos; char *pw_dir; char *pw_shell; }; 2、分析相并的系统文件/etc/passwd ⑴ root:x:0:0:root:/root:/bin/bash ⑵ daemon:x:1:1:daemon:/usr/sbin:/bin/sh ⑶ bin:x:2:2:bin:/bin:/bin/sh 在passwd文件中记录的是所有系统用户 每一行表示一个完整的struct passwd结构,以":"分隔出每一项值,其7项。 3、获取系统当前运行用户的基本信息。 #include <grp.h> #include <pwd.h> #include <unistd.h> #include <stdio.h> int main () { uid_t uid; struct passwd *pw; struct group *grp; char **members; uid = getuid (); pw = getpwuid (uid); if (!pw) { printf ("Couldn"t find out about user %d.
", (int)uid); return 1; } printf ("I am %s.
", pw->pw_gecos); printf ("User login name is %s.
", pw->pw_name); printf ("User uid is %d.
", (int) (pw->pw_uid)); printf ("User home is directory is %s.
", pw->pw_dir); printf ("User default shell is %s.
", pw->pw_shell); grp = getgrgid (pw->pw_gid); if (!grp) { printf ("Couldn"t find out about group %d.
", (int)pw->pw_gid); return 1; } printf ("User default group is %s (%d).
", grp->gr_name, (int) (pw->pw_gid)); printf ("The members of this group are:
"); members = grp->gr_mem; while (*members) { printf (" %s
", *(members)); members++; } return 0; } 编译,结果输出 $gcc -o userinfo userinfo.c $./userinfo I am root. My login name is root. My uid is 0. My home is directory is /root. My default shell is /bin/bash. My default group is root (0). The members of this group are: test user test2 4、查看所有的用户信息 使用pwd.h定义的方法getpwent(),逐行读取/etc/passwd中的记录,每调用getpwent函数一次返回一个完整用户信息struct passwd结构。 再次读取时,读入下一行的记录。 在使用之前先使用setpwent()打开文件(如果文件关闭)或重定位到的文件开始处,操作结束时使用endpwent()关闭/etc/passwd文件,避免对后面的使用产生负作用。 5、脚本操作,显示所有用户的信息中的name 使用cut命令将/etc/passwd中的内容逐行解析,"-d:"以":"将一行划分出7人字段列,-f1,为第一列 cut -d: -f1 /etc/passwd