Как скачать файл через консоль windows

How can I download something from the web directly without Internet Explorer or Firefox opening Acrobat Reader/Quicktime/MS Word/whatever? I'm using Windows, so a Windows version of Wget wou...

If PowerShell is an option, that’s the preferred route, since you (potentially) won’t have to install anything extra:

(new-object System.Net.WebClient).DownloadFile('http://www.example.com/file.txt', 'C:tmpfile.txt')

Failing that, Wget for Windows, as others have pointed out is definitely the second best option. As posted in another answer it looks like you can download Wget all by itself, or you can grab it as a part of Cygwin or MSys.

If for some reason, you find yourself stuck in a time warp, using a machine that doesn’t have PowerShell and you have zero access to a working web browser (that is, Internet Explorer is the only browser on the system, and its settings are corrupt), and your file is on an FTP site (as opposed to HTTP):

start->run "FTP", press "OK".

If memory serves it’s been there since Windows 98, and I can confirm that it is still there in Windows 8 RTM (you might have to go into appwiz.cpl and add/remove features to get it). This utility can both download and upload files to/from FTP sites on the web. It can also be used in scripts to automate either operation.

This tool being built-in has been a real life saver for me in the past, especially in the days of ftp.cdrom.com — I downloaded Firefox that way once, on a completely broken machine that had only a dial-up Internet connection (back when sneakernet’s maximum packet size was still 1.44 MB, and Firefox was still called «Netscape» /me does trollface).

A couple of tips: it’s its own command processor, and it has its own syntax. Try typing «help». All FTP sites require a username and password; but if they allow «anonymous» users, the username is «anonymous» and the password is your email address (you can make one up if you don’t want to be tracked, but usually there is some kind of logic to make sure it’s a valid email address).

Without using any non-standard (Windows included) utilities, is it possible to download using the Windows command line?

The preferred version is Windows XP, but it’s also interesting to know for newer versions.

To further clarify my question:

  • It has to be using HTTP
  • The file needs to be saved
  • Standard clean Windows install, no extra tools

So basically, since everybody is screaming Wget, I want simple Wget functionality, without using Wget.

Peter Mortensen's user avatar

asked Oct 23, 2009 at 14:58

Robert Massa's user avatar

Robert MassaRobert Massa

1,6354 gold badges13 silver badges17 bronze badges

6

You can write a VBScript and run it from the command line

Create a file downloadfile.vbs and insert the following lines of code:

' Set your settings
    strFileURL = "http://www.it1.net/images/it1_logo2.jpg"
    strHDLocation = "c:logo.jpg"

' Fetch the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")

    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()

If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary

objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0    'Set the stream position to the start

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing

objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing

Run it from the command line as follows:

cscript.exe downloadfile.vbs 

phuclv's user avatar

phuclv

24.7k13 gold badges105 silver badges219 bronze badges

answered Oct 23, 2009 at 15:31

3

Starting with Windows 7, I believe there’s one single method that hasn’t been mentioned yet that’s easy:

Syntax:

bitsadmin  /transfer job_name       /download  /priority priority   URL  localpathfile

Example:

bitsadmin  /transfer mydownloadjob  /download  /priority normal  ^
                  http://example.com/filename.zip  C:UsersusernameDownloadsfilename.zip

(Broken into two separate lines with ^ for readability
(to avoid scrolling).)

Warning: As pointed out in the comments,
the bitsadmin help message starts by saying:

BITSAdmin is deprecated and is not guaranteed to be available in future versions of Windows.
Administrative tools for the BITS service are now provided by BITS PowerShell cmdlets.

… but another comment reported that it works on Windows 8.

G-Man Says 'Reinstate Monica''s user avatar

answered May 16, 2011 at 9:13

timeshift's user avatar

timeshifttimeshift

8696 silver badges3 bronze badges

14

PowerShell (included with Windows 8 and included with .NET for earlier releases) has this capability. The powershell command allows running arbitrary PowerShell commands from the command line or a .bat file. Thus, the following line is what’s wanted:

