通過c語言(yan)基(ji)礎庫從獲取linux用戶的基(ji)本信息(xi)。
	1、使用struct passwd管理用戶信息。
	        struct passwd
	        {
	            char *pw_name; /* 用戶登錄名 */
	            char *pw_passwd; /* 密碼(加密后)*/
	            __uid_t pw_uid; /* 用戶ID */
	            __gid_t pw_gid; /* 組ID */
	            char *pw_gecos; /* 詳細用戶名 */
	            char *pw_dir; /* 用戶目錄 */
	            char *pw_shell; /* 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文件中記錄的是所有系統用戶
	        每一(yi)(yi)行表示一(yi)(yi)個完整的struct passwd結構,以(yi)':'分隔(ge)出每一(yi)(yi)項(xiang)值,其7項(xiang)。
	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.\n", (int)uid);
	                return 1;
	            }
	
	            printf ("I am %s.\n", pw->pw_gecos);
	            printf ("User login name is %s.\n", pw->pw_name);
	            printf ("User uid is %d.\n", (int) (pw->pw_uid));
	            printf ("User home is directory is %s.\n", pw->pw_dir);
	            printf ("User default shell is %s.\n", pw->pw_shell);
	            grp = getgrgid (pw->pw_gid);
	            if (!grp)
	            {
	                printf ("Couldn't find out about group %d.\n",
	                (int)pw->pw_gid);
	                return 1;
	            }
	    printf ("User default group is %s (%d).\n",
	                grp->gr_name, (int) (pw->pw_gid));
	    printf ("The members of this group are:\n");
	            members = grp->gr_mem;
	            while (*members)
	            {
	                printf ("\t%s\n", *(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、查(cha)看所有(you)的(de)用戶信(xin)息
	使用pwd.h定義的方法getpwent(),逐行讀取/etc/passwd中的記錄,每調用getpwent函數一次返回一個完整用戶信息struct passwd結構。
	再次讀(du)(du)取時,讀(du)(du)入下一行的記錄。
	在(zai)使(shi)用之前(qian)先使(shi)用setpwent()打開文(wen)(wen)件(如果文(wen)(wen)件關閉)或重定位到的(de)文(wen)(wen)件開始處,操作(zuo)結(jie)束時使(shi)用endpwent()關閉/etc/passwd文(wen)(wen)件,避免對(dui)后面的(de)使(shi)用產生負作(zuo)用。
	5、腳本操(cao)作,顯示所有(you)用戶的信息中的name
	使用cut命令將/etc/passwd中的內容逐行解析,"-d:"以':'將一行劃分出7人字段列,-f1,為第一列
	         cut -d: -f1 /etc/passwd