通過c語言基礎庫從獲取linux用戶的基本信息。
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文件中記錄的是所有系統用戶
每一行表示一個完整的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.\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、查看所有的用戶信息
使用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