emk*_*203 5 server ssh command-line networking
我想看看我是通过 ssh 连接还是运行本地终端。
如果我只是通过 ssh 进入服务器而不更改为 root via sudo
,这很容易。任何变量$SSH_CLIENT
,$SSH_CONNECTION
或$SSH_TTY
可用于检查一个变量是通过 SSH 连接还是本地连接。
问题:当我提升到 root 帐户sudo -i
以执行管理操作时,这些变量都没有帮助 - 它们都是空的。
确定连接是本地连接还是通过 SSH 连接的最佳方法是什么?
编辑:通过接受的答案,很容易有一个不显眼的 bash 提示,它反映了 ssh 状态和权限:
if [ "$color_prompt" = yes ]; then
# when system is accessed via SSH, hostname with light grey background
if [[ $(pstree -s $$) = *sshd* ]]; then sshbg="\[\033[48;5;7m\]"; fi
# when used as root, change username to orange and '#' to red for prompt
if [ $(id -u) -eq 0 ]; then usercol="\[\033[38;5;3m\]"; hashcol="\[\033[38;5;1m\]"; else usercol="\[\033[38;5;2m\]"; fi
# bash PS1 prompt
PS1="${usercol}\u\[$(tput sgr0)\]@\[$(tput sgr0)\]\[\033[38;5;4m\]${sshbg}\h\[$(tput sgr0)\]:\[$(tput sgr0)\]\[\033[38;5;6m\]\w\[$(tput sgr0)\]${hashcol}\\$ \[$(tput sgr0)\]"
unset sshbg rootcol hashcol
fi
Run Code Online (Sandbox Code Playgroud)
该部件的定时版本pstree
运行时间不到 20 毫秒,因此可以在不引入明显延迟的情况下使用。