以编程方式从Unix的用户名获取UID和GID?

我试图使用setuid()和setgid()来设置一个程序的各自的id从根放下权限,但使用它们,我需要知道我想改变的用户的uid和gid。

有没有系统调用来做到这一点? 我不想硬编码或从/ etc / passwdparsing。

另外,我想以编程方式而不是使用:

id -u USERNAME

任何帮助将不胜感激

看看getpwnam()和getgrnam()函数。

您想要使用getpw *系列调用系列,通常在pwd.h中 。 它本质上是/ etc / passwd中的信息的C级接口。

#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; } 

看看getpwnam和结构passwd。

您可以使用以下代码片段:

 #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; } 

Ref: getpwnam() getgrnam()