通過ssh會話執行bash別名
我在遠程主機上上設置過一個叫做 file_repl 的 bash 別名 。當我使用 ssh 命令登錄遠程主機后,可以很正常的使用這個別名。然而這個 bash 別名卻無法通過 ssh 來運行,像這樣:
$ ssh vivek@server1.cyberciti.biz file_replbash:file_repl:command not found
我要怎樣做才能通過 ssh 命令運行 bash 別名呢?
SSH 客戶端 (ssh) 是一個登錄遠程服務器并在遠程系統上執行 shell 命令的 Linux/Unix 命令。它被設計用來在兩個非信任的機器上通過不安全的網絡(比如互聯網)提供安全的加密通訊。
如何用 ssh 客戶端執行命令
通過 ssh 運行 free 命令或 date 命令 可以這樣做:
$ ssh vivek@server1.cyberciti.biz date
結果為:
Tue Dec 26 09:02:50 UTC 2017
或者:
$ ssh vivek@server1.cyberciti.biz free -h
結果為:
total used free shared buff/cache availableMem:2.0G 428M 138M 145M 1.4G 1.1GSwap:0B 0B 0B
理解 bash shell 以及命令的類型
bash shell 共有下面幾類命令:
- 別名,比如
ll - 關鍵字,比如
if - 函數 (用戶自定義函數,比如
genpasswd) - 內置命令,比如
pwd - 外部文件,比如
/bin/date
type 命令 和 command 命令 可以用來查看命令類型:
$ type -a datedate is /bin/date$ type -a freefree is /usr/bin/free$ command -V pwdpwd is a shell builtin$ type -a file_replis aliased to `sudo -i /shared/takes/master.replication'
date 和 free 都是外部命令,而 file_repl 是 sudo -i /shared/takes/master.replication 的別名。你不能直接執行像 file_repl 這樣的別名:
$ ssh user@remote file_repl
在 Unix 系統上無法直接通過 ssh 客戶端執行 bash 別名
要解決這個問題可以用下面方法運行 ssh 命令:
$ ssh -t user@remote /bin/bash -ic 'your-alias-here'$ ssh -t user@remote /bin/bash -ic 'file_repl'
ssh 命令選項:
-t:強制分配偽終端??梢杂脕碓谶h程機器上執行任意的 基于屏幕的程序,有時這非常有用。當使用-t時你可能會收到一個類似 “bash: cannot set terminal process group (-1): Inappropriate ioctl for device. bash: no job control in this shell .” 的錯誤。
bash shell 的選項:
-i:運行交互 shell,這樣 shell 才能運行 bash 別名。-c:要執行的命令取之于***個非選項參數的命令字符串。若在命令字符串后面還有其他參數,這些參數會作為位置參數傳遞給命令,參數從$0開始。
總之,要運行一個名叫 ll 的 bash 別名,可以運行下面命令:
$ ssh -t vivek@server1.cyberciti.biz -ic 'll'
結果為:

Running bash aliases over ssh based session when using Unix or Linux ssh cli
下面是我的一個 shell 腳本的例子:
#!/bin/bashI="tags.deleted.410"O="/tmp/https.www.cyberciti.biz.410.url.conf"box="vivek@server1.cyberciti.biz"[!-f "$I" ] && { echo "$I file not found。"; exit 10; }>$Ocat "$I" | sort | uniq | while read -r udouu="${u##https://www.cyberciti.biz}"echo "~^$uu 1;" >>"${O}"doneecho "Config file created at ${O} and now updating remote nginx config file"scp "${O}" ${box}:/tmp/ssh ${box} /usr/bin/lxc file push /tmp/https.www.cyberciti.biz.410.url.conf nginx-container/etc/nginx/ssh -t ${box} /bin/bash -ic 'push_config_job'
相關資料
更多信息請輸入下面命令查看 OpenSSH 客戶端 和 bash 的 man 幫助 :
$ man ssh$ man bash$ help type$ help command

