powershell -command "& { (New-Object Net.WebClient).DownloadFile('http://example.com/', 'c:somefile') }"

Peter Mortensen's user avatar

answered May 29, 2014 at 2:22

Nik's user avatar

NikNik

2693 silver badges2 bronze badges

4

I found a way of doing it, but really, just install Wget.

You can use Internet Explorer from a command line (iexplore.exe) and then enter a URL as an argument. So, run:

iexplore.exe http://blah.com/filename.zip

Whatever the file is, you’ll need to specify it doesn’t need confirmation ahead of time. Lo and behold, it will automatically perform the download. So yes, it is technically possible, but good lord do it in a different way.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:12

DHayes's user avatar

DHayesDHayes

2,17313 silver badges17 bronze badges

2

Windows Explorer (not to be confused with Internet Explorer) can download files via HTTP. Just enter the URL into the Address bar. Or from the command line, for example, C:windowsexplorer.exe http://somewhere.com/filename.ext.

You get the classic File Download prompt. Unless the file is a type that Windows Explorer knows how to display inline, (.html, .jpg, .gif), in which case you would then need to right-click to save it.

I just tested this on my VMware image of a virgin install of Windows XP 2002 SP1, and it works fine.

Peter Mortensen's user avatar

answered Aug 8, 2011 at 15:18

Chris Noe's user avatar

Chris NoeChris Noe

3972 gold badges5 silver badges16 bronze badges

3

You can use (in a standard Windows bat):

powershell -command "& { iwr http://www.it1.net/it1_logo2.jpg -OutFile logo.jpg }"

It seems to require PowerShell v4…

(Thanks to that comment and this one)

a_horse_with_no_name's user avatar

answered May 10, 2016 at 14:10

Anthony O.'s user avatar

Anthony O.Anthony O.

2601 gold badge6 silver badges8 bronze badges

Use FTP.

From the command line:

ftp ftp.somesite.com
user
password

etc. FTP is included in every Windows version I can remember; probably not in 3.1, maybe not in Windows 95, but certainly everything after that.

@RM: It is going to be rough if you don’t want to download any other tools. There exists a command line Wget for Windows and Wget is designed to do exactly what you’re asking for.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:01

Satanicpuppy's user avatar

SatanicpuppySatanicpuppy

6,7371 gold badge21 silver badges17 bronze badges

4

Use PowerShell like this:

  1. Create a download.ps1 file:

    param($url, $filename)
    $client = new-object System.Net.WebClient 
    $client.DownloadFile( $url, $filename)
    
  2. Now you can download a file like this:

    powershell Set-ExecutionPolicy Unrestricted
    powershell -ExecutionPolicy RemoteSigned -File "download.ps1" "http://somewhere.com/filename.ext" "d:filename.ext"
    

answered Apr 21, 2013 at 21:55

Thomas Jespersen's user avatar

1

On Win CMD (if you have write access):

set url=https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg
set file=file.jpg
certutil -urlcache -split -f %url% %file%
echo Done.

Built in Windows app. No need for external downloads.

Tested on Win 10

answered Apr 25, 2020 at 17:58

Zimba's user avatar

ZimbaZimba

96310 silver badges14 bronze badges

If you have python installed here’s an example which fetches the get-pip.py from the web

python -c "import urllib; urllib.urlretrieve ('https://bootstrap.pypa.io/get-pip.py', r'C:python27Toolsget-pip.py')"

gronostaj's user avatar

gronostaj

54.8k17 gold badges118 silver badges174 bronze badges

answered Aug 29, 2014 at 23:15

Sipherlab's user avatar

0

From Windows 10 build 17063 and later, ‘Curl’ is now included, so that you can execute it directly from Cmd.exe or PowerShell.exe.

For example:

C:>curl.exe -V
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: 2017-11-14, security patched: 2019-11-05
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL

To download a file:

curl.exe -O https://cdn.sstatic.net/Sites/superuser/Img/logo.svg

answered Sep 10, 2020 at 14:41

gsl's user avatar

gslgsl

2072 silver badges9 bronze badges

