我正在尝试创建一个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个小时。它似乎没有能力知道转移是否在中间超时 - 只有它无法启动转移。
我知道有一些方法可以终止执行命令,如果你将它与“sleep”结合起来,但由于这必须是“智能”并从它停止的地方重新启动,我不能只是杀死整个脚本。
有什么建议吗?如果我可以使用它通过终端命令登录,我愿意使用curl以外的东西。
答案 0 :(得分:0)
您可以尝试使用curl选项--connect-timeout
或--max-time
。
--max-time
应该是你的选择。
来自手册:
- max-time
允许整个操作采用的最长时间(以秒为单位)。这有助于防止批处理作业因网络速度缓慢或链接断开而挂起数小时。从7.32.0开始,此选项接受十进制值,但实际超时的精度会降低,因为指定的超时会以十进制精度增加。另请参阅--connect-timeout选项。
如果多次使用此选项,将使用最后一个选项。
然后在var中捕获命令的结果,并根据结果进一步处理。