Wget ошибка срок действия сертификата истек

I have a script that runs every day on an Ubuntu 14.04 server. The script is a simple wget command that downloads a file from a remote server and saves it to the local file system:

wget https://example.com/resources/scripts/myfile.php -O myfile.php

It has worked fine for months until this morning when suddenly when I run it I get:

--2020-05-30 11:57:16--  https://example.com/resources/scripts/myfile.php
Resolving example.com (example.com)... xx.xx.xx.xx
Connecting to example.com (example.com)|xx.xx.xx.xx|:443... connected.
ERROR: cannot verify example.com's certificate, issued by ‘/C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo RSA Domain Validation Secure Server CA’:
  Issued certificate has expired.
To connect to example.com insecurely, use `--no-check-certificate'.

The SSL for the domain is valid and expires in Jan. 2022. Nothing has changed on that front. And yet somehow wget no longer sees that.

Here is another interesting fact. If I run this same exact command on an Ubuntu 18 box, it works like a charm without any complaints. This tells me something is wrong with my Ubuntu 14.04 machine.

Curl produces the same error:

curl https://example.com
curl: (60) SSL certificate problem: certificate has expired

This post suggest that the certificate bundle is out of date. I have downloaded the suggested PEM file and tried running wget with by specifying the —ca-certificate=cacert.pem option, but to no avail.

I have also tried running: apt install ca-certificates and update-ca-certificates, but that did not work either.

Again, everything works great on an Ubuntu 18 box, but not Ubuntu 14 or 16. Also why did it work fine until this morning when I know nobody has touched the box? Clearly something is out of date, but I can’t seem to figure out how to fix it.

Does anybody have any suggestions?

So you installed wget and when you tried to download files in the Linux terminal, it got you an SSL certificate error like the following?

sagar@LHB:~$ wget https://expired.badssl.com
--2022-11-04 14:35:55--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
ERROR: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
To connect to expired.badssl.com insecurely, use `--no-check-certificate'.

The reason why you get this error is simple. By default, wget checks for a valid SSL certificate so that you can have a reliable connection and if not, it throws an error saying the Issued certificate has expired.

So let’s have a look at how to ignore SSL certificate errors while using wget.

Ignore SSL certificate error with wget

While I won’t advise you to connect over a website that has a broken SSL certificate, you may find this error on a trusted site and wish to continue, so here you go.

To ignore this error, you have to use --no-check-certificate option and it won’t check for an SSL certificate:

wget --no-check-certificate https://expired.badssl.com
sagar@LHB:~$ wget --no-check-certificate https://expired.badssl.com
--2022-11-04 15:18:07--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
WARNING: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
HTTP request sent, awaiting response... 200 OK
Length: 494 [text/html]
Saving to: ‘index.html.1’

index.html.1        100%[===================>]     494  --.-KB/s    in 0s      

2022-11-04 15:18:08 (209 MB/s) - ‘index.html.1’ saved [494/494]

Skip the certification check

⚠️

I do not recommend this unless you have an isolated environment or want to test things regardless of security concerns.

To skip the certification check every time you visit the broken SSL site, you just have to append check-certificate = off in wget config file:

And now, you can download files using wget over broken SSL sites without adding --no-check-certificate option:

sagar@LHB:~$ wget https://expired.badssl.com
--2022-11-04 15:41:50--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
WARNING: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
HTTP request sent, awaiting response... 200 OK
Length: 494 [text/html]
Saving to: ‘index.html.2’

index.html.2        100%[===================>]     494  --.-KB/s    in 0s      

2022-11-04 15:41:51 (191 MB/s) - ‘index.html.2’ saved [494/494]

Wrapping Up

Curl or wget, you can face this issue in both commands. We have covered handling the SSL certificate error with curl as well.

Ignore SSL Certificate Error with cURL

Getting an expired certificate error while downloading files with curl? Here’s how to ignore it.

Sagar Sharma

Through this guide, I explained how you could ignore SSL certificate errors with wget. If you have any queries, let me know in the comments.

I have a script that runs every day on an Ubuntu 14.04 server. The script is a simple wget command that downloads a file from a remote server and saves it to the local file system:

wget https://example.com/resources/scripts/myfile.php -O myfile.php

It has worked fine for months until this morning when suddenly when I run it I get:

--2020-05-30 11:57:16--  https://example.com/resources/scripts/myfile.php
Resolving example.com (example.com)... xx.xx.xx.xx
Connecting to example.com (example.com)|xx.xx.xx.xx|:443... connected.
ERROR: cannot verify example.com's certificate, issued by ‘/C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo RSA Domain Validation Secure Server CA’:
  Issued certificate has expired.
To connect to example.com insecurely, use `--no-check-certificate'.

The SSL for the domain is valid and expires in Jan. 2022. Nothing has changed on that front. And yet somehow wget no longer sees that.

Here is another interesting fact. If I run this same exact command on an Ubuntu 18 box, it works like a charm without any complaints. This tells me something is wrong with my Ubuntu 14.04 machine.

Curl produces the same error:

curl https://example.com
curl: (60) SSL certificate problem: certificate has expired

This post suggest that the certificate bundle is out of date. I have downloaded the suggested PEM file and tried running wget with by specifying the —ca-certificate=cacert.pem option, but to no avail.

I have also tried running: apt install ca-certificates and update-ca-certificates, but that did not work either.

Again, everything works great on an Ubuntu 18 box, but not Ubuntu 14 or 16. Also why did it work fine until this morning when I know nobody has touched the box? Clearly something is out of date, but I can’t seem to figure out how to fix it.

Does anybody have any suggestions?

So you installed wget and when you tried to download files in the Linux terminal, it got you an SSL certificate error like the following?

[email protected]:~$ wget https://expired.badssl.com
--2022-11-04 14:35:55--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
ERROR: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
To connect to expired.badssl.com insecurely, use `--no-check-certificate'.

The reason why you get this error is simple. By default, wget checks for a valid SSL certificate so that you can have a reliable connection and if not, it throws an error saying the Issued certificate has expired.

So let’s have a look at how to ignore SSL certificate errors while using wget.

Ignore SSL certificate error with wget

While I won’t advise you to connect over a website that has a broken SSL certificate, you may find this error on a trusted site and wish to continue, so here you go.

To ignore this error, you have to use --no-check-certificate option and it won’t check for an SSL certificate:

wget --no-check-certificate https://expired.badssl.com
[email protected]:~$ wget --no-check-certificate https://expired.badssl.com
--2022-11-04 15:18:07--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
WARNING: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
HTTP request sent, awaiting response... 200 OK
Length: 494 [text/html]
Saving to: ‘index.html.1’

index.html.1        100%[===================>]     494  --.-KB/s    in 0s      

2022-11-04 15:18:08 (209 MB/s) - ‘index.html.1’ saved [494/494]

Skip the certification check

⚠️

I do not recommend this unless you have an isolated environment or want to test things regardless of security concerns.

To skip the certification check every time you visit the broken SSL site, you just have to append check-certificate = off in wget config file:

And now, you can download files using wget over broken SSL sites without adding --no-check-certificate option:

[email protected]:~$ wget https://expired.badssl.com
--2022-11-04 15:41:50--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
WARNING: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
HTTP request sent, awaiting response... 200 OK
Length: 494 [text/html]
Saving to: ‘index.html.2’

index.html.2        100%[===================>]     494  --.-KB/s    in 0s      

2022-11-04 15:41:51 (191 MB/s) - ‘index.html.2’ saved [494/494]

Wrapping Up

Curl or wget, you can face this issue in both commands.

Through this guide, I explained how you could ignore SSL certificate errors with wget. If you have any queries, let me know in the comments.

Sagar Sharma

A software engineer who loves to tinker with hardware till it gets crashed. While reviving my crashed system, you can find me reading literature, manga, or watering my plants.

Одна из часто используемых утилит сисадминов- это wget.

Что такое команда wget?