If you install Telnet, I imagine you could make a HTTP request to a server to download a file.

You can also install Cygwin, and use wget to download a file as well. This is a very easy way to download files from the command line.

answered Oct 23, 2009 at 15:01

EvilChookie's user avatar

EvilChookieEvilChookie

4,5691 gold badge24 silver badges34 bronze badges

10

There are a few ways that you can download using the command line in Windows:

  1. You can use Cygwin.

    Note: the included apps are not native Linux apps. You must rebuild your application from source if you want to run on Windows.

  2. Using telnet it’s possible to make a request but you won’t see any processing.

  3. You can write bat or VBS scripts.

  4. Write your own program that you can run from cmd.exe.

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered Aug 20, 2011 at 3:22

Jesus's user avatar

JesusJesus

111 bronze badge

You can install the Linux application Wget on Windows. It can be downloaded from http://gnuwin32.sourceforge.net/packages/wget.htm. You can then issue the command ‘wget (inserturlhere)’ or any other URL in your command prompt, and it will allow you to download that URL/file/image.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:06

1

In default Windows, you can’t download via HTTP. Windows is a GUI-centric OS, so it lacks many of the commandline tools you’d find in other OS’s, like wget, which would be the prime candidate.

System.Net.WebClient.DownloadFile(), a function in the WiniNet API, can download files, but I’m not sure how far you’re getting into actual development vs. a batch file.

answered Oct 23, 2009 at 15:04

Andrew Scagnelli's user avatar

1

Without using any non-standard (Windows included) utilities, is it possible to download using the Windows command line?

The preferred version is Windows XP, but it’s also interesting to know for newer versions.

To further clarify my question:

  • It has to be using HTTP
  • The file needs to be saved
  • Standard clean Windows install, no extra tools

So basically, since everybody is screaming Wget, I want simple Wget functionality, without using Wget.

Peter Mortensen's user avatar

asked Oct 23, 2009 at 14:58

Robert Massa's user avatar

Robert MassaRobert Massa

1,6354 gold badges13 silver badges17 bronze badges

6

You can write a VBScript and run it from the command line

Create a file downloadfile.vbs and insert the following lines of code:

' Set your settings
    strFileURL = "http://www.it1.net/images/it1_logo2.jpg"
    strHDLocation = "c:logo.jpg"

' Fetch the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")

    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()

If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary

objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0    'Set the stream position to the start

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing

objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing

Run it from the command line as follows:

cscript.exe downloadfile.vbs 

phuclv's user avatar

phuclv

24.7k13 gold badges105 silver badges219 bronze badges

answered Oct 23, 2009 at 15:31

3

Starting with Windows 7, I believe there’s one single method that hasn’t been mentioned yet that’s easy:

Syntax:

bitsadmin  /transfer job_name       /download  /priority priority   URL  localpathfile

Example:

bitsadmin  /transfer mydownloadjob  /download  /priority normal  ^
                  http://example.com/filename.zip  C:UsersusernameDownloadsfilename.zip

(Broken into two separate lines with ^ for readability
(to avoid scrolling).)

Warning: As pointed out in the comments,
the bitsadmin help message starts by saying:

BITSAdmin is deprecated and is not guaranteed to be available in future versions of Windows.
Administrative tools for the BITS service are now provided by BITS PowerShell cmdlets.

… but another comment reported that it works on Windows 8.

G-Man Says 'Reinstate Monica''s user avatar

answered May 16, 2011 at 9:13

timeshift's user avatar

timeshifttimeshift

8696 silver badges3 bronze badges

14

PowerShell (included with Windows 8 and included with .NET for earlier releases) has this capability. The powershell command allows running arbitrary PowerShell commands from the command line or a .bat file. Thus, the following line is what’s wanted:

powershell -command "& { (New-Object Net.WebClient).DownloadFile('http://example.com/', 'c:somefile') }"

Peter Mortensen's user avatar

answered May 29, 2014 at 2:22

Nik's user avatar

NikNik

2693 silver badges2 bronze badges

4

I found a way of doing it, but really, just install Wget.

