运行“我是谁"在带有sudo的单个命令中不返回任何内容 [英] Running "who am i" in a single command with sudo doesnt return anything
问题描述
我正在尝试以以下方式在一行中运行我是谁"命令,但该命令不返回任何内容.
I am trying to run "who am i" command in a single line in the following way and it returns nothing.
echo $password | sudo -u user -S who am i
即使登录名命令也无法以这种方式工作.
Even logname command doesn't work in this way.
echo $password | sudo -u user -S logname
任何人都可以帮忙吗?
推荐答案
使用两个参数调用谁
时,将激活 -m
标志.从手册页:
When who
is invoked with two arguments, the -m
flag is activated. From the manual page:
-m
only hostname and user associated with stdin
在您的情况下,标准输入是管道,而不是终端,并且谁
(或 logname
)无法确定关联的用户.考虑以下shell命令片段:
In your case, the standard input is a pipe, rather than a terminal, and who
(or logname
) cannot determine the associated user. Consider this shell command snippet:
$ who am i
user pts/11 2014-09-04 00:15
$ logname
user
$ echo | who am i
$ echo | logname
logname: no login name
$
来自 GNU Coreutils who.c
来源:
if (my_line_only)
{
ttyname_b = ttyname (STDIN_FILENO);
if (!ttyname_b)
return;
if (STRNCMP_LIT (ttyname_b, DEV_DIR_WITH_TRAILING_SLASH) == 0)
ttyname_b += DEV_DIR_LEN; /* Discard /dev/ prefix. */
}
由于 ttyname()
在出现错误时会返回 NULL
,例如文件描述符不对应于终端( ENOTTY
),当
将立即返回. stdin
是管道时,who -m
Since ttyname()
returns NULL
on errors, such as the file descriptor not corresponding to a terminal (ENOTTY
), who -m
will return immediately when stdin
is a pipe.
对于 logname
,它的正确行为是返回 getlogin()
函数返回的字符串.不幸的是, getlogin()
手册页中的错误部分很清楚:
As for logname
, its proper behavior is to return the string that would have been returned by the getlogin()
function. Unfortunately, the bug section of the getlogin()
manual page is quite clear:
请注意,glibc不遵循POSIX规范,而是使用stdin代替/dev/tty.一个错误.(其他最近的系统,如SunOS 5.8和HP-UX 11.11和FreeBSD 4.8都在重定向标准输入时也返回登录名.)
Note that glibc does not follow the POSIX specification and uses stdin instead of /dev/tty. A bug. (Other recent systems, like SunOS 5.8 and HP-UX 11.11 and FreeBSD 4.8 all return the login name also when stdin is redirected.)
底线:您可能应该更新代码以使用 hostname
,例如 id -un
或您的解释器可能会提供的其他任何方式来确定当前用户. who -m
及其朋友不是很容易预测-坦白地说, who
的输出与 ls
一样,具有明显的预期性对于人类,而不是机器.
Bottom line: you should probably update your code to use hostname
and e.g. id -un
or whatever other means your shell interpretter may offer to determine the current user. who -m
and its friends are not very predictable - quite honestly the output of who
, much like ls
, has the distinct feel of being intended for humans, rather than machines.
这篇关于运行“我是谁"在带有sudo的单个命令中不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!