Команда wget – это популярная утилита командной строки Unix / Linux для извлечения контента из Интернета.

Она бесплатна  и предоставляет неинтерактивный способ загрузки файлов из Интернета.

Команда wget из коробки поддерживает протоколы HTTPS, HTTP и FTP.

Более того, вы также можете использовать с ней HTTP прокси.

Как команда wget поможет в траблшутинге?

Есть много способов и вариантов применения.

Как системный администратор, большую часть времени вы будете работать с терминалом, а при устранении неполадок, связанных с веб-приложением, вы можете захотеть не проверять всю страницу целиком, а только  лишь подключение к ней.

Наряду с wget вы конечно можете использовать не менее популярную команду curl:

⚓ Как использовать команду cURL в Linux

Или вы хотите проверить интранет-сайты.

Или вы захотите скачать определенную страницу, чтобы проверить содержимое.

wget неинтерактивен, что означает, что вы можете запускать его в фоновом режиме, даже если вы вышли из системы.

Может быть много случаев, когда вам необходимо отключиться от системы, даже когда вы извлекаете файлы из Интернета.

В фоновом режиме wget спокойное запустится и завершит назначенную работу.

Wget также может быть использован для получения всего сайта на ваш локальный компьютер.

Wget может следовать по ссылкам на страницах XHTML и HTML для создания локальной версии.

Для этого он должен загрузить страницу рекурсивно.

Это очень полезно, поскольку вы можете использовать его для загрузки важных страниц или сайтов для просмотра в автономном режиме.

Давайте посмотрим на эти команды в действии.

Синтаксис wget приведен ниже:

wget [option] [URL]

1. Скачать веб-страницу

Давайте попробуем скачать страницу. Пример: github.com

wget github.com

Если сеть в порядке, wget загрузит домашнюю страницу и покажет вывод, как показано ниже.

wget github.com
URL transformed to HTTPS due to an HSTS policy
--2020-02-23 10:45:52--  https://github.com/
Resolving github.com (github.com)... 140.82.118.3
Connecting to github.com (github.com)|140.82.118.3|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified 
Saving to: ‘index.html’

index.html                                       [ <=>                                                                                        ] 131.96K  --.-KB/s    in 0.04s

2020-02-23 10:45:52 (2.89 MB/s) - ‘index.html’ saved [135126]

2. Скачать несколько файлов

Wget также удобно использовать, когда вам нужно скачать несколько файлов одновременно.

Это может дать вам представление об автоматизации загрузки файлов с помощью некоторых скриптов.

Попробуем скачать файлы Python 3.8.1 и 3.5.1.

wget https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tgz https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

Итак, как вы можете догадаться, синтаксис следующий:

wget URL1 URL2 URL3

Вы просто должны добавить пробелы между URL-адресами.

3. Ограничить скорость загрузки

Это будет полезно, если вы хотите проверить, сколько времени занимает загрузка файла с другой пропускной способностью.

Используя опцию –limit-rate, вы можете ограничить скорость загрузки.

Вот результат загрузки файла Nodejs.

# wget https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
--2020-02-23 10:59:58--  https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
Resolving nodejs.org (nodejs.org)... 104.20.23.46, 104.20.22.46, 2606:4700:10::6814:162e, ...
Connecting to nodejs.org (nodejs.org)|104.20.23.46|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 14591852 (14M) [application/x-xz]
Saving to: ‘node-v12.16.1-linux-x64.tar.xz’

node-v12.16.1-linux-x64.tar.xz               100%[===========================================================================================>]  13.92M  --.-KB/s    in 0.05s

2020-02-23 10:59:58 (272 MB/s) - ‘node-v12.16.1-linux-x64.tar.xz’ saved [14591852/14591852]

Загрузка файлов объемом 13,92 МБ заняла 0,05 секунды.

Теперь давайте попробуем ограничить скорость до 500К.

wget --limit-rate=500k https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
--2020-02-23 11:00:18--  https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
Resolving nodejs.org (nodejs.org)... 104.20.23.46, 104.20.22.46, 2606:4700:10::6814:162e, ...
Connecting to nodejs.org (nodejs.org)|104.20.23.46|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 14591852 (14M) [application/x-xz]
Saving to: ‘node-v12.16.1-linux-x64.tar.xz.1’

node-v12.16.1-linux-x64.tar.xz.1             100%[===========================================================================================>]  13.92M   501KB/s    in 28s

2020-02-23 11:00:46 (500 KB/s) - ‘node-v12.16.1-linux-x64.tar.xz.1’ saved [14591852/14591852]

С уменьшением полосы пропускания скачивание заняло больше времени – 28 секунд.

Представьте, ваши пользователи жалуются на медленную загрузку, и вы знаете, что их пропускная способность сети довольно низкая.

Вы можете быстро попробовать –limit-rate для имитации проблемы.

4. Скачать в фоновом режиме

Загрузка больших файлов может занять некоторое время.

А что, если вы не хотите смотреть в свой терминал?

Ну, вы можете использовать аргумент -b, чтобы запустить wget в фоновом режиме.

wget -b https://slack.com
Continuing in background, pid 25430.
Output will be written to ‘wget-log.1’.
root@itisgood:~#

5. Игнорировать ошибку сертификата

Это удобно, когда вам нужно проверить веб-приложения интрасети, которые не имеют надлежащего сертификата.

По умолчанию wget выдаст ошибку, если сертификат недействителен.

