- Изучаем команду wget на 12 примерах
- 1. Загрузка одного файла
- 2. Загрузка файла и сохранение его с новым именем
- 3. Ограничение скорости загрузки файлов
- 4. Завершение прерванной загрузки
- 5. Фоновая загрузка файла
- 6. Загрузка нескольких файлов
- 7. Увеличение общего числа попыток загрузки файла
- 8. Загрузка файлов с FTP-сервера
- 9. Создание локальной копии веб-сайта
- 10. Загрузка с сайта только файлов определённого типа
- 11. Пропуск файлов определённого типа
- 12. Загрузка с использованием собственного .log-файла
- Итоги
- What is the Wget Command and How to Use It (12 Examples Included)
- What is the Wget Command?
- How to Install Wget?
- Wget Command Examples
- Using Wget Command to Download Single Files
- Using Wget Command to Download Multiple Files
- Using Wget Command to Get Files Under Different Names
- Using Wget Command to Save Files in Specified Directory
- Using Wget Command to Limit Download Speed
- Using Wget Command to Set Retry Attempts
- Using Wget Command to Download in Background
- Using Wget Command to Download via FTP
- Using Wget Command to Continue Interrupted Downloads
- Using Wget Command to Retrieve Whole Websites
- Using Wget Command to Locate Broken Links
- Using Wget Command to Download Numbered Files
- Conclusion
- 10 Wget (Linux File Downloader) Command Examples in Linux
- 1. Single file download
- 2. Download file with different name
- 3. Download multiple file with http and ftp protocol
- 4. Read URL’s from a file
- 5. Resume uncompleted download
- 6. Download file with appended .1 in file name
- 7. Download files in background
- 8. Restrict download speed limits
- 9. Restricted FTP and HTTP downloads with username and password
- 10. Find wget version and help
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Изучаем команду wget на 12 примерах
Все мы иногда качаем файлы из интернета. Если для этого использовать программы с графическим интерфейсом, то всё оказывается предельно просто. Однако, при работе в командной строке Linux дело несколько усложняется. Особенно — для тех, кто не знаком с подходящими инструментами. Один из таких инструментов — чрезвычайно мощная утилита wget, которая подходит для выполнения всех видов загрузок. Предлагаем вашему вниманию двенадцать примеров, разобрав которые, можно освоить основные возможности wget.
1. Загрузка одного файла
Если всё, что нужно — это загрузка одного файла, нам подойдёт следующая конструкция:
После ввода такой команды начнётся скачивание Nagios Core. В ходе этого процесса можно будет видеть данные о загрузке, например — сведения о том, какой объём данных уже загружен, текущую скорость, и то, сколько времени осталось до конца загрузки.
2. Загрузка файла и сохранение его с новым именем
Если мы хотим сохранить загруженный файл под именем, отличающимся от его исходного имени, нам пригодится команда wget с параметром -O :
При таком подходе загруженный файл будет сохранён под именем nagios_latest .
3. Ограничение скорости загрузки файлов
При необходимости скорость загрузки файлов с помощью wget можно ограничить. В результате эта операция не будет занимать весь доступный канал передачи данных и не повлияет на другие процессы, связанные с сетью. Сделать это можно, используя параметр —limit-rate и указав ограничение скорости, выраженное в байтах (в виде обычного числа), килобайтах (добавив после числа K ) или мегабайтах ( M ) в секунду:
Здесь задано ограничение скорости загрузки, равное 500 Кб/с.
4. Завершение прерванной загрузки
Если в ходе загрузки файлов эта операция была прервана, можно возобновить загрузку с помощью параметра -c команды wget :
Если этот параметр не использовать, то загрузка недокачанного файла начнётся сначала.
5. Фоновая загрузка файла
Если вы загружаете файл огромного размера и хотите выполнять эту операцию в фоне, сделать это можно, используя параметр -b :
6. Загрузка нескольких файлов
Если имеется список URL файлов, которые надо загрузить, но вам не хочется вручную запускать загрузки этих файлов, можно использовать параметр -I . Однако, перед тем, как начинать загрузку, нужно создать файл, содержащий все адреса. Например, сделать это можно такой командой:
В этот файл нужно поместить адреса — по одному в каждой строке. Далее, осталось лишь запустить wget , передав этой утилите только что созданный файл со списком загрузок:
Выполнение этой команды приведёт к поочерёдной загрузке всех файлов из списка.
7. Увеличение общего числа попыток загрузки файла
Для того, чтобы настроить число повторных попыток загрузки файла, можно использовать параметр —tries :
8. Загрузка файлов с FTP-сервера
Команда загрузки файла с анонимного FTP-сервера с помощью wget выглядит так:
Если для доступа к файлу требуются имя пользователя и пароль, то команда примет такой вид:
9. Создание локальной копии веб-сайта
Если нужно загрузить содержимое целого веб-сайта, сделать это можно, воспользовавшись параметром —mirror :
Обратите внимание на дополнительные параметры командной строки:
- -p : производится загрузка всех файлов, необходимых для корректного отображения HTML-страниц.
- —convert-links : ссылки в документах будут преобразованы для целей локального просмотра сайта.
- -P /home/dan : материалы будут сохранены в папку /home/dan .
10. Загрузка с сайта только файлов определённого типа
Для того, чтобы загрузить с сайта только файлы определённого типа, можно воспользоваться параметрами -r -A :
11. Пропуск файлов определённого типа
Если вы хотите скопировать целый веб-сайт, но при этом вам не нужны файлы определённого типа, отключить их загрузку можно с помощью параметра —reject :
12. Загрузка с использованием собственного .log-файла
Для того, чтобы загрузить файл и использовать при этом собственный .log -файл, воспользуйтесь параметром -o и укажите имя файла журнала:
Итоги
Wget — довольно простая в использовании, но весьма полезная утилита Linux. И, на самом деле то, о чём мы рассказали — лишь малая часть того, что она умеет. Надеемся, этот обзор поможет тем, кто не был знаком с wget, оценить эту программу, и, возможно, включить её в свой повседневный арсенал инструментов командной строки.
Уважаемые читатели! Пользуетесь ли вы инструментами командной строки Linux для загрузки файлов? Если да — просим о них рассказать.
Источник
What is the Wget Command and How to Use It (12 Examples Included)
This guide will show you how to use the wget command in Linux. We’ll also provide 12 useful wget command examples. By the end, you’ll know all about the wget command and will be able to use it to download files from the World Wide Web.
What is the Wget Command?
Wget is a computer tool created by the GNU Project. You can use it to retrieve content and files from various web servers. The name is a combination of World Wide Web and the word get. It supports downloads via FTP, SFTP, HTTP, and HTTPS.
Wget is created in portable C and usable on any Unix system. It’s also possible to implement on Mac OS X, Microsoft Windows, AmigaOS, and other popular platforms.
How to Install Wget?
For this wget command demonstration, we’ll be using Ubuntu 16.04. But the syntax will work on any other Linux distribution too.
To install wget on Ubuntu 18.04 or similar, execute the following command:
To install wget on CentOS 7 or it’s previous distros, use:
Once the setup finishes, you’ll be ready to use it. Also, the knowledge of basic SSH commands can make things easier.
Wget Command Examples
To get you started, we’ll provide 12 wget command examples that you can use for everyday tasks. Keep in mind that you may also call this function from scripts and cron jobs!
Using Wget Command to Download Single Files
One of the most basic wget command examples is downloading a single file and storing it on your current working directory. For example, you may get the latest version of WordPress by using the following:
Here is the output that you will see:
In this example, a file named latest.zip will be downloaded in the current working directory. You’ll also see extra information, such the download progress, speed, size, time, and date.
Using Wget Command to Download Multiple Files
We can take wget usage one step further and download multiple files at once. To do that, we will need to create a text document and place the download URLs there. In this example, we will retrieve the latest versions of WordPress, Joomla, and Drupal by using wget. Enter the following:
This will create an example.txt file and open a text editor interface. Paste these links there:
Once done, you may use -i to get all the files stored in your example text file:
Wait for the process to finish and you’ll have the installations of three most popular content management systems.
Using Wget Command to Get Files Under Different Names
In this wget example, we will save a file using a different name with the help of -O option:
In this case, the downloaded resource will be saved as wordpress-install.zip instead of it’s original name.
Using Wget Command to Save Files in Specified Directory
You can utilize wget to place a file in another directory using -P function:
The file you retrieve using this syntax will appear in documents/archives/ folder.
Using Wget Command to Limit Download Speed
With wget, you can also limit the download speed. This is useful when retrieving huge files and will prevent it from using all of your bandwidth. This wget example will set the limit to 500k:
Using Wget Command to Set Retry Attempts
Internet connection problems can cause your download to interrupt. To tackle this issue, we can increase the retry attempts using -tries function:
Using Wget Command to Download in Background
For extremely large files, you may take advantage of -b function. It will download your content in the background.
A wget-log will appear in your working directory, which can be used to check your download progress and status. This command will also do the trick:
Using Wget Command to Download via FTP
The command is also usable with FTP. You’ll only need to specify the username and password as in this wget example:
Using Wget Command to Continue Interrupted Downloads
Your download can get interrupted if you lose the internet connection or experience a power outage. This is quite a common occurrence when getting huge files. Instead of starting over, it’s possible to continue the download using -c function:
If you proceed without the -c function, the new file will have .1 added at the end as it already exists.
Using Wget Command to Retrieve Whole Websites
It is also possible to use wget command to download the content of an entire site. This will let you view it locally without an internet connection. Here is an example:
Let’s analyze the ingredients of this wget command:
–mirror | It makes your download recursive. |
–convert-links | All links will be converted for proper offline usage. |
–page-requisites | The following will include all necessary files such as CSS, JS, and images. |
–no-parent | It ensures that directories above the hierarchy are not retrieved. |
-P documents/websites/ | This ensures that all content goes to our specified directory. |
Once the process finishes, you’ll be able to open the downloaded website locally and find all the files in documents/websites/ folder.
Using Wget Command to Locate Broken Links
Let’s try something more advanced. We can use the wget command to locate all broken URLs that display 404 error on a specific website. Start by executing the following:
-o | Gathers output into a file for later use. |
-l | Specifies the recursion level. |
-r | Makes the download recursive. |
–spider | Sets wget to spider mode. |
We may now investigate the wget-log file to find the list of broken links. Here’s the command to do it:
Using Wget Command to Download Numbered Files
If you have files or images numbered in a certain list, you may easily download all of them with the following syntax:
Conclusion
Congratulations! By completing this tutorial you have learned various uses for the wget command. You can now utilize it to get single or multiple files. In addition, you’ve learned some advanced uses, such as downloading a whole website or locating broken URLs. For more information, you may also check the official documentation.
Are there any hidden tips or tricks that you want to share? Feel free to do so in the comments below!
Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.
Источник
10 Wget (Linux File Downloader) Command Examples in Linux
In this post we are going to review wget utility which retrieves files from World Wide Web (WWW) using widely used protocols like HTTP, HTTPS and FTP. Wget utility is freely available package and license is under GNU GPL License. This utility can be install any Unix-like Operating system including Windows and MAC OS. It’s a non-interactive command line tool. Main feature of Wget of it’s robustness. It’s designed in such way so that it works in slow or unstable network connections. Wget automatically start download where it was left off in case of network problem. Also downloads file recursively. It’ll keep trying until file has be retrieved completely.
10 Linux Wget Command Examples
First, check whether wget utility is already installed or not in your Linux box, using following command.
Please install it using YUM command in case wget is not installed already or you can also download binary package at http://ftp.gnu.org/gnu/wget/.
The -y option used here, is to prevent confirmation prompt before installing any package. For more YUM command examples and options read the article on 20 YUM Command Examples for Linux Package Management.
1. Single file download
The command will download single file and stores in a current directory. It also shows download progress, size, date and time while downloading.
2. Download file with different name
Using -O (uppercase) option, downloads file with different file name. Here we have given wget.zip file name as show below.
3. Download multiple file with http and ftp protocol
Here we see how to download multiple files using HTTP and FTP protocol with wget command at ones.
4. Read URL’s from a file
You can store number of URL’s in text file and download them with -i option. Below we have created tmp.txt under wget directory where we put series of URL’s to download.
5. Resume uncompleted download
In case of big file download, it may happen sometime to stop download in that case we can resume download the same file where it was left off with -c option. But when you start download file without specifying -c option wget will add .1 extension at the end of file, considering as a fresh download. So, it’s good practice to add -c switch when you download big files.
6. Download file with appended .1 in file name
When you start download without -c option wget add .1 at the end of file and start with fresh download. If .1 already exist .2 append at the end of file.
See the example files with .1 extension appended at the end of the file.
7. Download files in background
With -b option you can send download in background immediately after download start and logs are written in /wget/log.txt file.
8. Restrict download speed limits
With Option –limit-rate=100k, the download speed limit is restricted to 100k and the logs will be created under /wget/log.txt as shown below.
9. Restricted FTP and HTTP downloads with username and password
With Options –http-user=username, –http-password=password & –ftp-user=username, –ftp-password=password, you can download password restricted HTTP or FTP sites as shown below.
10. Find wget version and help
With Options –version and –help you can view version and help as needed.
In this article we have covered Linux wget command with options for daily administrative task. Do man wget if you wan to know more about it. Kindly share through our comment box or if we’ve missed out anything, do let us know.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник