
我需要建立一個腳本來登入 中列出的所有伺服器servers.txt
。我想使用密碼,而不是無密碼。登入後,我需要設定一個變數並執行if
- then
- else
。工作完成後,應該在本機電腦上建立一個文件,而不是在遠端電腦上。 (本機)檔案將包含未執行某些進程的電腦的主機名稱。
總體思路是:
#!/bin/bash
while read line
do
sshpass -p ******** ssh "mydomain1\admin1"@$line bash -s << EOF
pwd=*********
var=$"(ps -ef | grep http | grep -v grep | wc -l)"
if (( var > 0 ))
then
echo "$pwd" | sudo -S ps -ef | grep patrol | grep -v grep | awk '{print $2}' | xargs kill
echo "$pwd" | sudo -S rm -rf /data/abc /etc/efg
#need to create the log on local machine, not on remote machine
hostname >> /find.txt
else
#need to create the log on local machine, not on the remote machine
hostname >> /agentnotthere.txt
fi
EOF
#servers.txt contains server names
done < servers.txt
顯然,上面的第 5-16 行形成了一個此處文檔,其中包含要在遠端主機上運行的命令。在此文件中,我有命令hostname >> /find.txt
和hostname >> /agentnotthere.txt
.正如我的介紹段落中以及程式碼中的註釋中所述,我希望將(遠端)主機名稱寫入本機文件,而不是遠端電腦上的文件。顯然,遠端機器上的命令將寫入文件command >> filename
在遠端機器上。
如何讓我的腳本(用於ssh
在遠端電腦上執行一些命令)根據在遠端電腦上執行的測試結果將輸出寫入本機檔案?
答案1
我認為沒有一種簡單的方法可以完成您想要的操作,這意味著將本地主機上的文件與遠端電腦上執行的腳本分開寫入。
不過,您可以輕鬆地將腳本的輸出透過管道傳輸到一個本機檔案:
ssh host << EOF > output_file
some commands
to be executed
EOF
這樣,您可以重組腳本,使其執行ssh
多次(這會增加開銷,但您可以透過在設定檔中ssh
使用來減輕大部分開銷)。ControlPersist
ssh
所以你最終會得到這樣的結果(偽bash):
echo "get the output of var script" | ssh host > var_value
if var read from the file is more than zero; then
echo "the thing you want" | ssh host >> /find.txt
else
echo "the other thing you want" | ssh host >> /agentnotthere.txt
fi
這應該很適合您的用例:)
我對腳本本身的兩點看法:
- Ansible 或其他組態管理工具之一可能比編寫 bash 腳本更適合此任務
- 從安全性角度來看,使用 SSH 密碼而不是金鑰身份驗證是不好的。但我曾經遇到過由於公司政策/舊的嵌入式東西不支持它/等等而無法實現這一點的情況。
ps aux | grep -v grep | grep something
您可以使用pgrep
和,而不是使用舊的樣板pkill
。它們是標準的coreutils
,所以除非您使用非常古老的系統,否則它們應該可用。