2009-06-17 48 views
11

我試圖使用setuid()和setgid()來設置程序的各自的id從根刪除權限,但使用它們我需要知道我想要更改的用戶的uid和gid 。以編程方式從Unix中的用戶名獲取UID和GID?

有沒有系統調用來做到這一點?我不想硬編碼或從/ etc/passwd解析。

另外,我想這是通過編程而不是使用:

ID -u USERNAME

任何幫助,將不勝感激

+0

出了什麼問題解析/ etc/passwd文件? – eduffy 2009-06-17 20:10:52

+1

我應該說,「我寧願不要解析/ etc/passwd」,因爲我懷疑有一種更簡單的方法,並且感謝答案,我找到了它。 – Evan 2009-06-17 20:39:42

回答

3

你想使用系統調用的getpw *系列,一般在pwd.h。它基本上是/ etc/passwd中信息的C級接口。

1

看看getpwnam和struct passwd。

3
#include <sys/types.h> 
#include <pwd.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <stdio.h> 

int main() 
{ 
    char *username = ... 

    struct passwd *pwd = calloc(1, sizeof(struct passwd)); 
    if(pwd == NULL) 
    { 
     fprintf(stderr, "Failed to allocate struct passwd for getpwnam_r.\n"); 
     exit(1); 
    } 
    size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX) * sizeof(char); 
    char *buffer = malloc(buffer_len); 
    if(buffer == NULL) 
    { 
     fprintf(stderr, "Failed to allocate buffer for getpwnam_r.\n"); 
     exit(2); 
    } 
    getpwnam_r(username, pwd, buffer, buffer_len, &pwd); 
    if(pwd == NULL) 
    { 
     fprintf(stderr, "getpwnam_r failed to find requested entry.\n"); 
     exit(3); 
    } 
    printf("uid: %d\n", pwd->pw_uid); 
    printf("gid: %d\n", pwd->pw_gid); 

    free(pwd); 
    free(buffer); 

    return 0; 
} 
0

您可以使用下面的代碼片段:

#include <pwd.h> 
#include <grp.h> 

gid_t Sandbox::getGroupIdByName(const char *name) 
{ 
    struct group *grp = getgrnam(name); /* don't free, see getgrnam() for details */ 
    if(grp == NULL) { 
     throw runtime_error(string("Failed to get groupId from groupname : ") + name); 
    } 
    return grp->gr_gid; 
} 

uid_t Sandbox::getUserIdByName(const char *name) 
{ 
    struct passwd *pwd = getpwnam(name); /* don't free, see getpwnam() for details */ 
    if(pwd == NULL) { 
     throw runtime_error(string("Failed to get userId from username : ") + name); 
    } 
    return pwd->pw_uid; 
} 

編號:getpwnam()getgrnam()

相關問題