2015-01-13 369 views
3

我在這裏有一個方便的腳本,可以返回將在7天內過期或已過期的帳戶。我想讓它在多臺主機上運行,​​而無需將腳本放在每臺主機上,我添加了for loopssh $SERVER >> EOF部件,但它只是在運行腳本的系統上運行命令。

我相信錯誤是ssh $SERVER >> EOF但我不確定,因爲語法看起來正確。

#!/bin/bash 

for SERVER in `cat /lists/testlist` 
do 
    echo $SERVER 

    ssh $SERVER >> EOF 
    sudo cat /etc/shadow | cut -d: -f1,8 | sed /:$/d > /tmp/expirelist.txt 
    totalaccounts=`sudo cat /tmp/expirelist.txt | wc -l` 
    for((i=1; i<=$totalaccounts; i++)) 
    do 
     tuserval=`sudo head -n $i /tmp/expirelist.txt | tail -n 1` 
     username=`sudo echo $tuserval | cut -f1 -d:` 
     userexp=`sudo echo $tuserval | cut -f2 -d:` 
     userexpireinseconds=$(($userexp * 86400)) 
     todaystime=`date +"%s"` 
     if [[ $userexpireinseconds -ge $todaystime ]] ; 
     then 
     timeto7days=$(($todaystime + 604800)) 
     if [[ $userexpireinseconds -le $timeto7days ]]; 
     then 
      echo $username "is going to expire in 7 Days" 
     fi 
     else 
     echo $username "account has expired" 
     fi 
    done 
    sudo rm /tmp/expirelist.txt 
    EOF 
done 

回答

7

這裏的文件是由<< EOF啓動(或更好,<< 'EOF'以防止這裏的身體文稿正在由(本地)外殼擴展)和結束標記必須在第1列

你在做什麼是運行ssh並將標準輸出附加到文件EOF(>>是輸出重定向; <<是輸入重定向)。然後(本地)運行sudo等。它可能無法執行本地文件EOF(不可執行,希望),並且可能找不到任何其他命令。

我想你經過是這樣(其中我現在換成腳本背蜱與$(...)符號,並略微優化服務器列表生成與巴什使用):

#!/bin/bash 

for SERVER in $(</lists/testlist) 
do 
    echo $SERVER 

    ssh $SERVER << 'EOF' 
    sudo cat /etc/shadow | cut -d: -f1,8 | sed '/:$/d' > /tmp/expirelist.txt 
    totalaccounts=$(sudo cat /tmp/expirelist.txt | wc -l) 
    for ((i=1; i<=$totalaccounts; i++)) 
    do 
     tuserval=$(sudo head -n $i /tmp/expirelist.txt | tail -n 1) 
     username=$(sudo echo $tuserval | cut -f1 -d:) 
     userexp=$(sudo echo $tuserval | cut -f2 -d:) 
     userexpireinseconds=$(($userexp * 86400)) 
     todaystime=$(date +"%s") 
     if [[ $userexpireinseconds -ge $todaystime ]] 
     then 
     timeto7days=$(($todaystime + 604800)) 
     if [[ $userexpireinseconds -le $timeto7days ]] 
     then 
      echo $username "is going to expire in 7 Days" 
     fi 
     else 
     echo $username "account has expired" 
     fi 
    done 
    sudo rm /tmp/expirelist.txt 
EOF 
done 

非常接近,但差異真的很重要!特別要注意的是,結束標記EOF位於第1列中,並且根本沒有縮進。

+0

我已經做出了你提到的小改動,但行爲是一樣的。另外我注意到,對於測試列表中的每個服務器,它都會給出以下錯誤。 'line 7:EOF:Permission denied' 'line 29:EOF:command not found' – SpruceTips

+0

'EOF:command not found'消息意味着你做錯了什麼。最有可能的是,您縮進了EOF,而我明確指出EOF不能縮進('結束標記必須位於第1列'中)。也就是說,你應該得到關於「這裏的文檔不完整」等錯誤,所以我不確定你真正嘗試了什麼。 –

+0

發現它,我使用'>>'而不是'<<'。所有工作現在,謝謝! – SpruceTips