web-dev-qa-db-fra.com

Téléchargement de fichiers batch Windows à partir d'une URL

J'essaie de télécharger un fichier depuis un site Web (par exemple, http://www.example.com/package.Zip ) à l'aide d'un fichier de commandes Windows. Je reçois un code d'erreur lorsque j'écris la fonction ci-dessous:

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

Le fichier de commandes ne semble pas aimer le "/" après le http. Existe-t-il un moyen d'échapper à ces caractères afin d'éviter de supposer qu'il s'agit de paramètres de fonction?

98
James

Avec PowerShell 2.0 (Windows 7 préinstallé), vous pouvez utiliser:

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

À partir de PowerShell 3.0 (Windows 8 préinstallé), vous pouvez utiliser Invoke-WebRequest :

_Invoke-WebRequest http://www.example.com/package.Zip -OutFile package.Zip
_

A partir d'un fichier batch, ils s'appellent:

_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 est disponible pour l'installation sur XP, 3.0 pour Windows 7)

114
sevenforce

Il existe un composant Windows standard qui peut réaliser ce que vous essayez de faire: BITS . Il est inclus dans Windows depuis XP et 2000 SP3.

Courir:

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

Le nom du travail est simplement le nom d'affichage du travail de téléchargement. Définissez-le comme décrit.

89
brainwood

Cela peut être un peu hors sujet, mais vous pouvez assez facilement télécharger un fichier en utilisant Powershell . Powershell est livré avec les versions modernes de Windows, vous n’aurez donc pas à installer de matériel supplémentaire sur votre ordinateur. J'ai appris à le faire en lisant cette page:

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

Le code était:

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

La dernière fois que j'ai vérifié, il n'y a pas de commande en ligne de commande permettant de se connecter à une URL à partir de la ligne de commande MS. Essayez wget pour Windows:
http://gnuwin32.sourceforge.net/packages/wget.htm

ou URL2File:
http://www.chami.com/free/url2file_wincon.html

Sous Linux, vous pouvez utiliser "wget".

Sinon, vous pouvez essayer VBScript. Ils ressemblent à des programmes en ligne de commande, mais ce sont des scripts interprétés par l'hôte de scripts wscript.exe. Voici un exemple de téléchargement d'un fichier à l'aide de VBS:
https://serverfault.com/questions/29707/download-file-from-vbscript

25
LostInTheCode

Téléchargement de fichiers dans PURE BATCH ...

Sans JScript, VBScript, Powershell, etc ... Uniquement Batch pur!

Certaines personnes disent qu'il n'est pas possible de télécharger des fichiers avec un script batch sans utiliser JScript ou VBScript, etc ... Mais ils ont définitivement tort!

Voici une méthode simple qui semble fonctionner assez bien pour télécharger des fichiers dans vos scripts batch. Il devrait fonctionner sur presque toutes les URL de fichiers. Il est même possible d'utiliser un serveur proxy si vous en avez besoin.

Pour télécharger des fichiers, nous pouvons utiliser BITSADMIN.EXE à partir du système Windows. Il n’est pas nécessaire de télécharger/installer quoi que ce soit, d’utiliser JScript, VBScript, etc. Bitsadmin.exe est présent sur la plupart des versions de Windows, probablement à partir de XP vers Windows 10.

Prendre plaisir!


UTILISATION:

Vous pouvez utiliser directement la commande BITSADMIN, comme ceci:
bitsadmin /transfer mydownloadjob /download /priority normal "http://example.com/File.Zip" "C:\Downloads\File.Zip"

Serveur proxy:
Pour vous connecter à l'aide d'un proxy, utilisez cette commande avant le téléchargement.
bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080" "<local>"

Cliquez sur ce LINK si vous souhaitez plus d'informations sur BITSadmin.exe


FONCTIONS PERSONNALISÉES
:DOWNLOAD_FILE "URL"
:DOWNLOAD_PROXY_ON "SERVER:PORT"
:DOWNLOAD_PROXY_OFF

J'ai créé ces 3 fonctions pour simplifier les commandes bitsadmin. C'est plus facile à utiliser et à retenir. Cela peut être particulièrement utile si vous l'utilisez plusieurs fois dans vos scripts.

NOTEZ S'IL VOUS PLAÎT...
Avant d’utiliser ces fonctions, vous devez d’abord les copier de CUSTOM_FUNCTIONS.CMD à la fin de votre script. Il y a aussi un exemple complet: DOWNLOAD-EXAMPLE.CMD