You can use Internet Explorer from a command line (iexplore.exe) and then enter a URL as an argument. So, run:

iexplore.exe http://blah.com/filename.zip

Whatever the file is, you’ll need to specify it doesn’t need confirmation ahead of time. Lo and behold, it will automatically perform the download. So yes, it is technically possible, but good lord do it in a different way.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:12

DHayes's user avatar

DHayesDHayes

2,17313 silver badges17 bronze badges

2

Windows Explorer (not to be confused with Internet Explorer) can download files via HTTP. Just enter the URL into the Address bar. Or from the command line, for example, C:windowsexplorer.exe http://somewhere.com/filename.ext.

You get the classic File Download prompt. Unless the file is a type that Windows Explorer knows how to display inline, (.html, .jpg, .gif), in which case you would then need to right-click to save it.

I just tested this on my VMware image of a virgin install of Windows XP 2002 SP1, and it works fine.

Peter Mortensen's user avatar

answered Aug 8, 2011 at 15:18

Chris Noe's user avatar

Chris NoeChris Noe

3972 gold badges5 silver badges16 bronze badges

3

You can use (in a standard Windows bat):

powershell -command "& { iwr http://www.it1.net/it1_logo2.jpg -OutFile logo.jpg }"

It seems to require PowerShell v4…

(Thanks to that comment and this one)

a_horse_with_no_name's user avatar

answered May 10, 2016 at 14:10

Anthony O.'s user avatar

Anthony O.Anthony O.

2601 gold badge6 silver badges8 bronze badges

Use FTP.

From the command line:

ftp ftp.somesite.com
user
password

etc. FTP is included in every Windows version I can remember; probably not in 3.1, maybe not in Windows 95, but certainly everything after that.

@RM: It is going to be rough if you don’t want to download any other tools. There exists a command line Wget for Windows and Wget is designed to do exactly what you’re asking for.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:01

Satanicpuppy's user avatar

SatanicpuppySatanicpuppy

6,7371 gold badge21 silver badges17 bronze badges

4

Use PowerShell like this:

  1. Create a download.ps1 file:

    param($url, $filename)
    $client = new-object System.Net.WebClient 
    $client.DownloadFile( $url, $filename)
    
  2. Now you can download a file like this:

    powershell Set-ExecutionPolicy Unrestricted
    powershell -ExecutionPolicy RemoteSigned -File "download.ps1" "http://somewhere.com/filename.ext" "d:filename.ext"
    

answered Apr 21, 2013 at 21:55

Thomas Jespersen's user avatar

1

On Win CMD (if you have write access):

set url=https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg
set file=file.jpg
certutil -urlcache -split -f %url% %file%
echo Done.

Built in Windows app. No need for external downloads.

Tested on Win 10

answered Apr 25, 2020 at 17:58

Zimba's user avatar

ZimbaZimba

96310 silver badges14 bronze badges

If you have python installed here’s an example which fetches the get-pip.py from the web

python -c "import urllib; urllib.urlretrieve ('https://bootstrap.pypa.io/get-pip.py', r'C:python27Toolsget-pip.py')"

gronostaj's user avatar

gronostaj

54.8k17 gold badges118 silver badges174 bronze badges

answered Aug 29, 2014 at 23:15

Sipherlab's user avatar

0

From Windows 10 build 17063 and later, ‘Curl’ is now included, so that you can execute it directly from Cmd.exe or PowerShell.exe.

For example:

C:>curl.exe -V
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: 2017-11-14, security patched: 2019-11-05
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL

To download a file:

curl.exe -O https://cdn.sstatic.net/Sites/superuser/Img/logo.svg

answered Sep 10, 2020 at 14:41

gsl's user avatar

gslgsl

2072 silver badges9 bronze badges

If you install Telnet, I imagine you could make a HTTP request to a server to download a file.

You can also install Cygwin, and use wget to download a file as well. This is a very easy way to download files from the command line.

answered Oct 23, 2009 at 15:01

EvilChookie's user avatar

EvilChookieEvilChookie

4,5691 gold badge24 silver badges34 bronze badges

10