wget https://expired.badssl.com/
--2020-02-23 11:24:59--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
ERROR: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
To connect to expired.badssl.com insecurely, use `--no-check-certificate'.

Приведенный выше пример относится к URL-адресу, срок действия сертификата у которого истек.

Как вы можете видеть, система предложила использовать –no-check-Certificate, который будет игнорировать любую проверку сертификата.

wget https://untrusted-root.badssl.com/ --no-check-certificate
--2020-02-23 11:33:45--  https://untrusted-root.badssl.com/
Resolving untrusted-root.badssl.com (untrusted-root.badssl.com)... 104.154.89.105
Connecting to untrusted-root.badssl.com (untrusted-root.badssl.com)|104.154.89.105|:443... connected.
WARNING: cannot verify untrusted-root.badssl.com's certificate, issued by ‘CN=BadSSL Untrusted Root Certificate Authority,O=BadSSL,L=San Francisco,ST=California,C=US’:
  Self-signed certificate encountered.
HTTP request sent, awaiting response... 200 OK
Length: 600 
Saving to: ‘index.html.6’

index.html.6                                 100%[===========================================================================================>]     600  --.-KB/s    in 0s

2020-02-23 11:33:45 (122 MB/s) - ‘index.html.6’ saved [600/600]

6. Заголовок ответа HTTP

Посмотрите заголовок ответа HTTP сайта прям на терминале.

Использование -S выведет заголовок, как вы можете увидеть его, как показано ниже ( Пример с itsecforu )

wget https://www.itsecforu.ru -S
--2020-02-25 11:30:46-- https://www.itsecforu.ru/
Resolving www.itsecforu.ru (www.itsecforu.ru)... 37.140.192.99, 2a00:f940:2:2:1:3:0:81
Connecting to www.itsecforu.ru (www.itsecforu.ru)|37.140.192.99|:443... connected.
HTTP request sent, awaiting response...
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Tue, 25 Feb 2020 08:30:47 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 0
Connection: keep-alive
X-Powered-By: PHP/5.6.36
Set-Cookie: apbct_timestamp=1582619446; path=/; domain=itsecforu.ru; httponly
Set-Cookie: apbct_site_landing_ts=1582619446; path=/; domain=itsecforu.ru; httponly
Set-Cookie: apbct_page_hits=1; path=/; domain=itsecforu.ru; httponly
Set-Cookie: apbct_cookies_test=%257B%2522cookies_names%2522%253A%255B%2522apbct_timestamp%2522%252C%2522apbct_site_landing_ts%2522%252C%2522apbct_page_hits%2522%255D%252C%2522check_value%2522%253A%2522d9c7e9c1369fe7d54b54da2a92cdaf01%2522%257D; path=/; domain=itsecforu.ru; httponly
Location: https://itsecforu.ru/
Strict-Transport-Security: max-age=31536000;
Location: https://itsecforu.ru/ [following]
--2020-02-25 11:30:47-- https://itsecforu.ru/
Resolving itsecforu.ru (itsecforu.ru)... 37.140.192.99, 2a00:f940:2:2:1:3:0:81
Connecting to itsecforu.ru (itsecforu.ru)|37.140.192.99|:443... connected.
HTTP request sent, awaiting response...
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 25 Feb 2020 08:30:49 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.6.36
Link: <https://itsecforu.ru/wp-json/>; rel="https://api.w.org/", <https://itsecforu.ru/>; rel=shortlink
Set-Cookie: apbct_timestamp=1582619447; path=/; domain=itsecforu.ru; httponly
Set-Cookie: apbct_page_hits=2; path=/; domain=itsecforu.ru; httponly
Set-Cookie: apbct_cookies_test=%257B%2522cookies_names%2522%253A%255B%2522apbct_timestamp%2522%252C%2522apbct_site_landing_ts%2522%252C%2522apbct_page_hits%2522%255D%252C%2522check_value%2522%253A%2522a03457d3d599cadadd7c93808f66a0d3%2522%257D; path=/; domain=itsecforu.ru; httponly
Strict-Transport-Security: max-age=31536000;
Length: unspecified 
Saving to: ‘index.html.1’

[ <=>

7. Использовать User-Agent

Может возникнуть ситуация, когда вы захотите подключить сайт с помощью user-agent.

Или определенный user-agent браузера.

Это можно сделать, указав –user-agent.

Приведенный ниже пример для user-agent MyCustomUserAgent.

wget https://gf.dev --user-agent="MyCustomUserAgent"

8. Заголовок хоста

Когда приложение все еще находится в разработке, у вас может не быть правильного URL для его тестирования.

Или, возможно, вы захотите протестировать отдельный экземпляр HTTP с использованием IP, но вам нужно предоставить заголовок хоста для правильной работы приложения.

В этой ситуации ключт –header будет полезен.

wget --header="Host: application.com" http://10.10.10.1

Использовать можно не только Host, вы можете вставить любой заголовок, который вам нравится.

9. Подключиться через прокси

Если вы работаете в среде DMZ, у вас может не быть доступа к интернет-сайтам.

Но вы можете воспользоваться прокси для подключения к сайту.

wget -e use_proxy=yes http_proxy=$PROXYHOST:PORT http://externalsite.com

Не забудьте обновить переменную $PROXYHOST:PORT

10. Подключиться, используя определенный протокол TLS

Обычно я бы рекомендовал использовать OpenSSL для тестирования протокола TLS.

Но вы также можете использовать wget.

wget --secure-protocol=TLSv1_2 https://example.com

Вышеуказанная команда заставит wget подключиться через TLS 1.2.

Заключение

Знание необходимой команды может помочь вам в работе.

Я надеюсь, что вышеизложенная информация даст вам представление о том, что вы можете сделать с помощью wget.

Удачного траблшутинга и оставайтесь с нами 🙂

См. также по теме:

  • 🌐 Использование Wget с FTP для рекурсивного скачивания / просмотра веб-сайтов
  • 🐧 Как установить Wget на Linux
  • 💄 Как установить и использовать Wget на Mac
  • Как ограничить скорость загрузки файлов с помощью Wget в Linux
  • Как загрузить файлы в конкретный каталог с помощью Wget
  • 🐧 [CentOS] Инструменты, не включенные в CentOS 7 minimal

Перейти к содержанию

На чтение 2 мин Опубликовано 31.12.2021

Игнорируем ошибки проверки сертификата при использовании wget.

Попробуйте получить доступ к адресу, защищенному самоподписанным сертификатом.

$ wget --output-document - https://nextcloud.example.org
--2021-07-16 13:59:59--  https://nextcloud.example.org/
Resolving nextcloud.example.org (nextcloud.example.org)... 192.168.8.32
Connecting to nextcloud.example.org (nextcloud.example.org)|192.168.8.32|:443... connected.
ERROR: cannot verify nextcloud.example.org's certificate, issued by ‘CN=nextcloud.example.org’:
  Self-signed certificate encountered.
To connect to nextcloud.example.org insecurely, use `--no-check-certificate'.
$ wget --quiet --no-check-certificate  --output-document - https://nextcloud.example.org/robots.txt
User-agent: *
Disallow: /

Выдержка из страницы руководства.

[...]

--no-check-certificate
   Don't check the server certificate against the available certificate authorities.  Also don't require the URL host name to match the common name
   presented by the certificate.

   As of Wget 1.10, the default is to verify the server's certificate against the recognized certificate authorities, breaking the SSL handshake and
   aborting the download if the verification fails.  Although this provides more secure downloads, it does break interoperability with some sites
   that worked with previous Wget versions, particularly those using self-signed, expired, or otherwise invalid certificates.  This option forces an
   "insecure" mode of operation that turns the certificate verification errors into warnings and allows you to proceed.

   If you encounter "certificate verification" errors or ones saying that "common name doesn't match requested host name", you can use this option
   to bypass the verification and proceed with the download.  Only use this option if you are otherwise convinced of the site's authenticity, or if
   you really don't care about the validity of its certificate.  It is almost always a bad idea not to check the certificates when transmitting
   confidential or important data.  For self-signed/internal certificates, you should download the certificate and verify against that instead of
   forcing this insecure mode.  If you are really sure of not desiring any certificate verification, you can specify --check-certificate=quiet to
   tell wget to not print any warning about invalid certificates, albeit in most cases this is the wrong thing to do.

[...]

см. также:

  • 🖧 Советы и рекомендации по использованию команды wget в системах Linux
  • 🖧 В чем разница между curl и Wget?
  • 🖧 Как использовать wget за прокси

Пожалуйста, не спамьте и никого не оскорбляйте.

Это поле для комментариев, а не спамбокс.

Рекламные ссылки не индексируются!

wget — это популярная утилита командной строки Unix / Linux для извлечения контента из интернета. Он бесплатный и предоставляет способ загрузки файлов из интернета через терминал. Команда wget поддерживает протоколы HTTPS, HTTP и FTP из коробки. Более того, вы также можете использовать HTTP прокси.

Как он поможет вам устранить неполадки?

Есть много способов.

Как системный администратор, большую часть времени вы будете работать с терминалом, а при устранении неполадок, связанных с веб-приложением, вы можете не захотеть проверять всю страницу, а только возможность подключения. Или вы захотите загрузить определенную страницу, чтобы проверить содержимое.

wget неинтерактивен, что означает, что вы можете запускать его в фоновом режиме, даже если вы вышли из системы. Может быть много случаев, когда вам необходимо отключиться от системы, даже когда вы извлекаете файлы из Интернета. В фоновом режиме, wget будет работать пока не закончит назначенную работу.

Он также может быть использован для получения всего сайта на ваших локальных компьютерах. Он может следовать ссылкам на страницах XHTML и HTML для создания локальной версии. Для этого wget должен загрузить страницу рекурсивно. Это очень полезно, поскольку вы можете использовать его для загрузки важных страниц или сайтов для просмотра в автономном режиме.

Если вы любитель Linux, советуем прочитать об 11 команд на Linux для работы в качестве системного администратора.

Давайте посмотрим wget в действии. Синтаксис wget приведен ниже.

wget [option] [URL]

1. Скачать веб-страницу

Попробуем скачать страницу. Например: stackoverflow.com

wget stackoverflow.com

Если соединение с интернетом установлено, он загрузит домашнюю страницу и покажет вывод, как показано ниже.

