2016-10-18 57 views
0

我試圖創建一個bash腳本來從某個網站下載文件。在bash腳本中記錄執行時間並在需要太長時間時終止當前命令

他們的下載鏈接是連續的 - 例如,它只是id = 1,id = 2,id = 3一直到660000.唯一的要求是你必須登錄,這使得這有點困難。哦,並且登錄將在幾個小時後隨機超時,因此我必須重新登錄。

這是我當前的腳本,它在99%的時間內運行良好。

#!/bin/sh 
cd downloads 

for i in `seq 1 660000` 
do 
lastname="" 
echo "Downloading file $i" 
echo "Downloading file $i" >> _downloadinglog.txt 

response=$(curl --write-out %{http_code} -b _cookies.txt -c _cookies.txt --silent --output /dev/null "[sample URL to make sure cookie is still logged in]") 

if ! [ $response -eq 200 ] 

then 
    echo "Cookie didn't work, trying to re-log in..." 
    curl -d "userid=[USERNAME]" -d "pwd=[PASSWORD]" -b _cookies.txt -c _cookies.txt --silent --output /dev/null "[login URL]" 
    response=$(curl --write-out %{http_code} -b _cookies.txt -c _cookies.txt --silent --output /dev/null "[sample URL again]") 
    if ! [ $response -eq 200 ] 
    then 
    echo "Something weird happened?? Response code $response. Logging in didn't fix issue, fix then resume from $(($i - 1))" 
    echo "Something weird happened?? Response code $response. Logging in didn't fix issue, fix then resume from $(($i - 1))" >> _downloadinglog.txt 
    exit 0 
    fi 
    echo "Downloading file $(($i - 1)) again incase cookie expiring caused it to fail" 
    echo "Downloading file $(($i - 1)) again incase cookie expiring caused it to fail" >> _downloadinglog.txt 
    lastname=$(curl --write-out %{filename_effective} -O -J -b _cookies.txt -c _cookies.txt "[URL to download files]?id=$(($i - 1))") 
    echo "id $(($i - 1)) = $lastname" >> _downloadinglog.txt 
    lastname="" 
    echo "Downloading file $i" 
    echo "Downloading file $i" >> _downloadinglog.txt 
fi 
lastname=$(curl --write-out %{filename_effective} -O -J -b _cookies.txt -c _cookies.txt "[URL to download files]?id=$i") 
echo "id $i = $lastname" >> _downloadinglog.txt 
done 

所以基本上我把它做的是試圖移動到下一個文件中的設置之前下載一個隨機文件。如果下載失敗,我們假設登錄cookie不再有效,並告訴curl重新登錄。

這很好,我可以從它得到幾千個文件。但是會發生什麼 - 無論是我的路由器停了一兩秒鐘,還是他們的網站都停了一兩分鐘,捲曲就會坐在那裏,認爲它會下載好幾個小時。我曾經回過頭來花費24小時在同一個文件上。它似乎沒有能力知道轉移是否在中間時間結束 - 只有當它不能開始轉移時。

我知道如果將它與「睡眠」結合起來,有些方法可以終止命令的執行,但是因爲這必須是「智能」並從停止的地方重新開始,所以我不能殺死整個腳本。

有什麼建議嗎?如果我可以使用它來通過終端命令登錄,我願意使用curl以外的內容。

+0

一個簡單的方法是設置相當於一個事件循環,並將命令產生爲子shell。在你的循環中,定期檢查任務是否完成,如果有必要的話,如果過了很多時間就終止它們。 –

+0

@DavidHoelzer你可能是指_background jobs_(在命令的末尾用控制運算符'&開始),而不是_subshel​​ls_。 – mklement0

+0

我不知道你可以用shell腳本來做到這一點,但是對於python和請求來說這是完全簡單的。 –

回答

0

您可以嘗試使用捲曲選項--connect-timeout--max-time--max-time應該是你的選擇。

從手冊:

--max時間

最大時間,你讓整個操作需要幾秒鐘。由於網絡速度較慢或鏈接斷開,這對於防止批量作業掛起數小時很有用。自7.32.0版本開始,此選項接受十進制值,但實際超時的準確度會降低,因爲指定的超時會以十進制精度增加。另請參閱--connect-timeout選項。

如果多次使用此選項,將使用最後一個。

然後在var中捕獲該命令的結果並根據結果進一步處理。