There are a few ways that you can download using the command line in Windows:

  1. You can use Cygwin.

    Note: the included apps are not native Linux apps. You must rebuild your application from source if you want to run on Windows.

  2. Using telnet it’s possible to make a request but you won’t see any processing.

  3. You can write bat or VBS scripts.

  4. Write your own program that you can run from cmd.exe.

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered Aug 20, 2011 at 3:22

Jesus's user avatar

JesusJesus

111 bronze badge

You can install the Linux application Wget on Windows. It can be downloaded from http://gnuwin32.sourceforge.net/packages/wget.htm. You can then issue the command ‘wget (inserturlhere)’ or any other URL in your command prompt, and it will allow you to download that URL/file/image.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:06

1

In default Windows, you can’t download via HTTP. Windows is a GUI-centric OS, so it lacks many of the commandline tools you’d find in other OS’s, like wget, which would be the prime candidate.

System.Net.WebClient.DownloadFile(), a function in the WiniNet API, can download files, but I’m not sure how far you’re getting into actual development vs. a batch file.

answered Oct 23, 2009 at 15:04

Andrew Scagnelli's user avatar

1

Downloading files in PURE BATCH…
Without any JScript, VBScript, Powershell, etc… Only pure Batch!

Some people are saying it’s not possible of downloading files with a batch script without using any JScript or VBScript, etc… But they are definitely wrong!

Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file’s URL. It is even possible to use a proxy server if you need it.

For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.

Enjoy!


USAGE:

You can use the BITSADMIN command directly, like this:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:DownloadsFile.zip"

Proxy Server:
For connecting using a proxy, use this command before downloading.
bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"

Click this LINK if you want more info about BITSadmin.exe


TROUBLESHOOTING:
If you get this error: «Unable to connect to BITS — 0x80070422»
Make sure the windows service «Background Intelligent Transfer Service (BITS)» is enabled and try again. (It should be enabled by default.)


CUSTOM FUNCTIONS
Call :DOWNLOAD_FILE "URL"
Call :DOWNLOAD_PROXY_ON "SERVER:PORT"
Call :DOWNLOAD_PROXY_OFF

I made these 3 functions for simplifying the bitsadmin commands. It’s easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.

PLEASE NOTE…
Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD

:DOWNLOAD_FILE «URL»
The main function, will download files from URL.

:DOWNLOAD_PROXY_ON «SERVER:PORT»
(Optional) You can use this function if you need to use a proxy server.
Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.

EXAMPLE:
CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"
CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:DownloadsFile.zip"
CALL :DOWNLOAD_PROXY_OFF


CUSTOM_FUNCTIONS.CMD

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

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
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 FILES, 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 URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"

rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:Folder5MB.zip"

rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"

:MAIN

ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
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 THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"

rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF

:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.

:EXIT_SCRIPT
PAUSE
EXIT /B




rem FUNCTIONS SECTION


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

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

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

GNU Wget — консольная программа для загрузки файлов по сети. Поддерживает протоколы HTTP, FTP и HTTPS, а также работу через HTTP прокси-сервер. Программа включена почти во все дистрибутивы Linux. Утилита разрабатывалась для медленных соединений, поэтому она поддерживает докачку файлов при обрыве соединения.

Для работы с Wget под Windows, переходим по ссылке и скачиваем файл wget.exe. Создаем директорию C:Program FilesWget-Win64 и размещаем в ней скачанный файл. Для удобства работы добавляем в переменную окружения PATH путь до исполняемого файла.

Давайте попробуем что-нибудь скачать, скажем дистрибутив Apache под Windows:

> wget https://home.apache.org/~steffenal/VC15/binaries/httpd-2.4.35-win64-VC15.zip
--2018-09-14 10:34:09--  https://home.apache.org/~steffenal/VC15/binaries/httpd-2.4.35-win64-VC15.zip
Resolving home.apache.org (home.apache.org)... 163.172.16.173
Connecting to home.apache.org (home.apache.org)|163.172.16.173|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17856960 (17M) [application/zip]
Saving to: 'httpd-2.4.35-win64-VC15.zip'