root@user:~# wget stackoverflow.com
URL transformed to HTTPS due to an HSTS policy
--2020-02-25 09:53:28--  https://stackoverflow.com/
Распознаётся stackoverflow.com (stackoverflow.com)… 151.101.129.69, 151.101.193.69, 151.101.1.69, ...
Подключение к stackoverflow.com (stackoverflow.com)|151.101.129.69|:443... соединение установлено.
HTTP-запрос отправлен. Ожидание ответа… 200 OK
Длина: 112371 (110K) [text/html]
Сохранение в: «index.html»

index.html          100%[===================>] 109,74K   408KB/s    за 0,3s    

2020-02-25 09:53:29 (408 KB/s) - «index.html» сохранён [112371/112371]

root@user:~#

2. Скачать несколько файлов

Удобно, когда вам нужно скачать несколько файлов одновременно. Это может дать вам представление об автоматизации загрузки файлов с помощью некоторых скриптов.

Попробуем скачать файлы Python 3.8.1 и 3.5.1.

wget https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tgz https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

Итак, как вы можете догадаться, синтаксис такой, как показано ниже.

wget URL1 URL2 URL3

Вы просто должны обеспечить пространство (пробел) между URL-адресами.

3. Ограничить скорость загрузки

Иногда бывает полезным когда вы хотите проверить, сколько времени занимает загрузка файла с другой пропускной способностью.

Используя параметр --limit-rate, вы можете ограничить скорость загрузки.

Вот результат загрузки Nodejs.

root@user:~# wget https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
--2020-02-25 10:02:54--  https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
Распознаётся nodejs.org (nodejs.org)… 104.20.22.46, 104.20.23.46, 2606:4700:10::6814:162e, ...
Подключение к nodejs.org (nodejs.org)|104.20.22.46|:443... соединение установлено.
HTTP-запрос отправлен. Ожидание ответа… 200 OK
Длина: 14591852 (14M) [application/x-xz]
Сохранение в: «node-v12.16.1-linux-x64.tar.xz»

node-v12.16.1-linux 100%[===================>]  13,92M  3,78MB/s    за 4,0s    

2020-02-25 10:02:58 (3,46 MB/s) - «node-v12.16.1-linux-x64.tar.xz» сохранён [14591852/14591852]

Загрузка файлов объемом 13,92 МБ заняла 4 секунды. Теперь давайте попробуем ограничить скорость до 500 КБ.

root@user:~# wget --limit-rate=500k https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
--2020-02-25 10:04:45--  https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
Распознаётся nodejs.org (nodejs.org)… 104.20.23.46, 104.20.22.46, 2606:4700:10::6814:172e, ...
Подключение к nodejs.org (nodejs.org)|104.20.23.46|:443... соединение установлено.
HTTP-запрос отправлен. Ожидание ответа… 200 OK
Длина: 14591852 (14M) [application/x-xz]
Сохранение в: «node-v12.16.1-linux-x64.tar.xz»

node-v12.16.1-linux 100%[===================>]  13,92M   522KB/s    за 28s     

2020-02-25 10:05:13 (503 KB/s) - «node-v12.16.1-linux-x64.tar.xz» сохранён [14591852/14591852]

Из-за уменьшение пропускной способности, скачивание файла заняло больше времени: 28 секунд. Представьте, ваши пользователи жалуются на медленную загрузку, и вы знаете, что их пропускная способность сети низкая. С помощью параметра  --limit-rate вы можете попытаться быстро смоделировать проблему.

4. Скачать в фоновом режиме

Загрузка больших файлов может занять много времени. Плюс если вы еще захотите ограничить скорость, как показано выше. Для того, чтобы долго не пялиться в терминал, в ожидании когда файлы загрузиться, можно проделать вес этот процесс в фоновом режиме.

Для этого вы можете использовать аргумент -b для запуска wget в фоновом режиме.

root@user:~# wget -b https://slack.com
Работа продолжается в фоновом режиме, pid 2450.
Выходные данные будут записаны в «wget-log».

root@user:~#

5. Игнорировать ошибку сертификата

Это удобно, когда вам нужно проверить веб-приложения, которые не имеют надлежащего сертификата. По умолчанию wget выдаст ошибку, если сертификат недействителен.

root@user:~# wget https://expired.badssl.com/
--2020-02-25 10:16:29--  https://expired.badssl.com/
Распознаётся expired.badssl.com (expired.badssl.com)… 104.154.89.105
Подключение к expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... соединение установлено.
ОШИБКА: невозможно проверить сертификат expired.badssl.com, выпущенный «CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB»:
  Для запрошенного сертификата истёк срок действия.
Для небезопасного подключения к expired.badssl.com используйте параметр «--no-check-certificate».

Приведенный выше пример относится к URL-адресу, срок действия которого истек. Как вы можете видеть, он предложил использовать параметр --no-check-certificate который будет игнорировать любую проверку сертификата.

root@user:~# wget https://untrusted-root.badssl.com/ --no-check-certificate
--2020-02-25 10:19:34--  https://untrusted-root.badssl.com/
Распознаётся untrusted-root.badssl.com (untrusted-root.badssl.com)… 104.154.89.105
Подключение к untrusted-root.badssl.com (untrusted-root.badssl.com)|104.154.89.105|:443... соединение установлено.
ПРЕДУПРЕЖДЕНИЕ: невозможно проверить сертификат untrusted-root.badssl.com, выпущенный «CN=BadSSL Untrusted Root Certificate Authority,O=BadSSL,L=San Francisco,ST=California,C=US»:
  Обнаружен самостоятельно подписанный сертификат.
HTTP-запрос отправлен. Ожидание ответа… 200 OK
Длина: 600 [text/html]
Сохранение в: «index.html.1»

index.html.1        100%[===================>]     600  --.-KB/s    за 0s      

2020-02-25 10:19:35 (34,4 MB/s) - «index.html.1» сохранён [600/600]

Круто, не правда ли?

6. Заголовок ответа HTTP

Смотрите заголовок ответа HTTP любого сайта в терминале.

При использовании параметра -s, wget также покажет http заголовок страницы.

root@user:~# wget https://github.com -S
--2020-02-25 10:27:09--  https://github.com/
Распознаётся github.com (github.com)… 140.82.118.4
Подключение к github.com (github.com)|140.82.118.4|:443... соединение установлено.
HTTP-запрос отправлен. Ожидание ответа… 
  HTTP/1.1 200 OK
  Date: Tue, 25 Feb 2020 06:27:05 GMT
  Content-Type: text/html; charset=utf-8
  Server: GitHub.com
  Status: 200 OK
  Vary: X-PJAX, Accept-Encoding, Accept, X-Requested-With
  ETag: W/"a31adc71563b164fd0d33424f6a05a27"
  Cache-Control: max-age=0, private, must-revalidate
  Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
  X-Frame-Options: deny
  X-Content-Type-Options: nosniff
  X-XSS-Protection: 1; mode=block
  Referrer-Policy: origin-when-cross-origin, strict-origin-when-cross-origin
  Expect-CT: max-age=2592000, report-uri="https://api.github.com/_private/browser/errors"
  Content-Security-Policy: default-src 'none'; base-uri 'self'; block-all-mixed-content; connect-src 'self' uploads.github.com www.githubstatus.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com wss://live.github.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com; frame-ancestors 'none'; frame-src render.githubusercontent.com; img-src 'self' data: github.githubassets.com identicons.github.com collector.githubapp.com github-cloud.s3.amazonaws.com *.githubusercontent.com customer-stories-feed.github.com spotlights-feed.github.com; manifest-src 'self'; media-src 'none'; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com
  Age: 6
  Set-Cookie: _gh_sess=BnblGIPpIaiUhFIE4iTylHACRtS6%2By%2FDzdThgfcpqE3Uo2wXp7QTJXCCEpka72yAS6phLFfzozbmADCKcSutvPZxSj8UHP3ikTTu%2F8Cd3QbCXYqUBiVPWmYQ0gwhRfolv4K40c05eYXlNqBXNeYFvR7wb%2BEWIDSOMVUm0O81nMLiZZgYFfetyBTYuuLhwNAXc0WcT6nh8WBqyCj5lkSADBSRwbQrUeVjghqPRX4FfGrjtgJ3yjHlyjMZZKMGR8F34m6VebuIKcibRXT9oqkzCQ%3D%3D--3YFWMiCZ4m03WsdT--TOfg%2Fx7gnExjYz1UOV7kPg%3D%3D; Path=/; HttpOnly; Secure
  Set-Cookie: _octo=GH1.1.1883752978.1582612031; Path=/; Domain=github.com; Expires=Thu, 25 Feb 2021 06:27:11 GMT; Secure
  Set-Cookie: logged_in=no; Path=/; Domain=github.com; Expires=Thu, 25 Feb 2021 06:27:11 GMT; HttpOnly; Secure
  Accept-Ranges: bytes
  Transfer-Encoding: chunked
  X-GitHub-Request-Id: 0A3C:1C90:767DF5:B3C0FB:5E54BE3F
