developer tip

URL에서 Windows 배치 파일 다운로드

optionbox 2020. 8. 21. 07:34
반응형

URL에서 Windows 배치 파일 다운로드


Windows 배치 파일을 사용하여 웹 사이트 (예 : http://www.example.com/package.zip ) 에서 파일을 다운로드하려고 합니다. 아래 함수를 작성할 때 오류 코드가 나타납니다.

xcopy /E /Y "http://www.example.com/package.zip"

배치 파일은 http 다음에 "/"를 좋아하지 않는 것 같습니다. 해당 문자를 이스케이프하여 함수 매개 변수라고 가정하지 않는 방법이 있습니까?


PowerShell 2.0 (Windows 7 사전 설치)을 사용하면 다음을 사용할 수 있습니다.

(New-Object Net.WebClient).DownloadFile('http://www.example.com/package.zip', 'package.zip')

PowerShell 3.0 (Windows 8 사전 설치)부터 다음을 사용할 수 있습니다 Invoke-WebRequest.

Invoke-WebRequest http://www.example.com/package.zip -OutFile package.zip

배치 파일에서 다음과 같이 호출됩니다.

powershell -Command "(New-Object Net.WebClient).DownloadFile('http://www.example.com/package.zip', 'package.zip')"
powershell -Command "Invoke-WebRequest http://www.example.com/package.zip -OutFile package.zip"

(PowerShell 2.0은 XP, 3.0은 Windows 7에 설치 가능)


수행하려는 작업을 수행 할 수있는 표준 Windows 구성 요소가 있습니다. BITS . XP 및 2000 SP3부터 Windows에 포함되었습니다.

운영:

bitsadmin.exe /transfer "JobName" http://download.url/here.exe C:\destination\here.exe

작업 이름은 다운로드 작업의 표시 이름입니다. 수행중인 작업을 설명하는 이름으로 설정하십시오.


이것은 약간의 주제가 아닐 수 있지만 Powershell을 사용하여 파일을 매우 쉽게 다운로드 할 수 있습니다 . Powershell은 최신 버전의 Windows와 함께 제공되므로 컴퓨터에 추가 항목을 설치할 필요가 없습니다. 이 페이지를 읽고 방법을 배웠습니다.

http://teusje.wordpress.com/2011/02/19/download-file-with-powershell/

코드는 다음과 같습니다.

$webclient = New-Object System.Net.WebClient
$url = "http://www.example.com/file.txt"
$file = "$pwd\file.txt"
$webclient.DownloadFile($url,$file)

마지막으로 확인한 결과 MS 명령 줄에서 URL에 연결하는 명령 줄 명령이 없습니다. Windows 용 wget 사용해보기 :
http://gnuwin32.sourceforge.net/packages/wget.htm

또는 URL2File :
http://www.chami.com/free/url2file_wincon.html

Linux에서는 "wget"을 사용할 수 있습니다.

또는 VBScript를 사용해 볼 수 있습니다. 명령 줄 프로그램과 비슷하지만 wscript.exe 스크립트 호스트에서 해석하는 스크립트입니다. 다음은 VBS를 사용하여 파일을 다운로드하는 예입니다.
https://serverfault.com/questions/29707/download-file-from-vbscript


PURE BATCH에서 파일 다운로드 중 ...

JScript, VBScript, Powershell 등이 없습니다. 순수한 배치 만 가능합니다!

어떤 사람들은 JScript 나 VBScript 등을 사용하지 않고는 배치 스크립트로 파일을 다운로드 할 수 없다고 말하고 있습니다. 그러나 그들은 확실히 틀 렸습니다!

다음은 배치 스크립트에서 파일을 다운로드하는 데 매우 잘 작동하는 간단한 방법입니다. 거의 모든 파일의 URL에서 작동합니다. 필요한 경우 프록시 서버를 사용할 수도 있습니다.

파일 다운로드 를 위해 Windows 시스템에서 BITSADMIN.EXE사용할 수 있습니다 . 아무것도 다운로드 / 설치하거나 JScript 또는 VBScript 등을 사용할 필요가 없습니다. Bitsadmin.exe 는 XP에서 Windows 10까지 대부분의 Windows 버전에 있습니다.

즐겨!


용법:

다음과 같이 BITSADMIN 명령을 직접 사용할 수 있습니다.
bitsadmin /transfer mydownloadjob /download /priority normal "http://example.com/File.zip" "C:\Downloads\File.zip"

프록시 서버 :
프록시를 사용하여 연결하려면 다운로드하기 전에이 명령을 사용하십시오.
bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080" "<local>"

BITSadmin.exe에 대한 자세한 정보를 보려면이 링크를 클릭하십시오.


사용자 정의 기능
:DOWNLOAD_FILE "URL"
:DOWNLOAD_PROXY_ON "SERVER:PORT"
:DOWNLOAD_PROXY_OFF

bitsadmin 명령을 단순화하기 위해이 세 가지 기능을 만들었습니다. 사용하고 기억하기가 더 쉽습니다. 스크립트에서 여러 번 사용하는 경우 특히 유용 할 수 있습니다.

참고 사항 ...
이 함수를 사용하기 전에 먼저 CUSTOM_FUNCTIONS.CMD에서 스크립트의 끝으로 복사해야합니다. 완전한 예도 있습니다 : DOWNLOAD-EXAMPLE.CMD

: DOWNLOAD_FILE "URL"
주요 기능은 URL에서 파일을 다운로드합니다.

: DOWNLOAD_PROXY_ON "SERVER : PORT"
(선택 사항) 프록시 서버를 사용해야하는 경우이 기능을 사용할 수 있습니다.
: DOWNLOAD_PROXY_OFF 함수를 호출하면 비활성화됩니다.

예:
CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"
CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:\Downloads\File.zip"
CALL :DOWNLOAD_PROXY_OFF


CUSTOM_FUNCTIONS.CMD

:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority normal %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1 "<local>"
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

DOWNLOAD-EXAMPLE.CMD

@ECHO OFF
SETLOCAL

rem FOR DOWNLOADING, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.


:SETUP

rem DOWNLOADING A PICTURE (URL):
SET "FILE_URL=https://upload.wikimedia.org/wikipedia/en/8/86/Einstein_tongue.jpg"

rem SAVING FILE TO THE SCRIPT FOLDER:
SET "SAVING_TO=Einstein_tongue.jpg"
SET "SAVING_TO=%~dp0%SAVING_TO%"

rem OR, UNCOMMENT NEXT LINE FOR SAVING TO ANY OTHER PATH:
rem SET "SAVING_TO=C:\Folder\Einstein_tongue.jpg"


:MAIN

ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO:  "%SAVING_TO%"
ECHO.

rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"

rem HERE IS THE MAIN DOWNLOADING COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"

rem UNCOMMENT NEXT LINE FOR DISABLING ANY PROXY:
rem CALL :DOWNLOAD_PROXY_OFF

ECHO.

rem THIS IS THE END...
PAUSE
EXIT /B




rem FUNCTIONS SECTION


:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority normal %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1 "<local>"
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

' Create an HTTP object
myURL = "http://www.google.com"
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )

' Download the specified URL
objHTTP.Open "GET", myURL, False
objHTTP.Send
intStatus = objHTTP.Status

If intStatus = 200 Then
  WScript.Echo " " & intStatus & " A OK " +myURL
Else
  WScript.Echo "OOPS" +myURL
End If

그때

C:\>cscript geturl.vbs
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.

200 A OK http://www.google.com

또는 창에서 테스트하려면 두 번 클릭하십시오.


AFAIK, Windows에는 파일을 다운로드하는 기본 제공 명령 줄 도구가 없습니다. 그러나 VBScript에서 수행 할 수 있으며 에코 및 출력 리디렉션을 사용하여 배치에서 VBScript 파일을 생성 할 수 있습니다.

@echo off

rem Windows has no built-in wget or curl, so generate a VBS script to do it:
rem -------------------------------------------------------------------------
set DLOAD_SCRIPT=download.vbs
echo Option Explicit                                                    >  %DLOAD_SCRIPT%
echo Dim args, http, fileSystem, adoStream, url, target, status         >> %DLOAD_SCRIPT%
echo.                                                                   >> %DLOAD_SCRIPT%
echo Set args = Wscript.Arguments                                       >> %DLOAD_SCRIPT%
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1")              >> %DLOAD_SCRIPT%
echo url = args(0)                                                      >> %DLOAD_SCRIPT%
echo target = args(1)                                                   >> %DLOAD_SCRIPT%
echo WScript.Echo "Getting '" ^& target ^& "' from '" ^& url ^& "'..."  >> %DLOAD_SCRIPT%
echo.                                                                   >> %DLOAD_SCRIPT%
echo http.Open "GET", url, False                                        >> %DLOAD_SCRIPT%
echo http.Send                                                          >> %DLOAD_SCRIPT%
echo status = http.Status                                               >> %DLOAD_SCRIPT%
echo.                                                                   >> %DLOAD_SCRIPT%
echo If status ^<^> 200 Then                                            >> %DLOAD_SCRIPT%
echo    WScript.Echo "FAILED to download: HTTP Status " ^& status       >> %DLOAD_SCRIPT%
echo    WScript.Quit 1                                                  >> %DLOAD_SCRIPT%
echo End If                                                             >> %DLOAD_SCRIPT%
echo.                                                                   >> %DLOAD_SCRIPT%
echo Set adoStream = CreateObject("ADODB.Stream")                       >> %DLOAD_SCRIPT%
echo adoStream.Open                                                     >> %DLOAD_SCRIPT%
echo adoStream.Type = 1                                                 >> %DLOAD_SCRIPT%
echo adoStream.Write http.ResponseBody                                  >> %DLOAD_SCRIPT%
echo adoStream.Position = 0                                             >> %DLOAD_SCRIPT%
echo.                                                                   >> %DLOAD_SCRIPT%
echo Set fileSystem = CreateObject("Scripting.FileSystemObject")        >> %DLOAD_SCRIPT%
echo If fileSystem.FileExists(target) Then fileSystem.DeleteFile target >> %DLOAD_SCRIPT%
echo adoStream.SaveToFile target                                        >> %DLOAD_SCRIPT%
echo adoStream.Close                                                    >> %DLOAD_SCRIPT%
echo.                                                                   >> %DLOAD_SCRIPT%
rem -------------------------------------------------------------------------

