2015-10-13 59 views
0

我正在使用for循環連接到服務器列表並執行一些簡單的命令。如果服務器不可訪問,則將stderr寫入文件。然後,我將該文件作爲服務器名稱的grep。它看起來相對簡單,並且由於某種原因它不起作用。出於故障排除的目的,我已將服務器列表縮小到兩臺服務器,並且只運行簡單的命令。在bash中的grep語句

for i in $(cat serverlist) 
do 
    nexec -i $i hostname 2>>errorlog.txt 
    if grep -q $i errorlog.txt; then echo "error accessing" $i 
    else echo "was able to connect to" $i 
    fi 
done 

所以在服務器列表我已經定義爲了排除故障,兩個不正確的主機。 Nexec嘗試連接每個並執行hostname命令。如果是無法連接的錯誤消息被打印到ERRORLOG.TXT

例如, nexec:錯誤訪問主機TEST1

由於兩個服務器都錯誤地指定我不能夠連接到任何。再次用於故障排除目的

當grep的第一次運行時對$我這是在它doen't找到error.txt任何匹配列表中的第一個服務器。但是,它應該。如果我捕捉結果而不是狡猾,它就在那裏。

我其實在BladeLogic公司這樣做,這樣的規則是有點不同。它應該仍然有效。

+0

是否在列表中的第二個服務器的工作? – Barmar

+0

順便說一句,想想如果你有server101然後server1會發生什麼情況:即使server1失敗並且只有server101成功,grep server1也會成功。 –

+0

順便說一句,你需要閱讀nexec的stderr嗎?你確定**它不能正確表示在退出狀態中是否發生錯誤? –

回答

0

不熟悉nexec,但我想這樣的事情是你在找什麼

for i in $(cat serverlist) 
do 
    if [ ! "$(nexec -i $i hostname)" ] 
     then echo "error accessing" $i 
     else echo "was able to connect to" $i 
    fi 
done 
+0

由於他以追加模式重定向到'errorlog.txt',我想他想要永久記錄該文件中的所有錯誤。順便說一下,對於$(貓富)中的x而言, – Barmar

+1

是可怕的做法。請參閱http://mywiki.wooledge.org/BashPitfalls(其中包含條目#1)和http://mywiki.wooledge.org/BashFAQ/001以獲得更好的實踐。 –

+1

另外,報價的擴展:'nexec -i「$ I」' –

1
while read -r i <&3; do 
    nexec -i "$i" hostname 2>>"errorlog.$i.txt" || { 
     echo "nexec for $i exited with status $?" >&2 
     continue 
    } 
    # check for case where it claimed success but actually failed 
    # if nexec is written correctly, you don't need any of this logic 
    # ...and can completely remove the rest of the loop. 
    if grep -q -e "$i" "errorlog.$i.txt"; then 
     echo "error accessing $i" >&2 
    else 
     echo "was able to connect to $i" >&2 
    fi 
done 3<serverlist 

# and combine all the individual logs into one file: 
cat errorlog.*.txt >errorlog.txt && rm -f -- errorlog.*.txt