Длина: нет данных [text/html]
Сохранение в: «index.html.1»

index.html.1            [  <=>               ] 132,35K   507KB/s    за 0,3s    

2020-02-25 10:27:10 (507 KB/s) - «index.html.1» сохранён [135526]

7. Манипулировать User-Agent

Может возникнуть ситуация, когда вы захотите подключить сайт с помощью пользовательского агента User-Agent. Это выполнимо, если после URL-адреса, указать параметр --user-agent.

root@user:~# wget https://itgap.ru --user-agent="MyCustomUserAgent"

8. HTTP заголовоки

Когда приложение все еще находится в разработке, у вас может не быть правильного URL для его тестирования. Или, возможно, вы захотите протестировать отдельный экземпляр HTTP с использованием IP, но вам нужно предоставить заголовок хоста для правильной работы приложения. В этой ситуации используйте параметр --header.

Давайте рассмотрим пример тестирования http://10.10.10.1 с заголовком узла как application.com

wget --header="Host: application.com" http://10.10.10.1

Вы можете вставить любой заголовок, который вам понадобится.

9. Подключение через прокси

Если вы работаете в среде DMZ, у вас может не быть доступа к интернет-сайтам. Но вы можете воспользоваться прокси для подключения.

wget -e use_proxy=yes http_proxy=$PROXYHOST:PORT http://externalsite.com

Не забудьте обновить переменную $ PROXYHOST: PORT на актуальную.

10. Подключение с использованием определенного протокола TLS

Обычно я бы рекомендовал использовать OpenSSL для тестирования протокола TLS. Но вы также можете использовать wget.

wget --secure-protocol=TLSv1_2 https://example.com

Вышеуказанный пример заставит wget подключиться через TLS 1.2.

Заключение

Я надеюсь, что вышеизложенное дает вам представление о том, что вы можете сделать с wget.

У меня такой же симптом для f-droid.org:

% wget 'https://f-droid.org/F-Droid.apk'
--2020-06-03 14:10:18--  https://f-droid.org/F-Droid.apk
Resolving f-droid.org (f-droid.org)... 217.160.165.113, 148.251.140.42
Connecting to f-droid.org (f-droid.org)|217.160.165.113|:443... connected.
ERROR: The certificate of ‘f-droid.org’ is not trusted.
ERROR: The certificate of ‘f-droid.org’ has expired.

В моем случае (Debian 9 stretch) curl тоже не работает:

% curl 'https://f-droid.org/F-Droid.apk'
curl: (60) SSL certificate problem: certificate has expired
More details here: https://curl.haxx.se/docs/sslcerts.html

Посмотрев на источник wget, можно увидеть, что ошибка возникает из-за флага состояния, возвращаемого gnutls_certificate_verify_peers2. Мы можем попросить gnutls показать детали проверки сертификата:

% gnutls-cli f-droid.org -p 443
Processed 151 CA certificate(s).
Resolving 'f-droid.org:443'...
Connecting to '217.160.165.113:443'...
- Certificate type: X.509
- Got a certificate list of 3 certificates.
- Certificate[0] info:
 - subject `CN=f-droid.org,OU=PositiveSSL,OU=Domain Control Validated', issuer `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', serial 0x02a8508e042b9f065fafadd87cd7d103, RSA key 2048 bits, signed using RSA-SHA256, activated `2019-09-17 00:00:00 UTC', expires `2020-09-16 23:59:59 UTC', key-ID `sha256:e97ccbf3c188b5cf69a83ed0fc39b001ce1688a62b573193cef3f74984c7d703'
    Public Key ID:
            sha1:638f93856e1f5edfcbd40c46d4160cff21b0713a
            sha256:e97ccbf3c188b5cf69a83ed0fc39b001ce1688a62b573193cef3f74984c7d703
    Public key's random art:
            +--[ RSA 2048]----+
            |           o o+o.|
            |            *...o|
            |           E ..+ |
            |         .  ... o|
            |        S .   o .|
            |       o *   . o.|
            |        * o .  .o|
            |       . + o .o. |
            |          o   .oo|
            +-----------------+

- Certificate[1] info:
 - subject `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', issuer `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', serial 0x7d5b5126b476ba11db74160bbc530da7, RSA key 2048 bits, signed using RSA-SHA384, activated `2018-11-02 00:00:00 UTC', expires `2030-12-31 23:59:59 UTC', key-ID `sha256:e1ae9c3de848ece1ba72e0d991ae4d0d9ec547c6bad1dddab9d6beb0a7e0e0d8'
- Certificate[2] info:
 - subject `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', issuer `CN=AddTrust External CA Root,OU=AddTrust External TTP Network,O=AddTrust AB,C=SE', serial 0x13ea28705bf4eced0c36630980614336, RSA key 4096 bits, signed using RSA-SHA384, activated `2000-05-30 10:48:38 UTC', expires `2020-05-30 10:48:38 UTC', key-ID `sha256:c784333d20bcd742b9fdc3236f4e509b8937070e73067e254dd3bf9c45bf4dde'
- Status: The certificate is NOT trusted. The certificate chain uses expired certificate. 
*** PKI verification of server certificate failed...

Итак, проблема заключается в сертификате центра сертификации USERTrust RSA, предоставленном сервером.f-droid.org. Это промежуточный сертификат, подписанный AddTrust External CA Root, срок действия которого истек 4 дня назад.

Debian ca-certificatesпакет имеет самоподписанный (корневой) сертификат для центра сертификации USERTrust RSA:

% openssl x509 -inform PEM -in /usr/share/ca-certificates/mozilla/USERTrust_RSA_Certification_Authority.crt -text | grep -A2 Validity
    Validity
        Not Before: Feb  1 00:00:00 2010 GMT
        Not After : Jan 18 23:59:59 2038 GMT

… но gnutls сбит с толку сертификатом с истекшим сроком действия, предоставленным сервером, отсюда и ошибка.

В твоем случае (mirrors.edge.kernel.org) цепочка сертификатов выглядит следующим образом:

% gnutls-cli mirrors.edge.kernel.org -p 443
Processed 151 CA certificate(s).
Resolving 'mirrors.edge.kernel.org:443'...
Connecting to '147.75.101.1:443'...
- Certificate type: X.509
- Got a certificate list of 3 certificates.
- Certificate[0] info:
 - subject `CN=*.edge.kernel.org', issuer `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', serial 0x00a34d0ccfbf4ea450fe030fd3378f5d68, RSA key 2048 bits, signed using RSA-SHA256, activated `2020-03-16 00:00:00 UTC', expires `2021-03-16 23:59:59 UTC', key-ID `sha256:f3746cf281b6453def23289054e75e26e157bfd9eed5252b76ffdc828b802e41'
    Public Key ID:
            sha1:72d8fc84d0dea848189bc3ff8eb1d47629fd72c0
            sha256:f3746cf281b6453def23289054e75e26e157bfd9eed5252b76ffdc828b802e41
    Public key's random art:
            +--[ RSA 2048]----+
            |                 |
            |       .         |
            |  .   . .        |
            | . =   * +       |
            |  * . o.S o      |
            |   + o =E+       |
            |    = = +..      |
            |   . * o...      |
            |    o.o  o.      |
            +-----------------+

