bash 在bash脚本中获取SSH登录名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11052070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get SSH login name in bash script
提问by Bart van Heukelom
I have a Bash script on server Athat finds the logged in SSH user via the lognamecommand, even if it's run as rootwith sudo. If I SSH into server Afrom my desktop and run the script, it works fine.
我在服务器A上有一个 Bash 脚本logname,它通过命令找到登录的 SSH 用户,即使它root以sudo. 如果我从桌面通过SSH 连接到服务器A并运行该脚本,则它可以正常工作。
However, I've set up a post-commit hook on SVN server Swhich SSH's into Aand runs the script there, which causes logname to fail, with error "logname: no login name".
但是,我在 SVN 服务器S上设置了一个提交后挂钩,SSH 连接到A并在那里运行脚本,这导致 logname 失败,并出现错误“logname: no login name”。
If I SSH into Sfrom my desktop, then SSH into Afrom there, it works correctly, so the error must be in the fact that the SVN hook ultimately does not run from a virtual terminal.
如果我从我的桌面SSH 到S,然后从那里SSH 到A,它可以正常工作,所以错误一定是因为 SVN 钩子最终不是从虚拟终端运行的。
What alternative to lognamecan I use here?
logname我可以在这里使用什么替代方案?
采纳答案by Dmitri Chubarov
You could use the idcommand:
您可以使用以下id命令:
$ ssh 192.168.0.227 logname
logname: no login name
However
然而
$ ssh 192.168.0.227 id
uid=502(username) gid=100(users) groups=100(users)
In a bash script you can cut the username out of the id output with something like
在 bash 脚本中,您可以使用类似的内容从 id 输出中删除用户名
$ id | cut -d "(" -f 2 | cut -d ")" -f1
username
To have a script that works both in a sudo environment and without a terminal you could always execute different commands conditionally.
要拥有一个既可以在 sudo 环境中运行又可以在没有终端的情况下运行的脚本,您始终可以有条件地执行不同的命令。
if logname &> /dev/null ; then
NAME=$( logname )
else
NAME=$( id | cut -d "(" -f 2 | cut -d ")" -f1 )
fi
echo $NAME
回答by Bart van Heukelom
This is what I ended up with.
这就是我的结果。
if logname &> /dev/null; then
human_user=$(logname)
else
if [ -n "$SUDO_USER" ]; then
human_user=$SUDO_USER
else
human_user=$(whoami)
fi
fi
回答by Jens
Use id -nu. No silly forking and cutting to get at the user name.
使用id -nu. 没有愚蠢的分叉和切割来获取用户名。

