- Download a file from the command line in Windows
- Как скачать файлы из командной строки в Windows, как wget или cURL
- 17 ответов
- How can I download a file from the Internet via Command Prompt? [duplicate]
- 1 Answer 1
- Not the answer you’re looking for? Browse other questions tagged windows cmd or ask your own question.
- Linked
- Related
- Hot Network Questions
- Download web content through CMD
- 5 Answers 5
- Windows batch file file download from a URL
- 20 Answers 20
- Downloading files in PURE BATCH. Without any JScript, VBScript, Powershell, etc. Only pure Batch!
Download a file from the command line in Windows
As a Linux user, I can’t help but spend most of my time on the command line. Not that the GUI is not efficient, but there are things that are simply faster to do with the keyboard.
Think about copy and paste. Select a text you want to copy, go to the edit menu, click, precisely move down to copy, click, then go to the destination, click where you want to paste, go to edit menu, click, move down to the paste option, then paste. Every time I see someone do this, I die a little inside. Sure you can save some time by right-clicking, copy, right-click, paste. But you can save some more time by pressing, ctrl-c then ctrl-v
My hands are already on the keyboard, and I would rather do the mundane things on the keyboard and not think about them.
One thing I do frequently is download files. They can be zip file, tgz, or jpg. On linux, all I have to do is open the command line, run wget with the file I want to download and it is done.
Straight to the point. But how do you do that when you are on a Windows machine? Let me introduce you to cURL, pronounced curl. (i don’t know why I wrote it the way I did)
curl is a very powerful tool with too many feature. But I just want to download the file on Windows so let’s just learn how to do that.
Open PowerShell. That’s Windows Key + R then type powershell and press enter.
Now run the curl command with the -O option to specify the file output.
Easy right? Now you can download files right from the command line all by simply using your keyboard.
OK. It is time I confess. This is not the curl tool you are using. It’s only an alias. In reality, we are calling the command Invoke-WebRequest . But hey! It works, so we don’t care. You can call it in its native format if you want to.
Either way, now you know how to download a file from the command line.
Did you like this article? You can subscribe to read more awesome ones. Share your insightful comments here.
Как скачать файлы из командной строки в Windows, как wget или cURL
Как я могу скачать что-то из интернета непосредственно без Internet Explorer или Firefox открытие Acrobat Reader / Quicktime / MS Word / что?
Я использую Windows, поэтому версия Windows Wget будет делать.
17 ответов
GNU Wget — бесплатная сетевая утилита для извлечения файлов из мира Широкая паутина используя HTTP и FTP, 2 наиболее широко используемый интернет протоколы. Он работает неинтерактивно, что позволяет фон, после выхода из системы.
с этот раздел FAQ, скачать ссылки предложил:
ссылка с учтивостью Ерней Simončič используется вместо этого.
альтернатива, которую я недавно обнаружил, используя PowerShell:
это работает также с GET запросов.
Если необходимо указать учетные данные для загрузки файла, добавьте следующую строку:
появится стандартный запрос учетных данных windows. Введенные там учетные данные будут использоваться для загрузки файла. Это нужно сделать только один раз за все время использования объекта $client.
Если у вас PowerShell > = 3.0, вы можете использовать Invoke-WebRequest
Windows имеет свою собственную утилиту загрузки командной строки -BITSAdmin:
BITSAdmin-это инструмент командной строки, который можно использовать для создания загрузки или загружать задания и следить за их ходом.
и полный bitsadmin пример:
Edit:15.05.2018 — оказалось, что можно скачать с файл с сертификатом тоже:
Certutil не устанавливается по умолчанию на XP / Win2003, но avaialble на новых версиях windows.Для XP/2003 вам понадобится Admin Tool Pack для windows server 2003
сохраните следующий текст в wget.js и просто позвонить
Я сделал быстрый myGet.bat-файл, который вызывает метод PowerShell, описанный выше.
есть родной завиток для Windows доступен здесь. Существует множество разновидностей-с поддержкой SSL и без нее.
вам не нужен дополнительный багаж Cygwin и любит, только один маленький EXE-файл.
также важно знать, что есть оба wget и curl псевдонимы, встроенные во все современные версии Windows Powershell. Они эквивалентны.
нет дополнительные файлы или загрузки требуется получить wget функции:
вы можете ввести команду cURL, как тот, который загружает файл из Репозитории GitHub.
и покажется как это работает, но то, что он на самом деле делает это просто использование cURL в качестве псевдонима. В приведенном выше примере, что произойдет, это что вы просто получите заголовки вместо самого файла.
псевдонимы в PowerShell позволяют создавать ярлыки для более длинных команд, так что вам не придется вводить их все время.
если ввести команду Get-Alias, появится список всех псевдонимов, используемых в PowerShell. Как видите, команда curl просто вызывает команду Invoke-WebRequest. Они похожи, но не то же самое, поэтому выше запрос не работает для нас.
для правильной работы в PowerShell проще всего использовать переменные и -OutFile аргументов, как показано ниже:
этот синтаксис загрузит полное содержимое целевого файла azuredeploy.json локальный файл newfile.json
основное преимущество заключается в том, что он встроен в Powershell сам по себе, так что этот код будет выполняться непосредственно без загрузки или каких-либо других дополнительных файлов, необходимых для его работы на любой современной версии Windows.
Я искал то же самое, и поскольку у меня не было привилегии установить любой из вышеперечисленных пакетов, я пошел на небольшой обходной путь (для загрузки 30+файлов):
- Я создал пакетный файл
- перечислены все файлы
- Put firefox.exe в начале каждой строки
- пошел в каталог firefox в Program Files
- запустил его.
If PowerShell Это вариант, это предпочтительный маршрут, так как вам (потенциально) не придется устанавливать ничего лишнего:
В противном случае, Wget для Windows, Как отметили другие, безусловно, второй лучший вариант. Как опубликовано в другом ответе, похоже, что вы можете скачать Wget все само по себе, или вы можете захватить его как часть Cygwin или MSys.
Если по какой-то причине, вы не найдете сами застряли в временной деформации, используя машину, которая не имеет PowerShell и у вас нет доступа к работающему веб-браузеру (то есть Internet Explorer является единственным браузером в системе, и его настройки повреждены), а ваш файл находится на FTP-сайте (в отличие от HTTP):
Если память служит он был там с Windows 98, и я могу подтвердить, что он по-прежнему существует в Windows 8 RTM (вы, возможно, придется перейти в appwiz.cpl и добавить/удалить компоненты, чтобы получить она.) Эта утилита может как загружать, так и загружать файлы на/с FTP-сайтов в интернете. его можно также использовать в сценариях для того чтобы автоматизировать любую деятельность.
этот встроенный инструмент был для меня настоящим спасателем в прошлом, особенно во времена ftp.cdrom.com — я загрузил Firefox таким образом однажды, на полностью сломанной машине, у которой было только подключение к интернету (когда максимальный размер пакета sneakernet все еще составлял 1,44 МБ, а Firefox все еще назывался «Netscape» / me делает trollface).
несколько советов: это собственный командный процессор, и у него свой синтаксис. Попробуйте ввести «помощь». Все FTP-сайты требуют имя пользователя и пароль; но если они позволяют «анонимные» пользователи, имя пользователя «анонимный» и пароль Ваш адрес электронной почты (вы можете сделать один, если вы не хотите, чтобы быть отслежены, но, как правило, есть какая-то логика, чтобы убедиться, что это действительный адрес электронной почты).
How can I download a file from the Internet via Command Prompt? [duplicate]
As mentioned in the title I need a command line that allows me to download a file in the background without installing any tool just cmd I found this one but it doesn’t work in the background and Need a confirmation
so how to make the magic happen? and is there another command that i need to add it to the above line like a confirmation !?
1 Answer 1
CMD doesn’t have a built-in download command. You can download a utility like wget, and get the file with
PowerShell, which is built into every version of Windows 7 and above, does have a built-in command for downloading in Invoke-Webrequest
You can invoke this in one line from CMD by using the following PowerShell.exe command line.
Not the answer you’re looking for? Browse other questions tagged windows cmd or ask your own question.
Linked
Related
Hot Network Questions
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Download web content through CMD
I want some way of getting an online content on the command prompt window (Windows CMD).
Imagine some content online stored either on a hosting service or the MySql database provided to you by that hosting service. It can be any data stored in any form. I just want to remotely view it with the help of a CMD window anywhere in the world. What command should I be using?
To make it more clear, lets just say you have one day to prepare for your exam. Rather than preparing for it, you are making a plan to cheat.
Now your exam is going to be conducted on a computer that has been allotted to you and you are not allowed to use a browser or download any new application on the PC. But you can use Command Prompt, so your task being a cheat is to put the answers somewhere online. You cannot install anything new.
How will you go about if you are stuck in the above scene?
P.S This is for educational purpose only. I have no such such exams.
5 Answers 5
It depends entirely on how the content is stored and accessed. CMD knows how to get things from SMB network shares (\computername\folder), but you need to run a program to access most other stuff. (eg: sqlcmd for a database)
CMD does not support downloading web content. You will need to use another program to connect to the website and download the page. Obviously a browser would work. Another option is to download wget.exe from UnxUtils. Or use another scripting language like PowerShell or Wscript.
If you have access to launch PowerShell (pre-installed on Windows 7-10), you can use the .NET library to download web resources.
This will use .NET to connect to the page and download it into the local directory. To download to another directory or filename, change the -OutFile argument.
To launch this from CMD, go into a PowerShell prompt by simply typing powershell in CMD, and running the PS commands from there. Alternatively, you can run PS commands from CMD using the powershell -c command.
Windows batch file file download from a URL
I am trying to download a file from a website (ex. http://www.example.com/package.zip) using a Windows batch file. I am getting an error code when I write the function below:
The batch file doesn’t seem to like the «/» after the http. Are there any ways to escape those characters so it doesn’t assume they are function parameters?
20 Answers 20
With PowerShell 2.0 (Windows 7 preinstalled) you can use:
Starting with PowerShell 3.0 (Windows 8 preinstalled) you can use Invoke-WebRequest :
From a batch file they are called:
(PowerShell 2.0 is available for installation on XP, 3.0 for Windows 7)
There’s a standard Windows component which can achieve what you’re trying to do: BITS. It has been included in Windows since XP and 2000 SP3.
The job name is simply the display name for the download job — set it to something that describes what you’re doing.
This might be a little off topic, but you can pretty easily download a file using Powershell. Powershell comes with modern versions of Windows so you don’t have to install any extra stuff on the computer. I learned how to do it by reading this page:
Last I checked, there isn’t a command line command to connect to a URL from the MS command line. Try wget for Windows:
http://gnuwin32.sourceforge.net/packages/wget.htm
In Linux, you can use «wget».
Alternatively, you can try VBScript. They are like command line programs, but they are scripts interpreted by the wscript.exe scripts host. Here is an example of downloading a file using VBS:
https://serverfault.com/questions/29707/download-file-from-vbscript
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.
USAGE:
You can use the BITSADMIN command directly, like this:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND «http://example.com/File.zip» «C:\Downloads\File.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.