【发布时间】:2013-05-16 00:26:42
【问题描述】:
我正在尝试进行网络日志记录,并使用 getpwnam() 函数来检查用户名是否存在。但是对于有效的用户名 getpwnam 返回错误:没有这样的文件或目录。所以我尝试了 getpwnam_r(),但同样的错误也失败了。我在嵌入式 arm linux 上运行,我使用 /etc/passwd 来存储密码(我没有 /etc/shadow)。我的测试程序是:
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int
main(int argc, char *argv[])
{
struct passwd pwd;
struct passwd *result;
char *buf;
size_t bufsize;
int s;
if (argc != 2) {
fprintf(stderr, "Usage: %s username\n", argv[0]);
exit(EXIT_FAILURE);
}
bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1) /* Value was indeterminate */
bufsize = 16384; /* Should be more than enough */
buf = malloc(bufsize);
if (buf == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
s = getpwnam_r(argv[1], &pwd, buf, bufsize, &result);
if (result == NULL) {
if (s == 0)
printf("Not found\n");
else {
errno = s;
perror("getpwnam_r");
}
exit(EXIT_FAILURE);
}
printf("Name: %s; UID: %ld\n", pwd.pw_gecos, (long) pwd.pw_uid);
exit(EXIT_SUCCESS);
}
密码文件只能由root写入:
/ # ls -l /etc/passwd
-rw-r--r-- 1 root root 207 Jan 1 00:29 /etc/passwd
/ #
我也尝试使用 root 权限运行我的程序 (test),但是当我给它一个现有的用户名时它也失败了。
/ # /tmp/test admin
getpwnam_r: No such file or directory
/ #
1) 那么,我忘记了什么,或者应该补充什么?
2) 我需要使用/etc/shadow 文件来存储系统用户的密码吗?
更新:
我的密码文件是:
~ # cat /etc/passwd
root:b6MVch7fPLasN:0:0:root:/home/root:/bin/ash
admin:8Mt/Jtxcyg8AY:1000:1000:admin:/tmp:/tmp/cli
user:5v4HoPrA9NtUo:1001:1000:user:/tmp:/tmp/cli
~ #
提前致谢!巴基尔
【问题讨论】:
-
No such file or directory为ENOENT打印,如果给定的name不存在,则可能返回。那么你确定你是用一个有效的账户名来测试这个吗? -
是的,我确定。我什至使用 adduser 命令添加新用户,但得到了相同的结果。也许我需要在 /etc 目录中更改或添加一些其他文件?我的密码文件是: ~ # cat /etc/passwd root:b6MVch7fPLasN:0:0:root:/home/root:/bin/ash admin:8Mt/Jtxcyg8AY:1000:1000:admin:/tmp:/tmp/cli用户:5v4HoPrA9NtUo:1001:1000:user:/tmp:/tmp/cli ~ #
-
您实际使用的是什么
bufsize?你可能想把它打印出来。 -
我的 bufsize = 1024 字节。
-
您可以为您的程序 (
strace /tmp/test) 运行 strace 以查看发生了什么以及发生了什么失败。