cscript //Nologo %DLOAD_SCRIPT% http://example.com targetPathAndFile.html

여기에 더 많은 설명


  1. Download Wget from here http://downloads.sourceforge.net/gnuwin32/wget-1.11.4-1-setup.exe

  2. Then install it.

  3. Then make some .bat file and put this into it

    @echo off
    
    for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set y=%%k
    for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set d=%%k%%i%%j
    for /F "tokens=5-8 delims=:. " %%i in ('echo.^| time ^| find "current" ') do set t=%%i%%j
    set t=%t%_
    if "%t:~3,1%"=="_" set t=0%t%
    set t=%t:~0,4%
    set "theFilename=%d%%t%"
    echo %theFilename%
    
    
    cd "C:\Program Files\GnuWin32\bin"
    wget.exe --output-document C:\backup\file_%theFilename%.zip http://someurl/file.zip
    
  4. Adjust the URL and the file path in the script

  5. Run the file and profit!

You cannot use xcopy over http. Try downloading wget for windows. That may do the trick. It is a command line utility for non-interactive download of files through http. You can get it at http://gnuwin32.sourceforge.net/packages/wget.htm


If bitsadmin isn't your cup of tea, you can use this PowerShell command:

Start-BitsTransfer -Source http://www.foo.com/package.zip -Destination C:\somedir\package.zip

Use Bat To Exe Converter

Create a batch file and put something like the code below into it

%extd% /download http://www.examplesite.com/file.zip file.zip

or

%extd% /download http://stackoverflow.com/questions/4619088/windows-batch-file-file-download-from-a-url thistopic.html

and convert it to exe.


BATCH may not be able to do this, but you can use JScript or VBScript if you don't want to use tools that are not installed by default with Windows.

The first example on this page downloads a binary file in VBScript: http://www.robvanderwoude.com/vbstech_internet_download.php

This SO answer downloads a file using JScript (IMO, the better language): Windows Script Host (jscript): how do i download a binary file?

Your batch script can then just call out to a JScript or VBScript that downloads the file.


This should work i did the following for a game server project. It will download the zip and extract it to what ever directory you specify.

Save as name.bat or name.cmd

