Linux-两种ssh远程执行命令方式加载环境变量区别

最近在编写脚本的时候发现一个问题,在执行kubectl -n kube-system get pods这个命令的时候,通过ssh root@ip commandssh root@ip command登录后执行得到了不同的结果,

  • ssh root@ip command下结果:
[root@test1 ~]# ssh [email protected]'kubectl -n kube-system get pods'
error: the server doesn't have a resource type "pods"
  • ssh root@ip command登录后执行命令:
[root@test3 ~]# kubectl -n kube-system get pods
NAME                                                 READY   STATUS    RESTARTS   AGE
coredns-fb8b8dccf-5px49                              1/1     Running   0          161d
coredns-fb8b8dccf-tdlbd                              1/1     Running   0          161d
etcd-test3.weikayuninternal.com                      1/1     Running   2          191d
kube-apiserver-test3.weikayuninternal.com            1/1     Running   1          191d
kube-controller-manager-test3.weikayuninternal.com   1/1     Running   2          191d
kube-flannel-ds-amd64-nj5vz                          1/1     Running   0          161d
kube-proxy-vbm7c                                     1/1     Running   0          161d
kube-scheduler-test3.weikayuninternal.com            1/1     Running   2          191d
kubernetes-dashboard-5f7b999d65-87bnk                1/1     Running   0          161d

从上面可以看到SSH远程执行获取pods失败了,但是shell窗口执行却成功了,所以我们可以猜到两者之间一定有什么区别导致结果的不同。那么区别在哪里呢?通过研究发现两者的环境变量存在区别,通过执行printenv可以查看所有设置的环境变量:

  • ssh root@ip command:
[root@iZ23ozpjtzfZ ~]# ssh [email protected] 'printenv'
[email protected]'s password: 
...
USER=root
...
  • ssh root@ip登录后执行命令:
[root@test3 ~]# printenv
...
USER=root
KUBECONFIG=/etc/kubernetes/admin.conf
...

通过上面可以看到SSH远程执行的时候是没有KUBECONFIG这个环境变量,而Shell窗口是有的,为什么有这个区别呢?这就要从Linux的bash的四种模式说起。
bash的四种模式:

  • login + interactive
  • login + non-interactive
  • non-login + interactive
  • non-login + non-interactive
    这四种模式的具体介绍大家可以通过man bash查看,这里不过多的介绍了,我们主要看一下加载环境变量配置文件的区别:
login interactive + non-login non-interactive + non-login
/etc/profile A
/etc/bash.bashrc A
~/.bashrc B
~/.bash_profile B1
~/.bash_login B2
~/.profile B3
BASH_ENV A

从上面可以看出不同方式下加载的配置文件不同,那么怎么知道我们是加载了那些配置文件呢? 这里有一个验证的方法,就是在上面的每个配置文件中添加一句echo $/etc/profile这样的命令,把每个文件的路径打印出来。当配置文件被加载时,会输出相应的文件名,本例中在两个文件中加了该命令:/etc/pfoile, ~/.bashrc,然后使用不同SSH方式执行命令的结果如下。

  • ssh root@ip command
[root@iZ23ozpjtzfZ ~]# ssh [email protected] 'echo $-'
[email protected]'s password: 
@_/.bash_rc

只加载了.bashrc文件,未加载/etc/profile。

  • ssh root@ip登录后执行命令:
root@iZ23ozpjtzfZ ~]# ssh [email protected]
[email protected]'s password: 
Last login: Thu Nov 21 18:41:31 2019 from 10.168.81.39

Welcome to Alibaba Cloud Elastic Compute Service !

@/etc/profile
@_/.bash_rc
[root@test3 ~]# echo $-
himBH

从输出可以看到两个配置都加载了,而KUBECONFIG只定义在/etc/profile中,没有定义在.bashrc文件中,所以通过ssh root@ip command执行时没有拿到KUBECONFIG这个环境变量从而导致报错。知道原因后我们就可以将KUBECONFIG环境变量添加到.bashrc文件即可。

你可能感兴趣的:(Linux-两种ssh远程执行命令方式加载环境变量区别)