2009-11-13 22 views
9

我想要一個bash腳本,會做:如何使用平在腳本

for c in computers: 
do 
    ping $c 
    if ping is sucessfull: 
     ssh $c 'check something' 
done 

如果我只做ssh和計算機是iresponsive,它永遠的超時。所以我想用ping的輸出來查看電腦是否存在。我怎麼做?其他的想法將是巨大的也

回答

12

使用ping的返回值:

for C in computers; do 
    ping -q -c 1 $C && ssh $C 'check something' 
done 

ping將與值0如果單平(-c 1)succceeds退出。在ping超時時間內,或者如果$C無法解析,它將以非零值退出。

+1

這個答案是錯誤的,如果你還沒有爲你正在ping的目標IP設置默認路由,你仍然會得到0返回值。 – 2013-02-22 14:51:04

+2

@SpaceRocker:非常有趣!我剛剛檢查過'man ping',並且我傾向於將這種行爲視爲'ping'中的一個錯誤,因爲在那種情況下,我預計返回值爲2。引用:_「如果ping完全沒有收到任何回覆數據包,它將以代碼1退出。如果指定了數據包計數和最後期限,並且在截止時間到達之前收到的計數數據包數少於它,它也將退出與代碼1.在其他錯誤退出代碼2.否則它退出代碼0.這使得有可能使用退出代碼來查看主機是否存活。「_你對此有什麼看法? – Stephan202 2013-02-22 15:16:13

8

ping命令中使用-w開關(或在FreeBSD和OS X上爲-t),然後檢查命令的返回值。

ping -w 1 $c 
RETVAL=$? 
if [ $RETVAL -eq 0 ]; then 
    ssh $c 'check something' 
fi 

您可能需要調整您通過與-w參數,如果你要連接的主機都遠,延遲較高。

man ping

-w deadline 
      Specify a timeout, in seconds, before ping exits regardless of 
      how many packets have been sent or received. In this case ping 
      does not stop after count packet are sent, it waits either for 
      deadline expire or until count probes are answered or for some 
      error notification from network. 
+0

該行RETVAL = $?不起作用 - 我是bash新手。你如何使它工作? – Guy 2009-11-13 09:38:20

+0

對不起 - 我的錯。它的作品 – Guy 2009-11-13 09:41:56

+0

應該是'[$ RETVAL -eq 0]'。 – Rhubbarb 2012-02-02 10:44:20

-1

使用此在您的bash循環:

RESULT="64" 
PING=$(ping 127.0.0.1 -c 1 | grep 64 | awk '{print $1}') 
if [ "$RESULT" != "$PING" ] 
then 
    #ping failed 
else 
    #ping successful, do ssh here 
fi 
4

並非所有的網絡環境允許Ping經歷(雖然許多人),而不是所有主機會回答一個ping請求。我會建議不要使用平,而是設置連接超時SSH:

 
for c in compuers; do 
    ssh -o ConnectTimeout=2 $c 'check something' 
done 
+0

這是唯一正確的解決方案。當SSH連接成功時,ping會失敗的原因還有很多。 – 2015-03-18 00:34:42

0

使用64值作爲測量工具是不符合邏輯。取而代之的是使用接收/丟失數據包的數量。

這個腳本會工作:

RESULT="1" 
PING=$(ping ADDRESS -c 1 | grep -E -o '[0-9]+ received' | cut -f1 -d' ') 
if [ "$RESULT" != "$PING" ] 
then 
    DO SOMETHING 
else 
    DO SOMETHING 
fi 
0

這裏是我的黑客:

#ipaddress shell variable can be provided as an argument to the script. 
while true 
do 
    nmap_output=$(nmap -p22 ${ipaddress}) 
    $(echo ${nmap_output} | grep -q open) 
    grep_output=$? 
    if [ "$grep_output" == 0 ] ; then 
     #Device is LIVE and has SSH port open for clients to connect 
     break 
    else 
     #[01 : bold 
     #31m : red color 
     #0m : undo text formatting 
     echo -en "Device is \e[01;31mdead\e[0m right now .... !\r" 
    fi 
done 
#\033[K : clear the text for the new line 
#32 : green color 
echo -e "\033[KDevice is \e[01;32mlive\e[0m !" 
ssh [email protected]${ipaddress} 

不依賴於只是ping。爲什麼?
- 成功ping並不保證您成功訪問ssh。您仍然可以將ping測試添加到此腳本的開頭,如果ping失敗並退出,則不執行上述操作。

高於bash腳本代碼段,驗證您嘗試訪問 的設備是否有客戶端(您)要連接到的SSH端口。需要安裝nmap包。

我不明白你爲什麼要ssh到該腳本中的多臺計算機。但是,我的ssh可以用於一個設備,並且可以進行修改以滿足您的需求。

+0

我在添加這個答案,希望未來的用戶訪問此頁面時,可以獲得另一種智能SSH登錄設備的方法。 – smRaj 2015-03-18 00:34:49