通過ssh會話執(zhí)行bash別名
我在遠(yuǎn)程主機(jī)上上設(shè)置過一個叫做 file_repl 的 bash 別名 。當(dāng)我使用 ssh 命令登錄遠(yuǎn)程主機(jī)后,可以很正常的使用這個別名。然而這個 bash 別名卻無法通過 ssh 來運(yùn)行,像這樣:
$ ssh vivek@server1.cyberciti.biz file_repl
bash:file_repl:command not found
我要怎樣做才能通過 ssh 命令運(yùn)行 bash 別名呢?
SSH 客戶端 (ssh) 是一個登錄遠(yuǎn)程服務(wù)器并在遠(yuǎn)程系統(tǒng)上執(zhí)行 shell 命令的 Linux/Unix 命令。它被設(shè)計用來在兩個非信任的機(jī)器上通過不安全的網(wǎng)絡(luò)(比如互聯(lián)網(wǎng))提供安全的加密通訊。
如何用 ssh 客戶端執(zhí)行命令
通過 ssh 運(yùn)行 free
命令或 date 命令 可以這樣做:
$ ssh vivek@server1.cyberciti.biz date
結(jié)果為:
Tue Dec 26 09:02:50 UTC 2017
或者:
$ ssh vivek@server1.cyberciti.biz free -h
結(jié)果為:
total used free shared buff/cache available
Mem:2.0G 428M 138M 145M 1.4G 1.1G
Swap:0B 0B 0B
理解 bash shell 以及命令的類型
bash shell 共有下面幾類命令:
- 別名,比如
ll
- 關(guān)鍵字,比如
if
- 函數(shù) (用戶自定義函數(shù),比如
genpasswd
) - 內(nèi)置命令,比如
pwd
- 外部文件,比如
/bin/date
type 命令 和 command 命令 可以用來查看命令類型:
$ type -a date
date is /bin/date
$ type -a free
free is /usr/bin/free
$ command -V pwd
pwd is a shell builtin
$ type -a file_repl
is aliased to `sudo -i /shared/takes/master.replication'
date
和 free
都是外部命令,而 file_repl
是 sudo -i /shared/takes/master.replication
的別名。你不能直接執(zhí)行像 file_repl
這樣的別名:
$ ssh user@remote file_repl
在 Unix 系統(tǒng)上無法直接通過 ssh 客戶端執(zhí)行 bash 別名
要解決這個問題可以用下面方法運(yùn)行 ssh 命令:
$ ssh -t user@remote /bin/bash -ic 'your-alias-here'
$ ssh -t user@remote /bin/bash -ic 'file_repl'
ssh
命令選項:
-t
:強(qiáng)制分配偽終端??梢杂脕碓谶h(yuǎn)程機(jī)器上執(zhí)行任意的 基于屏幕的程序,有時這非常有用。當(dāng)使用-t
時你可能會收到一個類似 “bash: cannot set terminal process group (-1): Inappropriate ioctl for device. bash: no job control in this shell .” 的錯誤。
bash shell 的選項:
-i
:運(yùn)行交互 shell,這樣 shell 才能運(yùn)行 bash 別名。-c
:要執(zhí)行的命令取之于***個非選項參數(shù)的命令字符串。若在命令字符串后面還有其他參數(shù),這些參數(shù)會作為位置參數(shù)傳遞給命令,參數(shù)從$0
開始。
總之,要運(yùn)行一個名叫 ll
的 bash 別名,可以運(yùn)行下面命令:
$ ssh -t vivek@server1.cyberciti.biz -ic 'll'
結(jié)果為:
Running bash aliases over ssh based session when using Unix or Linux ssh cli
下面是我的一個 shell 腳本的例子:
#!/bin/bash
I="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; }
>$O
cat "$I" | sort | uniq | while read -r u
do
uu="${u##https://www.cyberciti.biz}"
echo "~^$uu 1;" >>"${O}"
done
echo "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'
相關(guān)資料
更多信息請輸入下面命令查看 OpenSSH 客戶端 和 bash 的 man 幫助 :
$ man ssh
$ man bash
$ help type
$ help command