linux下獲取使用者基本資訊

2021-05-12 13:18:03 字數 1741 閱讀 5643

孫曉明,

華清遠見嵌入式學院

講師。通過c語言基礎庫從獲取linux使用者的基本資訊。

1、使用struct passwd管理使用者資訊。

struct passwd

;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

#include

#include

#include

int main ()

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 ("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)

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

linux下獲取使用者基本資訊

通過c 語言基礎庫從獲取 linux 使用者的基本資訊。1 使用struct passwd 管理使用者資訊。struct passwd 2 分析相並的系統檔案 etc passwd 1.root x 0 0 root root bin bash 2.daemon x 1 1 daemon usr s...

linux環境下獲取使用者基本資訊

通過c語言基礎庫從獲取linux使用者的基本資訊。1 使用struct passwd管理使用者資訊。2 分析相並的系統檔案 etc passwd 在passwd檔案中記錄的是所有系統使用者 每一行表示乙個完整的struct passwd結構,以 分隔出每一項值,其7項。3 獲取系統當前執行使用者的基...

微信批量獲取使用者基本資訊介面

介面 返回引數及輸入引數說明鏈結官網 直接貼方法咯 批量獲取使用者基本資訊 accesstoken var data new return commonjsonsend.send accesstoken,url,data,timeout timeout 使用者基本資訊類和 top方法返回類,可以寫在...