- Certificate[1] info:
 - subject `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', issuer `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', serial 0x7d5b5126b476ba11db74160bbc530da7, RSA key 2048 bits, signed using RSA-SHA384, activated `2018-11-02 00:00:00 UTC', expires `2030-12-31 23:59:59 UTC', key-ID `sha256:e1ae9c3de848ece1ba72e0d991ae4d0d9ec547c6bad1dddab9d6beb0a7e0e0d8'
- Certificate[2] info:
 - subject `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', issuer `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', serial 0x01fd6d30fca3ca51a81bbc640e35032d, RSA key 4096 bits, signed using RSA-SHA384, activated `2010-02-01 00:00:00 UTC', expires `2038-01-18 23:59:59 UTC', key-ID `sha256:c784333d20bcd742b9fdc3236f4e509b8937070e73067e254dd3bf9c45bf4dde'
- Status: The certificate is trusted. 

Снова мы видим центр сертификации USERTrust RSA, но здесь это самоподписанный (корневой) сертификат, срок действия которого не истек. Я предполагаю, что kernel.org также предоставил просроченный промежуточный сертификат, но исправленный вами. я думаю--no-dns-cache не имеет значения, простое совпадение.

Кстати, Firefox отлично отображает https://f-droid.org/.Show page info / Securityпоказывает новый самоподписанный (корневой) сертификат USERTrust:Not after: 18 January 2038, 23:59:59 GMT. То есть Firefox проигнорировал просроченный промежуточный сертификат USERTrust, предоставленный сервером, использовал действительный корневой сертификат USERTrust, доступный локально.

Разрешение? Веб-мастер сервера должен удалить устаревший промежуточный сертификат из конфигурации сервера. А пока используйте Firefox (или curl, если он работает) вместо wget.

Обновление: как отметили люди f-droid, ошибка gnutls уже исправлена, исправление должно быть скоро в Debian-security.

Wget – свободная утилита, предоставляющая неинтерактивный способ загрузки файлов из интернета
по HTTPS, HTTP, FTP и даже HTTP-прокси.

Вы можете запустить wget в фоновом режиме, а он доделает
всю назначенную работу. Обычно утилиту используют для получения всего веб-сайта,
перехода по ссылкам на страницах XHTML/HTML и создания локальной версии сайта.
Синтаксис wget выглядит так:

        wget [option] [URL]
    

1. Скачивание страницы

Попробуем загрузить
страницу github.com:

        wget github.com
    

Если все подключилось,
то wget загрузит домашнюю страницу и покажет результат, как показано ниже:

        wget github.com
URL transformed to HTTPS due to an HSTS policy
--2020-02-23 10:45:52--  https://github.com/
Resolving github.com (github.com)... 140.82.118.3
Connecting to github.com (github.com)|140.82.118.3|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘index.html’

index.html                                       [ <=>                                                                                        ] 131.96K  --.-KB/s    in 0.04s

2020-02-23 10:45:52 (2.89 MB/s) - ‘index.html’ saved [135126]
    

2. Скачивание нескольких
файлов

Круто, если можно
загрузить сразу несколько файлов. Это, кстати, идея для написания какого-нибудь
скрипта для автоматизации загрузки файлов, подумайте на досуге.

Попробуем скачать
архивы с Python 3.8.1 и 3.5.1:

        wget https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tgz https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
    

Как вы уже догадались,
синтаксис такой:

        wget URL1 URL2 URL3
    

Не забывайте про пробел
между ссылками!

3. Ограничение скорости
загрузки

Ограничить скорость загрузки полезно,
когда стоит задача проверить, сколько времени занимает загрузка файла на разной
пропускной способности.

Используя опцию --
limit-rate
, вы можете ограничить скорость загрузки.

Вот результат загрузки
файла Node.js:

        wget https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
--2020-02-23 10:59:58--  https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
Resolving nodejs.org (nodejs.org)... 104.20.23.46, 104.20.22.46, 2606:4700:10::6814:162e, ...
Connecting to nodejs.org (nodejs.org)|104.20.23.46|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 14591852 (14M) [application/x-xz]
Saving to: ‘node-v12.16.1-linux-x64.tar.xz’

node-v12.16.1-linux-x64.tar.xz               100%[===========================================================================================>]  13.92M  --.-KB/s    in 0.05s

2020-02-23 10:59:58 (272 MB/s) - ‘node-v12.16.1-linux-x64.tar.xz’ saved [14591852/14591852]
    

Потребовалось 0.05 с, чтобы скачать 13.92 Мб. Теперь попробуем ограничить скорость до 500 Кб/с:

        wget --limit-rate=500k https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
--2020-02-23 11:00:18--  https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz
Resolving nodejs.org (nodejs.org)... 104.20.23.46, 104.20.22.46, 2606:4700:10::6814:162e, ...
Connecting to nodejs.org (nodejs.org)|104.20.23.46|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 14591852 (14M) [application/x-xz]
Saving to: ‘node-v12.16.1-linux-x64.tar.xz.1’

node-v12.16.1-linux-x64.tar.xz.1             100%[===========================================================================================>]  13.92M   501KB/s    in 28s

2020-02-23 11:00:46 (500 KB/s) - ‘node-v12.16.1-linux-x64.tar.xz.1’ saved [14591852/14591852]
    

Скорость загрузки упала
до 28 с. Представьте себе ситуацию – юзеры жалуются на медленную загрузку.
Вы можете быстро поиграться с limit-rate для имитации проблемы.

4. Загрузка в фоне

Загрузка больших файлов
может занять некоторое время, но что если вы не хотите смотреть в терминал?

Можно использовать ключ
-b, чтобы запустить wget в фоновом режиме:

        wget -b https://slack.com
Continuing in background, pid 25430.
Output will be written to ‘wget-log.1’.
    

5. Игнорирование ошибки
сертификата

Игнорирование ошибки сертификата удобно, когда вам
нужно обратиться к узлу во внешней сети без соответствующего сертификата. Если сертификат не является валидным, по
умолчанию wget выдаст ошибку.

        wget https://expired.badssl.com/
--2020-02-23 11:24:59--  https://expired.badssl.com/
Resolving expired.badssl.com (expired.badssl.com)... 104.154.89.105
Connecting to expired.badssl.com (expired.badssl.com)|104.154.89.105|:443... connected.
ERROR: cannot verify expired.badssl.com's certificate, issued by ‘CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB’:
  Issued certificate has expired.