httpd-2.4.35-win64-VC15.zip   100%[=================================================>]  17,03M  8,50MB/s    in 2,0s

2018-09-14 10:34:12 (8,50 MB/s) - 'httpd-2.4.35-win64-VC15.zip' saved [17856960/17856960]

Если утилита ругается на сертификаты при скачивании по HTTPS, нужно использовать дополнительную опцию --no-check-certificate.

Примеры

Загрузка всех URL, указанных в файле (каждая ссылка с новой строки):

> wget -i download.txt

Скачивание файлов в указанный каталог:

> wget -P /path/for/save ftp://ftp.example.org/image.iso

Скачивание файла file.zip и сохранение под именем archive.zip:

> wget -O archive.zip http://example.com/file.zip

Продолжить загрузку ранее не полностью загруженного файла:

> wget -c http://example.org/image.iso

Вывод заголовков HTTP серверов и ответов FTP серверов:

> wget -S http://example.org/

Скачать содержимое каталога archive и всех его подкаталогов, при этом не поднимаясь по иерархии каталогов выше:

> wget -r --no-parent http://example.org/some/archive/

Использование имени пользователя и пароля на FTP/HTTP:

> wget --user=login --password=password ftp://ftp.example.org/image.iso
> wget ftp://login:password@ftp.example.org/image.iso

Отправить POST-запрос в формате application/x-www-form-urlencoded:

> wget --post-data="user=evgeniy&password=qwerty" http://example.org/auth/

Сохранение cookie в файл cookie.txt для дальнейшей отправки серверу:

> wget --save-cookie cookie.txt http://example.org/

Сохраненный файл cookie.txt:

# HTTP cookie file.
# Generated by Wget on 2018-09-14 11:40:37.
# Edit at your own risk.

example.org    FALSE    /    FALSE    1570196437    visitor    71f61d2a01de1394f60120c691a52c56

Отправка cookie, сохраненных ранее в файле cookie.txt:

> wget --load-cookie cookie.txt http://example.org/

Отправка заголовков:

> wget --header="Accept-Language: ru-RU,ru;q=0.9" --header="Cookie: PHPSESSID=....." http://example.org/

Справка по утилите:

> wget -h
GNU Wget 1.11.4, программа для загрузки файлов из сети в автономном режиме.
Использование: wget [ОПЦИЯ]... [URL]...
Запуск:
  -V,  --version          вывод версии Wget и выход.
  -h,  --help             вывод этой справки.
  -b,  --background       после запуска перейти в фоновый режим.
  -e,  --execute=КОМАНДА  выполнить команду в стиле .wgetrc.

Журналирование и входной файл:
  -o,  --output-file=ФАЙЛ    записывать сообщения в ФАЙЛ.
  -a,  --append-output=ФАЙЛ  дописывать сообщения в конец ФАЙЛА.
  -d,  --debug               вывод большого количества отладочной информации.
  -q,  --quiet               молча (без выходных данных).
  -v,  --verbose             подробный вывод (по умолчанию).
  -nv, --no-verbose          отключение подробного режима, но не полностью.
  -i,  --input-file=ФАЙЛ     загрузка URL-ов, найденных в ФАЙЛЕ.
  -F,  --force-html          считать, что входной файл - HTML.
  -B,  --base=URL            добавление URL в начало относительных ссылок в файле -F -i.

