linux關於使用者資訊的編程

來源:互聯網
上載者:User

Linux對每一個使用者都提供了一個uid,我們從uid開始來說說使用者資訊。

uid有自己的類型,uid_t,它定義在標頭檔sys/types.h中。它通常是一個小整數。有些UID是系統預定義的,其他的則是系統管理員

在添加心使用者時建立的,一般情況下,uid都大於100。

#include<sys/types.h>

#include<unistd.h>

uid_t getuid(void);

char *getlogin(void);

getuid函數返回程式關聯的UID,它通常是啟動程式的使用者的UID。

getlogin函數返回目前使用者關聯的登入名稱。

系統檔案/etc/passwd包涵一個使用者帳號資料庫。它由行組成,每行對應一個使用者,包括使用者名稱,加密口令,使用者識別碼,群組識別碼,全名,家目錄和

預設的shell.

人們定義了一組函數來提供一個標準而又有效擷取使用者資訊的編程介面。

#include<sys/types.h>

#include<pwd.h>

struct passwd *getpwuid(uid_t uid);

struct passwd *getpwnam(const char *name);

密碼資料庫結構passwd定義在標頭檔pwd.h中,它包括下面幾個成員。

passwd成員                                             說明

char *pw_name                                     使用者登入名稱

uid_t pw_uid                                           UID號

gid_t pw_gid                                           GID號

char *pw_dir                                           使用者家目錄

char *pw_gecos                                    使用者全名

char *pw_shell                                      使用者預設shell

#include <sys/types.h>#include <pwd.h>#include <stdio.h>#include <unistd.h>#include <stdlib.h>int main(){    uid_t uid;    gid_t gid;    struct passwd *pw;    uid = getuid();    gid = getgid();    printf("User is %s\n", getlogin());    printf("User IDs: uid=%d, gid=%d\n", uid, gid);    pw = getpwuid(uid);    printf("UID passwd entry:\n name=%s, uid=%d, gid=%d, home=%s, shell=%s\n",        pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell);    pw = getpwnam("root");    printf("root passwd entry:\n");    printf("name=%s, uid=%d, gid=%d, home=%s, shell=%s\n",        pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell);    exit(0);}

如果要掃描密碼檔案中的所有資訊,你可以使用getpwent函數。它的作用是依次取出檔案資料項目。

#include<pwd.h>

#include<sys/types.h>

void endpwent(void);

struct passwd *getpwent(void);

void setpwent(void);

getpwent函數依次返回使用者的資訊資料項目。當到達檔案尾是,它返回一個null 指標。如果已經掃描了足夠多的資料項目,你可以使用endpwent函數來終止

處理過程。setpwent函數重設讀指標到密碼檔案的開始位置。這樣下一個getpwent調用將開始一個新的掃描。

使用者和組標識還可以被其他一些不太常用的函數獲得。

#include<sys/types.h>

#include<unistd.h>

uid_t getuid(uid);

gid_t getgid(void);

int setuid(uid_t uid);

int getgid(gid_t gid);

上述函數只有在超級使用者下才可以使用。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.