要做的事情
遠(yuǎn)程主機(your.host.com)上部署有docker顾画,期望從本地開發(fā)機ssh到遠(yuǎn)程主機爆价,在指定的容器中執(zhí)行命令箭养,基本命令如下:
/usr/bin/ssh -i /home/users/yangjinfeng02/.ssh/.id_rsa -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no -t rd@your.host.com "sudo docker exec -u rd -it 0284c4594aecc7689de407e8d2aa9106edaf646b000e3c362ad95f6dde5c9f0b bash -c 'pwd'"
出現(xiàn)的問題
登入shell終端,手動執(zhí)行上面的命令模孩,一切ok付翁。但是放到crontab中無法執(zhí)行简肴,重定向輸出到文件晃听,得到如下信息
Pseudo-terminal will not be allocated because stdin is not a terminal.
問題排查與解決
注意到ssh命令中的-t參數(shù)百侧,是用來控制給ssh分配偽終端。查看ssh幫助
-T Disable pseudo-tty allocation.
-t Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g., when implementing
menu services. Multiple -t options force tty allocation, even if ssh has no local tty.
注意到上述問題出錯信息能扒,結(jié)合ssh -t參數(shù)的含義佣渴,
Multiple -t options force tty allocation, even if ssh has no local tty.
可看出問題是在于分配終端引起的。
使用 ssh -t -t 執(zhí)行初斑,發(fā)現(xiàn)crontab下運行正常辛润,問題得以解決。
延伸1——不分配偽終端
既然是終端分配導(dǎo)致的见秤,那么根據(jù)ssh -T參數(shù)的含義砂竖,是否可以disable偽終端的分配呢真椿?可以進行試驗,執(zhí)行如下命令
/usr/bin/ssh -i /home/users/yangjinfeng02/.ssh/.id_rsa -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no -T rd@your.host.com "sudo docker exec -u rd -it 0284c4594aecc7689de407e8d2aa9106edaf646b000e3c362ad95f6dde5c9f0b bash -c 'pwd'"
此時不管是命令行乎澄,還是crontab里突硝,均無法運行。提示如下錯誤信息
sudo: sorry, you must have a tty to run sudo
出現(xiàn)該問題置济,是因為sudo命令必須在終端中執(zhí)行解恰。如果要突破該限制,需要修改/etc/sudoers浙于,有兩種選擇
Replace Defaults requiretty by Defaults !requiretty in your /etc/sudoers. This will impact your global sudo configuration.
Alternatively, you can change this configuration at a per user, per group or per command basis
Defaults!/path/to/my/bin !requiretty
Defaults:myuser !requiretty
延伸2——登錄shell和非登錄shell的區(qū)別
直接在終端里執(zhí)行shell命令护盈,與crontab里執(zhí)行,本質(zhì)區(qū)別是二者環(huán)境變量的差異羞酗。
登錄shell將查找4個不同的啟動文件來處理其中的命令腐宋。 bash shell處理文件的順序如下:
1:/etc/profile
2:/etc/profile.d等待配置文件
3:$HOME/.bash_profile 會加載$HOME/.bashrc和/etc/bashrc
4:$HOME/.bash_login
5:$HOME/.profile
非登入shell則按如下順序加載配置文件
1:/etc/bashrc
2:~/.bashrc