To connect to expired.badssl.com insecurely, use `--no-check-certificate'.

    

На примере выше результат истекшего срока действия сертификата. Предлагается использовать
--no-check-certificate для игнорирования любой проверки сертификата. Сравним результат с добавленным ключом:

        wget https://untrusted-root.badssl.com/ --no-check-certificate
--2020-02-23 11:33:45--  https://untrusted-root.badssl.com/
Resolving untrusted-root.badssl.com (untrusted-root.badssl.com)... 104.154.89.105
Connecting to untrusted-root.badssl.com (untrusted-root.badssl.com)|104.154.89.105|:443... connected.
WARNING: cannot verify untrusted-root.badssl.com's certificate, issued by ‘CN=BadSSL Untrusted Root Certificate Authority,O=BadSSL,L=San Francisco,ST=California,C=US’:
  Self-signed certificate encountered.
HTTP request sent, awaiting response... 200 OK
Length: 600 [text/html]
Saving to: ‘index.html.6’

index.html.6   100%[===========================================================================================>]     600  --.-KB/s    in 0s

2020-02-23 11:33:45 (122 MB/s) - ‘index.html.6’ saved [600/600]
    

6. Заголовок HTTP ответа

С помощью ключа -S в
терминал будет выведен заголовок, как это произошло с Яндексом:

         wget -S --no-check-certificate https://www.yandex.ru
--2020-03-20 02:52:16--  https://www.yandex.ru/
Resolving www.yandex.ru (www.yandex.ru)... 149.5.244.14, 80.239.201.15
Connecting to www.yandex.ru (www.yandex.ru)|149.5.244.14|:443... connected.
HTTP request sent, awaiting response...
   HTTP/1.1 200 Ok
  Accept-CH: Viewport-Width, DPR, Device-Memory, RTT, Downlink, ECT
  Accept-CH-Lifetime: 31536000
  Cache-Control: no-cache,no-store,max-age=0,must-revalidate
  Content-Length: 199540 
  Content-Type: text/html; charset=UTF-8
  Date: Thu, 19 Mar 2020 23:52:49 GMT
  Expires: Thu, 19 Mar 2020 23:52:50 GMT
  Last-Modified: Thu, 19 Mar 2020 23:52:50 GMT
  P3P: policyref="/w3c/p3p.xml", CP="NON DSP ADM DEV PSD IVDo OUR IND STP PHY PR                                                     E NAV UNI"
  Set-Cookie: yp=1587253970.ygu.1; Expires=Sun, 17-Mar-2030 23:52:49 GMT; Domain                                                     =.yandex.ru; Path=/
  Set-Cookie: mda=0; Expires=Fri, 17-Jul-2020 23:52:49 GMT; Domain=.yandex.ru; P                                                     ath=/
  Set-Cookie: yandex_gid=213; Expires=Sat, 18-Apr-2020 23:52:49 GMT; Domain=.yan                                                     dex.ru; Path=/
  X-Content-Type-Options: nosniff
  X-Frame-Options: DENY
  X-Yandex-Sdch-Disable: 1

    

7. Манипуляции с
User-Agent

Бывает так, что мы хотим открыть сайт с помощью другого user-agent. Это можно сделать, указав ключ --user-agent:

        wget https://gf.dev --user-agent="MyCustomUserAgent"
    

8. Заголовок хоста

Когда приложение находится
в разработке и есть необходимость что-то потестить, но нет подходящего
URL-адреса или мы хотим протестировать домен с использованием IP-адреса – в обеих ситуациях будет полезен --header.

Для примера возьмем
http://10.10.10.1 и application.com в качестве заголовка:

        wget --header="Host: application.com" http://10.10.10.1
    

9. Подключение через
прокси

Если вы работаете в
среде DMZ, вас может не выпускать в интернет. Воспользуйтесь преимуществами
прокси для подключения:

        wget -e use_proxy=yes http_proxy=$PROXYHOST:PORT http://externalsite.com
    

Не забудьте в
переменной $PROXYHOST:PORT указать реальные значения.

10. Подключение через TLS

Обычно рекомендуют
использовать OpenSSL для тестирования протокола TLS. Но можете использовать и
wget.

        wget --secure-protocol=TLSv1_2 https://example.com
    

Вышеизложенное заставит
wget подключиться через TLS 1.2.

Заключение

Если вам интересно подробнее разобраться в утилите, имеется перевод документации wget на русский. В некоторых случаях хорошей альтернативой wget является cURL, а для создания зеркал сайтов (чего cURL не умеет) обычно используется rsync.

Еще вам могут быть интересны следующие публикации:

  • 6 команд терминала и пара комбинаций, полезных для начинающих разработчиков
  • Терминал Linux: видеокурс по работе на примере Ubuntu
  • 14 полезных трюков для работы с консолью

Источники

  • https://geekflare.com/wget-command-examples/

Значит поставил кто-то другой. Можешь использовать http либо ключ —no-check-certificate. Либо обновить сертификат.

slowpony ★★★★

(26.07.22 19:56:07 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от slowpony 26.07.22 19:56:07 MSK

Так оно же пишет, что сертификат «протух». Вроде как, у всех сертификатов есть срок жизни

  • Ссылка

У сайта истёк срок жизни сертификата. Нужно попросить администратора этого сайта исправить проблему.

vbr

(08.08.22 10:52:27 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от User01 08.08.22 10:49:09 MSK

Попробуй спросить у поисковика $SERVERNAME install ssl certificate или $SERVERNAME установка ssl сертификата. Здесь $SERVERNAME — тот http-сервер, который крутится у тебя на VDS.

Если же пользуешься хостингом для веб-страниц — покопайся в документации хостера, как они предлагают ставить сертификаты через их админку.

  • Ссылка

wget --no-check-certificate

Не?

Ну и проверить наличие установленного пакета ca-certificates

neocrust ★★★★★

(08.08.22 10:56:56 MSK)

Последнее исправление: neocrust 08.08.22 10:58:00 MSK
(всего

исправлений: 2)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от neocrust 08.08.22 10:56:56 MSK

ну там не только wget не работает, есть игра, в ней плагин, и он как-то обращается к сайту, вернее обращался, сейчас не может уже. Я просто проверил для теста с wget и увидел что проблема не в том сайте а у меня на железке. А где они сидят, может их можно как-то скачать с друго сервера посредством rsync на пример. Или их ставить нужно именно

User01

(08.08.22 11:20:50 MSK)

  • Ссылка

Ответ на:

комментарий
от vbr 08.08.22 10:52:27 MSK

думаю не в сайте дело, на другом сервере все работает и скачивает с этого сайта

User01

(08.08.22 11:21:28 MSK)

  • Показать ответы
  • Ссылка

Ответ на:

комментарий
от User01 08.08.22 11:21:28 MSK

Ответ на:

комментарий
от aol 08.08.22 11:31:28 MSK

Ответ на:

комментарий
от User01 08.08.22 11:37:56 MSK

Ответ на:

комментарий
от aol 08.08.22 11:50:50 MSK

дата тоже в порядке)

User01

(08.08.22 12:05:59 MSK)

  • Ссылка

Ответ на:

комментарий
от User01 08.08.22 11:21:28 MSK

Покажи выхлоп curl -v "https://mysite.com"

Сначала с того сервера, где не работает, потом с того, где работает. И вывод команды date — тоже с обоих серверов.

vbr

(08.08.22 13:32:10 MSK)

Последнее исправление: vbr 08.08.22 13:33:12 MSK
(всего

исправлений: 1)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от vbr 08.08.22 13:32:10 MSK

Ответ на:

комментарий
от User01 08.08.22 15:21:37 MSK

Ответ на:

комментарий
от User01 08.08.22 15:21:37 MSK

У меня скиллов не хватает понять, в чём проблема, может кто поумней поможет. Но однозначно какая-то проблема с TLS, причём нетривиальная. В макоси у меня есть родной openssl, есть из macports. Родной не соединяет, неродной соединяет. Это прям с одного компьютера.

https://pastebin.com/raw/b544MmRC

Как промежуточный вариант костыльного решения, если у тебя нет возможности настроить этот сервер, попробуй скачать curl поновей.

vbr

(08.08.22 15:45:23 MSK)

  • Ссылка

Ответ на:

комментарий
от aol 08.08.22 15:40:10 MSK

root@srv:~# sudo sed -e '/mozilla/DST_Root_CA_X3.crt/ s/^!*/!/' -i /etc/ca                                                                                        -certificates.conf ; sudo update-ca-certificates
Updating certificates in /etc/ssl/certs...
0 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d...
done.
root@srv:~#  wget https://csgoairlines.ru                                                                                                                            --2022-08-08 21:41:41--  https://csgoairlines.ru/
Resolving csgoairlines.ru (csgoairlines.ru)... 172.67.181.137, 104.21.18.93, 260                                                                                        6:4700:3031::ac43:b589, ...
Connecting to csgoairlines.ru (csgoairlines.ru)|172.67.181.137|:443... connected                                                                                        .
ERROR: The certificate of 'csgoairlines.ru' is not trusted.
ERROR: The certificate of 'csgoairlines.ru' hasn't got a known issuer.

не помогает к сожалению

User01

(08.08.22 21:42:37 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от User01 08.08.22 21:42:37 MSK

тогда вариантов у тебя осталось немного:

  1. обновить систему (или openssl в ней)
  2. игнорировать ошибку с сертификатом — wget --no-check-certificate

aol ★★★★★

(09.08.22 17:46:32 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от aol 09.08.22 17:46:32 MSK

систему обновлять боюсь, вдруг что-то полетит.openssl не получается обновить, удалял и снова ставил не помогло.
игнорировать если wget то можно, но я выше писал что это плагин в игровом сервере обращается к сайту, туда я это не подсуну, да и исходника плагина нет чтобы его подкоректировать

User01

(09.08.22 22:04:30 MSK)

  • Ссылка

I have the same symptom for f-droid.org:

% wget 'https://f-droid.org/F-Droid.apk'
--2020-06-03 14:10:18--  https://f-droid.org/F-Droid.apk
Resolving f-droid.org (f-droid.org)... 217.160.165.113, 148.251.140.42
Connecting to f-droid.org (f-droid.org)|217.160.165.113|:443... connected.
ERROR: The certificate of ‘f-droid.org’ is not trusted.
ERROR: The certificate of ‘f-droid.org’ has expired.

In my case (Debian 9 stretch), curl doesn’t work either:

% curl 'https://f-droid.org/F-Droid.apk'
curl: (60) SSL certificate problem: certificate has expired
More details here: https://curl.haxx.se/docs/sslcerts.html

Looking at wget source one can see the error comes from status flag returned by gnutls_certificate_verify_peers2. We can ask gnutls to show certificate verification details:

% gnutls-cli f-droid.org -p 443
Processed 151 CA certificate(s).
Resolving 'f-droid.org:443'...
Connecting to '217.160.165.113:443'...
- Certificate type: X.509
- Got a certificate list of 3 certificates.
- Certificate[0] info:
 - subject `CN=f-droid.org,OU=PositiveSSL,OU=Domain Control Validated', issuer `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', serial 0x02a8508e042b9f065fafadd87cd7d103, RSA key 2048 bits, signed using RSA-SHA256, activated `2019-09-17 00:00:00 UTC', expires `2020-09-16 23:59:59 UTC', key-ID `sha256:e97ccbf3c188b5cf69a83ed0fc39b001ce1688a62b573193cef3f74984c7d703'
    Public Key ID:
            sha1:638f93856e1f5edfcbd40c46d4160cff21b0713a
            sha256:e97ccbf3c188b5cf69a83ed0fc39b001ce1688a62b573193cef3f74984c7d703
    Public key's random art:
            +--[ RSA 2048]----+
            |           o o+o.|
            |            *...o|
            |           E ..+ |
            |         .  ... o|
            |        S .   o .|
            |       o *   . o.|
            |        * o .  .o|
            |       . + o .o. |
            |          o   .oo|
            +-----------------+

