使用代理从URL批量下载文件

时间:2017-04-06 14:46:52

标签: windows batch-file download scripting

我必须从Web上下载xls文件并每天早上保存到本地文件夹中。 我想创建一个CMD文件,然后使用Windows调度程序。

该文件始终具有相同的网址,例如 www.example.com/myfile.xls

我找到了一些教程并剪下了有关它的代码,但我的问题是我需要使用代理服务器(“proxy.mycompany.com”和端口“1234”)。< / p>

是否可以使用CMD文件执行此操作,或者我需要转移到其他一些解决方案(VB.net,...)?

1 个答案:

答案 0 :(得分:1)

我建议使用嵌入在.cmd中的JScript

@set @tmpvar=1 /*
@echo off

echo Downloading...
call :download "http://download.qt.io/official_releases/jom/jom.zip" || echo Failed

echo Downloading using proxy...
call :download "http://download.qt.io/official_releases/jom/jom_1_1_1.zip" "206.128.191.77:8008" || echo Failed

goto :EOF

rem  Function :download
rem    %1 - URL
rem    %2 - [Proxy]
rem    %3 - [file name]
:download
cscript /nologo /e:jscript "%~f0" %*
exit /b %ERRORLEVEL%

*/

function getFileName(uri) {
    var re = /\/([^?/]+)(?:\?.+)?$/;
    var match = re.exec(uri);
    return match != null ? match[1] : "output";
}

try {

    var Source = WScript.Arguments.Item(0);
    var Proxy  = WScript.Arguments.Length > 1 ? WScript.Arguments.Item(1) : "";
    var Target = WScript.Arguments.Length > 2 ? WScript.Arguments.Item(2) : getFileName(Source);

    var Object = WScript.CreateObject('MSXML2.ServerXMLHTTP');
    if (Proxy.length > 0) {
        Object.setProxy(2/*SXH_PROXY_SET_PROXY*/, Proxy, "");
    }
    Object.open('GET', Source, false);
    Object.send();
    if (Object.status != 200) {
        WScript.Echo('Error:' + Object.status);
        WScript.Echo(Object.statusText);
        WScript.Quit(1);
    }

    var File = WScript.CreateObject('Scripting.FileSystemObject');
    if (File.FileExists(Target)) {
        File.DeleteFile(Target);
    }

    var Stream = WScript.CreateObject('ADODB.Stream');
    Stream.Open();
    Stream.Type = 1/*adTypeBinary*/;
    Stream.Write(Object.responseBody);
    Stream.Position = 0;
    Stream.SaveToFile(Target, 2/*adSaveCreateOverWrite*/);
    Stream.Close();

} catch (e) {
    WScript.Echo("--------------------");
    WScript.Echo("Error " + (e.number & 0xFFFF) + "\r\n  " + e.description.replace(/[\r\n]*$/, "\r\n"));
    for (var i = 0; i < WScript.Arguments.length; ++i) {
        WScript.Echo("  arg" + (i+1) + ": " + WScript.Arguments(i));
    }
    WScript.Echo("--------------------");
    WScript.Quit(1);
}