: DOWNLOAD_FILE "URL"
La fonction principale téléchargera les fichiers depuis l’URL.

: DOWNLOAD_PROXY_ON "SERVEUR: PORT"
(Facultatif) Vous pouvez utiliser cette fonction si vous devez utiliser un serveur proxy.
L'appel de la fonction: DOWNLOAD_PROXY_OFF le désactivera.

EXEMPLE:
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
12
Frank Einstein
' 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

ensuite

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

ou double-cliquez dessus pour tester dans Windows

11
Kalpesh Soni

Autant que je sache, Windows ne dispose pas d’outil de ligne de commande intégré pour télécharger un fichier. Mais vous pouvez le faire à partir d'un script VBScript et générer le fichier VBScript à partir de batch en utilisant la redirection d'écho et de sortie:

@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

Plus d'explication ici

5
Abscissa
  1. Téléchargez Wget à partir d'ici http://downloads.sourceforge.net/gnuwin32/wget-1.11.4-1-setup.exe

  2. Puis installez-le.

  3. Puis créez un fichier .bat et mettez-le dedans

    @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. Ajustez l'URL et le chemin du fichier dans le script

  5. Exécutez le fichier et profitez!
4
boksiora

Vous ne pouvez pas utiliser xcopy sur http. Essayez de télécharger wget pour Windows. Cela peut faire l'affaire. Il s'agit d'un utilitaire de ligne de commande pour le téléchargement non interactif de fichiers via http. Vous pouvez l'obtenir à http://gnuwin32.sourceforge.net/packages/wget.htm

3
Matt Wrock

Si bitsadmin n'est pas votre tasse de thé, vous pouvez utiliser cette commande PowerShell:

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

Utilisez Bat To Exe Converter

Créez un fichier de commandes et mettez-y quelque chose comme le code ci-dessous

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

ou

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

et le convertir en exe.

3
kentuckyschreit

Au lieu de wget, vous pouvez également utiliser aria2 pour télécharger le fichier à partir d'une URL particulière.

Voir le lien suivant pour en savoir plus sur aria2:

https://aria2.github.io/

2
Sasikumar

Cela devrait fonctionner, j'ai fait ce qui suit pour un projet de serveur de jeu. Il va télécharger le fichier Zip et l'extraire dans le répertoire que vous spécifiez.

Enregistrer sous name.bat ou 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

2
C0nw0nk

BATCH n'est peut-être pas en mesure de le faire, mais vous pouvez utiliser JScript ou VBScript si vous ne souhaitez pas utiliser d'outils qui ne sont pas installés par défaut avec Windows.

Le premier exemple de cette page télécharge un fichier binaire dans VBScript: http://www.robvanderwoude.com/vbstech_internet_download.php

Cette SO réponse télécharge un fichier à l'aide de JScript (IMO, le meilleur langage): Windows Script Host (jScript): comment puis-je télécharger un fichier binaire?

Votre script batch peut alors simplement appeler un JScript ou un VBScript qui télécharge le fichier.

2
aikeru

Cette question a une très bonne réponse dans ici . Mon code est purement basé sur cette réponse avec quelques modifications.

Enregistrez le fragment ci-dessous sous le nom wget.bat et placez-le dans votre chemin système (par exemple, placez-le dans un répertoire et ajoutez ce répertoire au chemin système.)

Vous pouvez l'utiliser dans votre cli comme suit:

wget url/to/file [?custom_name]

url_to_file est obligatoire et custom_name est facultatif

  1. Si le nom n'est pas fourni, le fichier téléchargé sera sauvegardé sous son propre nom à partir de l'URL.
  2. Si le nom est fourni, le fichier sera enregistré sous le nouveau nom.

L'URL du fichier et les noms de fichiers enregistrés sont affichés en texte coloré en ans. Si cela vous pose problème, vérifiez 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. Ce code nécessite l'installation de PowerShell.

1
bantya

Vous pouvez configurer une tâche planifiée à l'aide de wget, utilisez le champ "Exécuter" dans la tâche planifiée comme suit:

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

J'ai trouvé ce script VB:

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

Fonctionne comme un charme. Configuré en tant que fonction avec un appel de fonction très simple:

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

Originaire de: http://www.ericphelps.com/scripting/samples/BinaryDownload/index.htm

Voici le code complet pour la redondance:

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
1
Beachhouse