問題
最近在學習 ansible ,在使用普通用戶遠程執行 ip a
命令是發現提示錯誤:/bin/sh: ip: command not found。
原因
command not found 命令未找到,一般想到的是環境變量的問題。網上查找資料,也證實了這個猜測,根本原因是 ansible 登錄方式為 non-login shell(與之對應的是 login shell )。login shell 登陸后會加載 /etc/profile、~/.bash_profile,而 non-login shell 登陸后不會加載 /etc/profile、~/.bash_profile,而是加載 /etc/bashrc、~/.bashrc,一般的環境變量都設置在 /etc/profile、~/.bash_profile,所以這時就出現了找不到命令的情況。
- login shell:取得 shell 需要完整的登錄流程,就是說通過輸入賬號和密碼登錄系統。
- non-login shell:取得 shell 不需要重復登錄的舉動。比如 X Window 登錄 linux 后,再以 X 的圖形界面啟動終端機,此時那個終端機並沒有需要輸入賬號和密碼或者在原本的 shell 環境下再次執行 sh 命令,同樣也沒有輸入賬號密碼就進入新的 shell環境(前一個 shell 的子進程)。
解決方案
- 把 /etc/profile、~/.bash_profile中的環境變量同步一份到 /etc/bashrc、~/.bashrc,這種方案不推薦。
- 執行命令或腳本時命令都寫全路徑,我一般采用這種方案。
- 執行命令和腳本時前面首先加載環境變量,比如:
. /etc/profile &> /dev/null; . ~/.bash_profile &> /dev/null; ip a;
。