Загрузка:
  -t,  --tries=ЧИСЛО              установить ЧИСЛО повторных попыток (0 без ограничения).
       --retry-connrefused        повторять, даже если в подключении отказано.
  -O,  --output-document=ФАЙЛ     записывать документы в ФАЙЛ.
  -nc, --no-clobber               пропускать загрузки, которые приведут к загрузке уже существующих файлов.
  -c,  --continue                 возобновить загрузку частично загруженного файла.
       --progress=ТИП             выбрать тип индикатора выполнения.
  -N,  --timestamping             не загружать повторно файлы, только если они не новее, чем локальные.
  -S,  --server-response          вывод ответа сервера.
       --spider                   ничего не загружать.
  -T,  --timeout=СЕКУНДЫ          установка значений всех тайм-аутов в СЕКУНДЫ.
       --dns-timeout=СЕК          установка тайм-аута поиска в DNS в СЕК.
       --connect-timeout=СЕК      установка тайм-аута подключения в СЕК.
       --read-timeout=СЕК         установка тайм-аута чтения в СЕК.
  -w,  --wait=СЕКУНДЫ             пауза в СЕКУНДАХ между загрузками.
       --waitretry=СЕКУНДЫ        пауза в 1..СЕКУНДЫ между повторными попытками загрузки.
       --random-wait              пауза в 0...2*WAIT секунд между загрузками.
       --no-proxy                 явно выключить прокси.
  -Q,  --quota=ЧИСЛО              установить величину квоты загрузки в ЧИСЛО.
       --bind-address=АДРЕС       привязка к АДРЕСУ (имя хоста или IP) локального хоста.
       --limit-rate=СКОРОСТЬ      ограничение СКОРОСТИ загрузки.
       --no-dns-cache             отключение кэширования поисковых DNS-запросов.
       --restrict-file-names=ОС   ограничение на символы в именах файлов, использование которых допускает ОС.
       --ignore-case              игнорировать регистр при сопоставлении файлов и/или каталогов.
  -4,  --inet4-only               подключаться только к адресам IPv4.
  -6,  --inet6-only               подключаться только к адресам IPv6.
       --prefer-family=СЕМЕЙСТВО  подключаться сначала к адресам указанного семейства, может быть IPv6, IPv4 или ничего.
       --user=ПОЛЬЗОВАТЕЛЬ        установить и ftp- и http-пользователя в ПОЛЬЗОВАТЕЛЬ.
       --password=ПАРОЛЬ          установить и ftp- и http-пароль в ПАРОЛЬ.

Каталоги:
  -nd, --no-directories            не создавать каталоги.
  -x,  --force-directories         принудительно создавать каталоги.
  -nH, --no-host-directories       не создавать каталоги как на хосте.
       --protocol-directories      использовать имя протокола в каталогах.
  -P,  --directory-prefix=ПРЕФИКС  сохранять файлы в ПРЕФИКС/...
       --cut-dirs=ЧИСЛО            игнорировать ЧИСЛО компонентов удалённого каталога.

Опции HTTP:
       --http-user=ПОЛЬЗОВАТЕЛЬ   установить http-пользователя в ПОЛЬЗОВАТЕЛЬ.
       --http-password=ПАРОЛЬ     установить http-пароль в ПАРОЛЬ.
       --no-cache                 отвергать кэшированные сервером данные.
  -E,  --html-extension           сохранять HTML-документы с расширением .html.
       --ignore-length            игнорировать поле заголовка Content-Length.
       --header=СТРОКА            вставить СТРОКУ между заголовками.
       --max-redirect             максимально допустимое число перенаправлений на страницу.
       --proxy-user=ПОЛЬЗОВАТЕЛЬ  установить ПОЛЬЗОВАТЕЛЯ в качестве имени пользователя для прокси.
       --proxy-password=ПАРОЛЬ    установить ПАРОЛЬ в качестве пароля для прокси.

       --referer=URL           включить в HTTP-запрос заголовок Referer: URL.
       --save-headers          сохранять HTTP-заголовки в файл.
  -U,  --user-agent=АГЕНТ      идентифицировать себя как АГЕНТ вместо Wget/ВЕРСИЯ.
       --no-http-keep-alive    отключить поддержание активности HTTP (постоянные подключения).
       --no-cookies            не использовать кукисы.
       --load-cookies=ФАЙЛ     загрузить кукисы из ФАЙЛА перед сеансом.
       --save-cookies=ФАЙЛ     сохранить кукисы в ФАЙЛ после сеанса.
       --keep-session-cookies  загрузить и сохранить кукисы сеанса (непостоянные).
       --post-data=СТРОКА      использовать метод POST; отправка СТРОКИ в качестве данных.
       --post-file=ФАЙЛ        использовать метод POST; отправка содержимого ФАЙЛА.
       --content-disposition   Учитывать заголовок Content-Disposition при выборе имён для
                               локальных файлов (ЭКСПЕРИМЕНТАЛЬНЫЙ).
       --auth-no-challenge     Отправить базовые данные аутентификации HTTP
                               не дожидаясь ответа от сервера.

