加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

通过ssh运行命令也运行.bashrc?

发布时间:2020-12-15 16:59:21 所属栏目:安全 来源:网络整理
导读:在我阅读bash联机帮助页时,只应在以交互方式运行 shell时执行.bashrc.该联机帮助页将交互定义为: An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to ter
在我阅读bash联机帮助页时,只应在以交互方式运行 shell时执行.bashrc.该联机帮助页将交互定义为:

An interactive shell is one started without non-option arguments
and without the -c option whose standard input and error are both
connected to terminals (as determined by isatty(3)),or one started
with the -i option. PS1 is set and $- includes i if bash is
interactive,allowing a shell script or a startup file to test this
state.

然而,使用ssh执行命令也会导致运行.bashrc,这与我期望的相反,因为该命令不是以交互方式运行的.所以,这种行为看起来像一个bug,但它似乎在我尝试过的Red Hat和bash的所有版本上都很普遍.有人能解释为什么这种行为是正确的吗?

还有一点:即使运行.bashrc,也会设置$ – 和$PS,就好像shell是非交互式的(正如我所料).

$grep USER /etc/passwd
USER:x:UID:GID:UNAME:/home/USER:/bin/bash

$cat ~/.bashrc
echo bashrc:$-,$PS1

$bash -c 'echo $-'
hBc

$ssh localhost 'echo $-' </dev/null 2>/dev/null
USER@localhost's password:
bashrc:hBc,hBc

$ssh localhost 'ps -ef | grep $$' </dev/null 2>/dev/null
USER@localhost's password:
bashrc:hBc,USER 28296 28295 0 10:04 ? 00:00:00 bash -c ps -ef | grep $$
USER 28297 28296 0 10:04 ? 00:00:00 ps -ef
USER 28298 28296 0 10:04 ? 00:00:00 grep 28296

我目前正在通过在.bashrc中测试[[$ – = * i *]]来解决这个问题,但似乎我不应该这样做.

一个示例服务器,在我的主目录中不包含.bashrc(和.ssh)中的其他文件具有以下配置:

$cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.7 (Tikanga)

$bash --version
GNU bash,version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation,Inc.

我尝试过的bash版本:3.00.15,3.1.17,3.2.25,4.1.2(后者在Red Hat 6.3上).

从 Bash manual:

Bash attempts to determine when it is being run with its standard input connected to a network connection,as when executed by the remote shell daemon,usually rshd,or the secure shell daemon sshd. If Bash determines it is being run in this fashion,it reads and executes commands from ~/.bashrc,if that file exists and is readable. It will not do this if invoked as sh. The --norc option may be used to inhibit this behavior,and the --rcfile option may be used to force another file to be read,but rshd does not generally invoke the shell with those options or allow them to be specified.

默认Debian bashrc框架中的解决方法是将以下内容放在.bashrc的顶部:

# If not running interactively,don't do anything
[ -z "$PS1" ] && return

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读