Jos*_*son 35 database linux shell posix user-accounts
我可以通过/ etc/passwd grep,但这似乎很麻烦.'finger'没有安装,我想避免这种依赖.这是一个程序,所以如果有一些命令让你只是访问用户信息会很好.
big*_*ose 45
你没有指定编程语言,所以我假设你想要使用shell; 这是Posix炮弹的答案.
两个步骤:获取相应的记录,然后从该记录中获取所需的字段.
首先,通过查询passwd表来获取帐户记录:
$ user_name=foo
$ user_record="$(getent passwd $user_name)"
$ echo "$user_record"
foo:x:1023:1025:Fred Nurk,,,:/home/foo:/bin/bash
Run Code Online (Sandbox Code Playgroud)
对于歇斯底里的葡萄干,用户的全名记录在称为"GECOS"字段的字段中 ; 更复杂的是,这个字段通常有自己的结构,全名只是几个可选子字段之一.因此,任何想要从帐户记录中获取全名的内容都需要解析这两个级别.
$ user_record="$(getent passwd $user_name)"
$ user_gecos_field="$(echo "$user_record" | cut -d ':' -f 5)"
$ user_full_name="$(echo "$user_gecos_field" | cut -d ',' -f 1)"
$ echo "$user_full_name"
Fred Nurk
Run Code Online (Sandbox Code Playgroud)
您的编程语言可能具有库函数,可以用更少的步骤完成此操作.在C中,您将使用'getpwnam'函数,然后解析GECOS字段.
Dav*_*itt 26
在现代的glibc系统上,使用以下命令:
getent passwd "username" | cut -d ':' -f 5
Run Code Online (Sandbox Code Playgroud)
这将使您获得passwd指定用户的条目,独立于底层NSS模块.
阅读的联机帮助页getent.
如果您已经编程,可以使用getpwnam()C函数:
struct passwd *getpwnam(const char *name);
Run Code Online (Sandbox Code Playgroud)
该passwdstruct有一个pw_gecos成员,该成员应包含用户的全名.
阅读的联机帮助页getpwnam().
请注意,许多系统使用此字段的次数超过用户的全名.最常见的约定是,在字段中使用逗号()作为分隔符,并首先放置用户的真实姓名.
小智 8
如果您想从C中执行此操作,请尝试以下操作:
#include <sys/types.h>
#include <pwd.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
/* Get full name of a user, given their username. Return 0 for not found,
-1 for error, or 1 for success. Copy name to `fullname`, but only up
to max-1 chars (max includes trailing '\0'). Note that if the GECOS
field contains commas, only up to to (but not including) the first comma
is copied, since the commas are a convention to add more than just the
name into the field, e.g., room number, phone number, etc. */
static int getfullname(const char *username, char *fullname, size_t max)
{
struct passwd *p;
size_t n;
errno = 0;
p = getpwnam(username);
if (p == NULL && errno == 0)
return 0;
if (p == NULL)
return -1;
if (max == 0)
return 1;
n = strcspn(p->pw_gecos, ",");
if (n > max - 1)
n = max - 1;
memcpy(fullname, p->pw_gecos, n);
fullname[n] = '\0';
return 1;
}
int main(int argc, char **argv)
{
int i;
int ret;
char fullname[1024];
for (i = 1; i < argc; ++i) {
ret = getfullname(argv[i], fullname, sizeof fullname);
if (ret == -1)
printf("ERROR: %s: %s\n", argv[i], strerror(errno));
else if (ret == 0)
printf("UNKONWN: %s\n", argv[i]);
else
printf("%s: %s\n", argv[i], fullname);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结合其他答案,在最小的Debian/Ubuntu安装上测试:
getent passwd `whoami` | cut -d ':' -f 5 | cut -d ',' -f 1
Run Code Online (Sandbox Code Playgroud)
小智 6
试试这个:
getent passwd eutl420 | awk -F':' '{gsub(",", "",$5); print $5}'
Run Code Online (Sandbox Code Playgroud)
前两个答案可以合并为一行:
getent passwd <username> | cut -d ':' -f 5 | cut -d ',' -f 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44803 次 |
| 最近记录: |