Опции HTTPS (SSL/TLS):
       --secure-protocol=ПР    выбор безопасного протокола: auto, SSLv2, SSLv3 или TLSv1.
       --no-check-certificate  не проверять сертификат сервера.
       --certificate=FILE      файл сертификата пользователя.
       --certificate-type=ТИП  тип сертификата пользователя: PEM или DER.
       --private-key=ФАЙЛ      файл секретного ключа.
       --private-key-type=ТИП  тип секретного ключа: PEM или DER.
       --ca-certificate=ФАЙЛ   файл с набором CA.
       --ca-directory=КАТ      каталог, в котором хранится список CA.
       --random-file=ФАЙЛ      файл со случайными данными для SSL PRNG.
       --egd-file=ФАЙЛ         файл, определяющий сокет EGD со случайными данными.

Опции FTP:
       --ftp-user=ПОЛЬЗОВАТЕЛЬ  установить ftp-пользователя в ПОЛЬЗОВАТЕЛЬ.
       --ftp-password=ПАРОЛЬ    установить ftp-пароль в ПАРОЛЬ.
       --no-remove-listing      не удалять файлы файлы .listing.
       --no-glob                выключить маски для имён файлов FTP.
       --no-passive-ftp         отключить "пассивный" режим передачи.
       --retr-symlinks          при рекурсии загружать файлы по ссылкам (не каталоги).
       --preserve-permissions   сохранять права доступа удалённых файлов.

Рекурсивная загрузка:
  -r,  --recursive         включение рекурсивной загрузки.
  -l,  --level=ЧИСЛО       глубина рекурсии (inf и 0 - бесконечность).
       --delete-after      удалять локальные файлы после загрузки.
  -k,  --convert-links     делать ссылки локальными в загруженном HTML.
  -K,  --backup-converted  перед преобразованием файла X делать резервную копию X.orig.
  -m,  --mirror            короткая опция, эквивалентная -N -r -l inf --no-remove-listing.
  -p,  --page-requisites   загрузить все изображения и проч., необходимые для отображения HTML-страницы.
       --strict-comments   включить строгую (SGML) обработку комментариев HTML.

Разрешения/запреты при рекурсии:
  -A,  --accept=СПИСОК               список разрешённых расширений, разделённых запятыми.
  -R,  --reject=СПИСОК               список запрещённых расширений, разделённых запятыми.
  -D,  --domains=СПИСОК              список разрешённых доменов, разделённых запятыми.
       --exclude-domains=СПИСОК      список запрещённых доменов, разделённых запятыми.
       --follow-ftp                  следовать по ссылкам FTP в HTML-документах.
       --follow-tags=СПИСОК          список используемых тегов HTML, разделённых запятыми.
       --ignore-tags=СПИСОК          список игнорируемых тегов HTML, разделённых запятыми.
  -H,  --span-hosts                  заходить на чужие хосты при рекурсии.
  -L,  --relative                    следовать только по относительным ссылкам.
  -I,  --include-directories=СПИСОК  список разрешённых каталогов.
  -X,  --exclude-directories=СПИСОК  список исключаемых каталогов.
  -np, --no-parent                   не подниматься в родительский каталог.

Дополнительно

  • WGet — программа для загрузки файлов

Поиск:
CLI • Cookie • FTP • HTTP • HTTPS • Linux • POST • Web-разработка • Windows • wget • Форма

Каталог оборудования

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Производители

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Функциональные группы

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Понравилась статья? Поделить с друзьями:
  • Как скачать файл через командную строку windows
  • Как скачать файл с сервера через ssh windows
  • Как скачать файл с сервера ubuntu на компьютер windows
  • Как скачать файл с windows store
  • Как скачать файл с linux сервера на windows