@echo off
set downloadurl=http://media.steampowered.com/installer/steamcmd.zip
set downloadpath=C:\steamcmd\steamcmd.zip
set directory=C:\steamcmd\
%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& {Import-Module BitsTransfer;Start-BitsTransfer '%downloadurl%' '%downloadpath%';$shell = new-object -com shell.application;$zip = $shell.NameSpace('%downloadpath%');foreach($item in $zip.items()){$shell.Namespace('%directory%').copyhere($item);};remove-item '%downloadpath%';}"
echo download complete and extracted to the directory.
pause

Original : https://github.com/C0nw0nk/SteamCMD-AutoUpdate-Any-Gameserver/blob/master/steam.cmd


Instead of wget you can also use aria2 to download the file from a particular URL.

See the following link which will explain more about aria2:

https://aria2.github.io/


I found this VB script:

http://www.olafrv.com/?p=385

Works like a charm. Configured as a function with a very simple function call:

SaveWebBinary "http://server/file1.ext1", "C:/file2.ext2"

Originally from: http://www.ericphelps.com/scripting/samples/BinaryDownload/index.htm

Here is the full code for redundancy:

Function SaveWebBinary(strUrl, strFile) 'As Boolean
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
Const ForWriting = 2
Dim web, varByteArray, strData, strBuffer, lngCounter, ado
    On Error Resume Next
    'Download the file with any available object
    Err.Clear
    Set web = Nothing
    Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
    If web Is Nothing Then Set web = CreateObject("WinHttp.WinHttpRequest")
    If web Is Nothing Then Set web = CreateObject("MSXML2.ServerXMLHTTP")
    If web Is Nothing Then Set web = CreateObject("Microsoft.XMLHTTP")
    web.Open "GET", strURL, False
    web.Send
    If Err.Number <> 0 Then
        SaveWebBinary = False
        Set web = Nothing
        Exit Function
    End If
    If web.Status <> "200" Then
        SaveWebBinary = False
        Set web = Nothing
        Exit Function
    End If
    varByteArray = web.ResponseBody
    Set web = Nothing
    'Now save the file with any available method
    On Error Resume Next
    Set ado = Nothing
    Set ado = CreateObject("ADODB.Stream")
    If ado Is Nothing Then
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set ts = fs.OpenTextFile(strFile, ForWriting, True)
        strData = ""
        strBuffer = ""
        For lngCounter = 0 to UBound(varByteArray)
            ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1)))
        Next
        ts.Close
    Else
        ado.Type = adTypeBinary
        ado.Open
        ado.Write varByteArray
        ado.SaveToFile strFile, adSaveCreateOverWrite
        ado.Close
    End If
    SaveWebBinary = True
End Function

This question has very good answer in here. My code is purely based on that answer with some modifications.

Save below snippet as wget.bat and put it in your system path (e.g. Put it in a directory and add this directory to system path.)

You can use it in your cli as follows:

wget url/to/file [?custom_name]

where url_to_file is compulsory and custom_name is optional

  1. If name is not provided, then downloaded file will be saved by its own name from the url.
  2. If the name is supplied, then the file will be saved by the new name.

The file url and saved filenames are displayed in ansi colored text. If that is causing problem for you, then check this github project.

@echo OFF
setLocal EnableDelayedExpansion
set Url=%1
set Url=!Url:http://=!
set Url=!Url:/=,!
set Url=!Url:%%20=?!
set Url=!Url: =?!

call :LOOP !Url!

set FileName=%2
if "%2"=="" set FileName=!FN!

echo.
echo.Downloading: [1;33m%1[0m to [1;33m\!FileName![0m

powershell.exe -Command wget %1 -OutFile !FileName!

goto :EOF
:LOOP
if "%1"=="" goto :EOF
set FN=%1
set FN=!FN:?= !
shift
goto :LOOP

P.S. This code requires you to have PowerShell installed.


You can setup a scheduled task using wget, use the “Run” field in scheduled task as:

C:\wget\wget.exe -q -O nul "http://www.google.com/shedule.me"

use ftp:

(ftp *yourewebsite.com*-a)
cd *directory*
get *filename.doc*
close

Change everything in asterisks to fit your situation.

참고URL : https://stackoverflow.com/questions/4619088/windows-batch-file-file-download-from-a-url

반응형