![](/img/trans.png)
[英]How to execute a command on a machineA from machineX through a shell script?
[英]How to execute command from shell script on machineB and machineC by running it in machineA
我有以下提到的三台機器-
machineA
machineB
machineC
machineB和machineC具有此目錄-
/bat/data/snapshot_t1/
現在,我需要從machineA運行下面的shell腳本,並在/bat/data/snapshot_t1/
路徑下找到machineB和machineC中的最新目錄(通過登錄我猜的那些機器)。
下面是我的Shell腳本,在其中我知道如何使用find命令以及sort和tail來獲取最新目錄。
現在,我應該從machineA運行下面的shell腳本,然后在machineB和machineC中找到最新的目錄。
#!/bin/bash
readonly FILERS_LOCATION=(machineB machineC)
readonly DIRECTORY_LOCATION=/bat/data/snapshot_t1/
# login to machineB and find out the latest directory in machineB
dir1=`find $DIRECTORY_LOCATION -type d | sort | tail -1`; echo $dir
# login to machineC and find out the latest directory in machineC
dir2=`find $DIRECTORY_LOCATION -type d | sort | tail -1`; echo $dir
我如何從在machineA中運行的shell腳本登錄到machineB和machineC,然后在machineB和machineC上執行某些命令,然后將結果返回並存儲在某個變量中,例如dir1和dir2。
假設登錄名是david
,假設我在machineB和machineC上也設置了密鑰。
您可以將machineA
的公鑰復制到david@machineB
和david@machineC
搜索ssh-keygen
和ssh-copy-id
設置密鑰后,您可以從machineA
運行任何命令,而無需手動鍵入任何密碼。 ssh david@machineB hostname
獲取dir1
。
dir1=$(ssh david@machineB find $DIR -type d | sort | tail -1)
使用SSH遠程執行命令,並將結果通過管道傳遞到另一個程序/ shell腳本中進行處理。 ssh user@host yourscript.sh | anotherscript.sh
ssh user@host yourscript.sh | anotherscript.sh
。
ssh user@host yourscript.sh
在遠程計算機上執行命令並在stdout
上打印結果,因此您可以捕獲它並將其重定向到文件( ssh user@host yourscript.sh > result.txt
)以稍后處理或直接處理將其通過管道ssh user@host yourscript.sh | anotherscript.sh
到另一個腳本( ssh user@host yourscript.sh | anotherscript.sh
)。
您可以檢查$?
遠程命令的退出狀態的變量。
你可以使用ssh
命令是ssh -p port_num user @ host
port_num是端口號 ,默認為22 。 user是userName主機是ip或hostName 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.