- Certificate[1] info:
 - subject `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', issuer `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', serial 0x7d5b5126b476ba11db74160bbc530da7, RSA key 2048 bits, signed using RSA-SHA384, activated `2018-11-02 00:00:00 UTC', expires `2030-12-31 23:59:59 UTC', key-ID `sha256:e1ae9c3de848ece1ba72e0d991ae4d0d9ec547c6bad1dddab9d6beb0a7e0e0d8'
- Certificate[2] info:
 - subject `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', issuer `CN=AddTrust External CA Root,OU=AddTrust External TTP Network,O=AddTrust AB,C=SE', serial 0x13ea28705bf4eced0c36630980614336, RSA key 4096 bits, signed using RSA-SHA384, activated `2000-05-30 10:48:38 UTC', expires `2020-05-30 10:48:38 UTC', key-ID `sha256:c784333d20bcd742b9fdc3236f4e509b8937070e73067e254dd3bf9c45bf4dde'
- Status: The certificate is NOT trusted. The certificate chain uses expired certificate. 
*** PKI verification of server certificate failed...

So the problem is the USERTrust RSA Certification Authority certificate supplied by the server f-droid.org. This is an intermediate cert signed by AddTrust External CA Root that expired 4 days ago.

The Debian ca-certificates package has a self-signed (root) certificate for USERTrust RSA Certification Authority:

% openssl x509 -inform PEM -in /usr/share/ca-certificates/mozilla/USERTrust_RSA_Certification_Authority.crt -text | grep -A2 Validity
    Validity
        Not Before: Feb  1 00:00:00 2010 GMT
        Not After : Jan 18 23:59:59 2038 GMT

…but gnutls is confused by the expired cert supplied by the server, hence the error.

In your case (mirrors.edge.kernel.org) the certificate chain is as follows:

% gnutls-cli mirrors.edge.kernel.org -p 443
Processed 151 CA certificate(s).
Resolving 'mirrors.edge.kernel.org:443'...
Connecting to '147.75.101.1:443'...
- Certificate type: X.509
- Got a certificate list of 3 certificates.
- Certificate[0] info:
 - subject `CN=*.edge.kernel.org', issuer `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', serial 0x00a34d0ccfbf4ea450fe030fd3378f5d68, RSA key 2048 bits, signed using RSA-SHA256, activated `2020-03-16 00:00:00 UTC', expires `2021-03-16 23:59:59 UTC', key-ID `sha256:f3746cf281b6453def23289054e75e26e157bfd9eed5252b76ffdc828b802e41'
    Public Key ID:
            sha1:72d8fc84d0dea848189bc3ff8eb1d47629fd72c0
            sha256:f3746cf281b6453def23289054e75e26e157bfd9eed5252b76ffdc828b802e41
    Public key's random art:
            +--[ RSA 2048]----+
            |                 |
            |       .         |
            |  .   . .        |
            | . =   * +       |
            |  * . o.S o      |
            |   + o =E+       |
            |    = = +..      |
            |   . * o...      |
            |    o.o  o.      |
            +-----------------+

- Certificate[1] info:
 - subject `CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB', issuer `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', serial 0x7d5b5126b476ba11db74160bbc530da7, RSA key 2048 bits, signed using RSA-SHA384, activated `2018-11-02 00:00:00 UTC', expires `2030-12-31 23:59:59 UTC', key-ID `sha256:e1ae9c3de848ece1ba72e0d991ae4d0d9ec547c6bad1dddab9d6beb0a7e0e0d8'
- Certificate[2] info:
 - subject `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', issuer `CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US', serial 0x01fd6d30fca3ca51a81bbc640e35032d, RSA key 4096 bits, signed using RSA-SHA384, activated `2010-02-01 00:00:00 UTC', expires `2038-01-18 23:59:59 UTC', key-ID `sha256:c784333d20bcd742b9fdc3236f4e509b8937070e73067e254dd3bf9c45bf4dde'
- Status: The certificate is trusted. 

Again we see USERTrust RSA Certification Authority, but here it’s a self-signed (root) certificate, not expired. I guess kernel.org did supply expired intermediate certificate too, but corrected under your hands. I think --no-dns-cache is irrelevant, mere coincidence.

Incidentally, Firefox displays https://f-droid.org just fine. Show page info / Security reveals new self-signed (root) USERTrust cert: Not after: 18 January 2038, 23:59:59 GMT. That is, Firefox ignored the expired intermediate USERTrust cert supplied by the server, used the valid root USERTrust cert available locally.

Resolution? The server webmaster should remove the obsolete intermediate certificate from the server configuration. In the meantime, use Firefox (or curl, if it works) instead of wget.

Update: as f-droid people pointed out, the gnutls bug is fixed already, the fix should be in Debian-security soon.

Понравилась статья? Поделить с друзьями:
  • Whirlpool awg 218 коды ошибок
  • Wf602w2bkwq ошибка 3е как исправить
  • Whirlpool dwh b00 коды ошибок
  • Wget ошибка нет доверия сертификату для
  • Whirlpool ошибка e02