Linux upload file to https

Содержание
  1. How to download a file with curl on Linux/Unix command line
  2. How to download a file with curl command
  3. Installing curl on Linux or Unix
  4. Verify installation by displaying curl version
  5. Downloading files with curl
  6. Resuming interrupted downloads with curl
  7. How to get a single file without giving output name
  8. Dealing with HTTP 301 redirected file
  9. Downloading multiple files or URLs using curl
  10. Grab a password protected file with curl
  11. Downloading file using a proxy server
  12. Examples
  13. Getting HTTP headers information without downloading files
  14. How do I skip SSL skip when using curl?
  15. Rate limiting download/upload speed
  16. Setting up user agent
  17. Upload files with CURL
  18. Make curl silent
  19. Conclusion
  20. Securely transfer files between two hosts using HTTPS in Linux
  21. Install Apache
  22. Transfer.sh – Easy File Sharing from Linux Commandline
  23. Upload a Single File
  24. Download a File
  25. Upload Multiple Files
  26. Encrypt Files Before Transfer
  27. Use Wget Tool
  28. Create Alias Command
  29. If You Appreciate What We Do Here On TecMint, You Should Consider:
  30. Команда Wget в Linux с примерами
  31. Установка Wget
  32. Установка Wget в Ubuntu и Debian
  33. Установка Wget на CentOS и Fedora
  34. Синтаксис команды Wget
  35. Как скачать файл с помощью wget
  36. Сохранение загруженного файла под другим именем
  37. Загрузка файла в определенный каталог
  38. Ограничение скорости загрузки
  39. Возобновление загрузки
  40. Загрузка в фоновом режиме
  41. Смена пользовательского агента Wget
  42. Загрузка нескольких файлов
  43. Скачивание через FTP
  44. Создание зеркала веб-сайта
  45. Пропуск проверки сертификата
  46. Загрузка на стандартный вывод
  47. Выводы

How to download a file with curl on Linux/Unix command line

How to download a file with curl command

The basic syntax:

  1. Grab files with curl run: curl https://your-domain/file.pdf
  2. Get files using ftp or sftp protocol: curl ftp://ftp-your-domain-name/file.tar.gz
  3. You can set the output file name while downloading file with the curl, execute: curl -o file.pdf https://your-domain-name/long-file-name.pdf
  4. Follow a 301-redirected file while downloading files with curl, run: curl -L -o file.tgz http://www.cyberciti.biz/long.file.name.tgz

Let us see some examples and usage about the curl to download and upload files on Linux or Unix-like systems.

Installing curl on Linux or Unix

By default curl is installed on many Linux distros and Unix-like systems. But, we can install it as follows:
## Debian/Ubuntu Linux use the apt command/apt-get command ##
$ sudo apt install curl
## Fedora/CentOS/RHEL users try dnf command/yum command ##
$ sudo dnf install curl
## OpenSUSE Linux users try zypper command ##
$ sudo zypper install curl

Verify installation by displaying curl version

Type:
$ curl —version
We see:

Downloading files with curl

The command syntax is:
curl url —output filename
curl https://url -o output.file.name
Let us try to download a file from https://www.cyberciti.biz/files/sticker/sticker_book.pdf and save it as output.pdf
curl https://www.cyberciti.biz/files/sticker/sticker_book.pdf -o output.pdf
OR
curl https://www.cyberciti.biz/files/sticker/sticker_book.pdf —output output.pdf

The -o or —output option allows you to give the downloaded file a different name. If you do not provide the output file name curl will display it to the screen. Let us say you type:
curl —output file.html https://www.cyberciti.biz
We will see progress meter as follows:

The outputs indicates useful information such as:

  • % Total : Total size of the whole expected transfer (if known)
  • % Received : Currently downloaded number of bytes
  • % Xferd : Currently uploaded number of bytes
  • Average Dload : Average transfer speed of the entire download so far, in number of bytes per second
  • Speed Upload : Average transfer speed of the entire upload so far, in number of bytes per second
  • Time Total : Expected time to complete the operation, in HH:MM:SS notation for hours, minutes and seconds
  • Time Spent : Time passed since the start of the transfer, in HH:MM:SS notation for hours, minutes and seconds
  • Time Left : Expected time left to completion, in HH:MM:SS notation for hours, minutes and seconds
  • Current Speed : Average transfer speed over the last 5 seconds (the first 5 seconds of a transfer is based on less time, of course) in number of bytes per second

Resuming interrupted downloads with curl

Pass the -C — to tell curl to automatically find out where/how to resume the transfer. It then uses the given output/input files to figure that out:
## Restarting an interrupted download is important task too ##
curl -C — —output bigfilename https://url/file

How to get a single file without giving output name

You can save output file as it is i.e. write output to a local file named like the remote file we get. For example, sticker_book.pdf is a file name for remote URL https://www.cyberciti.biz/files/sticker/sticker_book.pdf. One can save it sticker_book.pdf directly without specifying the -o or —output option by passing the -O (capital
curl -O https://www.cyberciti.biz/files/sticker/sticker_book.pdf

Downloading files with curl in a single shot

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard
Читайте также:  Install mac os x lion app

Join Patreon

Dealing with HTTP 301 redirected file

The remote HTTP server might send a different location status code when downloading files. For example, HTTP URLs are often redirected to HTTPS URLs with HTTP/301 status code. Just pass the -L follow the 301 (3xx) redirects and get the final file on your system:
curl -L -O http ://www.cyberciti.biz/files/sticker/sticker_book.pdf

Downloading multiple files or URLs using curl

Try:
curl -O url1 -O url2
curl -O https://www.cyberciti.biz/files/adduser.txt \
-O https://www.cyberciti.biz/files/test-lwp.pl.txt
One can use the bash for loop too:

How to download a file using curl and bash for loop

Grab a password protected file with curl

Try any one of the following syntax
curl ftp://username:passwd@ftp1.cyberciti.biz:21/path/to/backup.tar.gz
curl —ftp-ssl -u UserName:PassWord ftp://ftp1.cyberciti.biz:21/backups/07/07/2012/mysql.blog.sql.tar.gz
curl https://username:passwd@server1.cyberciti.biz/file/path/data.tar.gz
curl -u Username:Password https://server1.cyberciti.biz/file/path/data.tar.gz

Downloading file using a proxy server

Again syntax is as follows:
curl -x proxy-server-ip:PORT -O url
curl -x ‘http://vivek:YourPasswordHere@10.12.249.194:3128’ -v -O https://dl.cyberciti.biz/pdfdownloads/b8bf71be9da19d3feeee27a0a6960cb3/569b7f08/cms/631.pdf

How to use curl command with proxy username/password

Examples

curl command can provide useful information, especially HTTP headers. Hence, one can use such information for debugging server issues. Let us see some examples of curl commands. Pass the -v for viewing the complete request send and response received from the web server.
curl -v url
curl -o output.pdf -v https://www.cyberciti.biz/files/sticker/sticker_book.pdf

Getting HTTP headers information without downloading files

Another useful option is to fetch HTTP headers. All HTTP-servers feature the command HEAD which this uses to get nothing but the header of a document. For instance, when you want to view the HTTP response headers only without downloading the data or actual files:
curl -I url
curl -I https://www.cyberciti.biz/files/sticker/sticker_book.pdf -o output.pdf

Getting header information for given URL

How do I skip SSL skip when using curl?

If the remote server has a self-signed certificate you may want to skip the SSL checks. Therefore, pass pass the -k option as follows:
curl -k url
curl -k https://www.cyberciti.biz/

Rate limiting download/upload speed

You can specify the maximum transfer rate you want the curl to use for both downloads and uploads files. This feature is handy if you have a limited Internet bandwidth and you would like your transfer not to use your entire bandwidth. The given speed is measured in bytes/second, unless a suffix is appended. Appending ‘k’ or ‘K’ will count the number as kilobytes, ‘m’ or ‘M’ makes it megabytes, while ‘g’ or ‘G’ makes it gigabytes. For Examples: 200K, 3m and 1G:
curl —limit-rate url
curl —limit-rate 200 https://www.cyberciti.biz/
curl —limit-rate 3m https://www.cyberciti.biz/

Setting up user agent

Some web application firewall will block the default curl user agent while downloading files. To avoid such problems pass the -A option that allows you to set the user agent.
curl -A ‘user agent name’ url
curl -A ‘Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0’ https://google.com/

Upload files with CURL

The syntax is as follows to upload files:
curl -F «var=@path/to/local/file.pdf» https://url/upload.php
For example, you can upload a file at

/Pictures/test.png to the server https://127.0.0.1/app/upload.php which processes file input with form parameter named img_file, run:
curl -F «img_file=@

/Pictures/test.png» https://127.0.0.1/app/upload.php
One can upload multiple files as follows:
curl -F «img_file1=@

/Pictures/test-1.png» \
-F «img_file2=@

Make curl silent

Want to make hide progress meter or error messages? Try passing the -s or —slient option to turn on curl quiet mode:
curl -s url
curl —silent —output filename https://url/foo.tar.gz

Conclusion

Like most Linux or Unix CLI utilities, you can learn much more about curl command by visiting this help page.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Securely transfer files between two hosts using HTTPS in Linux

Table of Contents

How to configure apache http server to transfer files? Steps to configure apache HTTP server over TLS/SSL to transfer files. How to configure Apache server using TLS/SSL to upload and transfer file using curl. How to transfer files over https? How to upload file using curl to an HTTPS server. How to configure HTTP server using LIMIT to allow download and upload of a file or directory using curl in Linux.

Earlier I had written an article with 5 different commands to securely transfer files between multiple hosts. Now you can consider HTTPS also as one of the possible options to securely transfer files (upload and download) between multiple hosts over the network.

Читайте также:  Открыть exe файл линуксе

In this article I will share the steps to configure an apache HTTP server using TLS/SSL and then transfer file to HTTPS server using curl (uploading a file). I am using CentOS 7.4 to demonstrate the steps from this article. I will configure a very basic HTTP server with not much customization as Apache can be very complex if we enter into using all the features. But since we are concentrating on configuring an HTTPS server to upload and download a file (transfer a file), we will configure a basic HTTPS server.

Install Apache

The very first thing we have to do is install the apache rpm before we start configuring our web server.

Next we will create some dummy file and directory and publish it on our webserver.

I am creating an alias /web which will redirect to /var/www/html/secret . Also we have defined directive. The directive limits the scope of the enclosed directives by URL. It is similar to the directive, and starts a subsection which is terminated with a directive. sections are processed in the order they appear in the configuration file, after the sections and .htaccess files are read, and after the sections.

The purpose of the directive is to restrict the effect of the access controls to the nominated HTTP methods. For all other methods, the access restrictions that are enclosed in the bracket will have no effect.

Next restart the httpd services to make the changes affect.

Check the service status.

Enable the httpd service to make it reboot persistent.

Источник

Transfer.sh – Easy File Sharing from Linux Commandline

Transfer.sh is a simple, easy and fast service for file sharing from the command-line. It allows you to upload up to 10GB of data and files are stored for 14 days, for free.

You can maximize amount of downloads and it also supports encryption for security. It supports the local file system (local); together with s3 (Amazon S3), and gdrive (Google Drive) cloud storage services.

Transfer.sh – Easy File Sharing in Linux Terminal

It is designed to be used with the Linux shell. In addition, you can preview your files in the browser. In this article, we will show how to use transfer.sh in Linux.

Upload a Single File

To upload a file, you can use the curl program with the —upload-file option as shown.

Download a File

To download your file, a friend or colleague can run the following command.

Upload Multiple Files

You can upload multiple files at once, for example:

Encrypt Files Before Transfer

To encrypt your files before the transfer, use the following command (you must have the gpg tool installed on the system). You will be prompted to enter a password to encrypt the file.

To download and decrypt the above file, use the following command:

Use Wget Tool

Transfer.sh also supports the wget tool. To upload a file, run.

Create Alias Command

To use the short transfer command, add an alias to your .bashrc or .zshrc startup file.

Then add the lines below in it (you can only choose one tool, either curl or wget).

Save the changes and close the file. Then source it to apply the changes.

From now on, you upload a file using the transfer command as shown.

To setup your own sharing server instance, download the program code from the Github repository.

You can find more information and sample use cases in the project homepage: https://transfer.sh/

Transfer.sh is a simple, easy and fast service for file sharing from the command-line. Share your thoughts about it with us via the feedback form below. You can also tell us about similar services that you have come across – we’ll be grateful.

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.

Источник

Команда Wget в Linux с примерами

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

Читайте также:  Avermedia mr 800 usb radio драйвер для windows 10

В этой статье показано, как использовать команду wget на практических примерах и подробных объяснениях наиболее распространенных параметров.

Установка Wget

Пакет wget предустановлен на сегодняшний день в большинстве дистрибутивов Linux.

Чтобы проверить, установлен ли пакет Wget в вашей системе, откройте консоль, введите wget и нажмите Enter. Если у вас установлен wget, система напечатает wget: missing URL . В противном случае он напечатает wget command not found .

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

Установка Wget в Ubuntu и Debian

Установка Wget на CentOS и Fedora

Синтаксис команды Wget

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

Выражения утилиты wget имеют следующую форму:

  • options — Параметры Wget
  • url — URL-адрес файла или каталога, который вы хотите скачать или синхронизировать.

Как скачать файл с помощью wget

В простейшей форме, при использовании без какой-либо опции, wget загрузит ресурс, указанный в [url], в текущий каталог.

В следующем примере мы загружаем tar-архив ядра Linux:

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

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

Чтобы отключить вывод, используйте параметр -q .

Если файл уже существует, wget добавит .N (число) в конец имени файла.

Сохранение загруженного файла под другим именем

Чтобы сохранить загруженный файл под другим именем, передайте параметр -O за которым следует выбранное имя:

Приведенная выше команда сохранит последний zip-файл hugo с GitHub как latest-hugo.zip вместо его исходного имени.

Загрузка файла в определенный каталог

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

Приведенная выше команда сообщает wget нужно сохранить iso-файл CentOS 7 в каталог /mnt/iso .

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

Чтобы ограничить скорость загрузки, используйте параметр —limit-rate . По умолчанию скорость измеряется в байтах в секунду. Добавьте k для килобайт, m для мегабайт и g для гигабайт.

Следующая команда загрузит двоичный файл Go и ограничит скорость загрузки до 1 МБ:

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

Возобновление загрузки

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

В следующем примере мы возобновляем загрузку iso-файла Ubuntu 18.04:

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

Загрузка в фоновом режиме

Для загрузки в фоновом режиме используйте параметр -b . В следующем примере мы загружаем iso-файл OpenSuse в фоновом режиме:

По умолчанию вывод перенаправляется в файл wget-log в текущем каталоге. Чтобы посмотреть статус загрузки, используйте команду tail :

Смена пользовательского агента Wget

Иногда при загрузке файла удаленный сервер может быть настроен на блокировку агента пользователя Wget. В подобных ситуациях для эмуляции другого браузера передайте параметр -U .

Приведенная выше команда wget-forbidden.com Firefox 60, запрашивающий страницу с wget-forbidden.com

Загрузка нескольких файлов

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

В следующем примере показано, как загрузить iso-файлы Arch Linux, Debian и Fedora, используя URL-адреса, указанные в linux-distros.txt :

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

Скачивание через FTP

Чтобы загрузить файл с FTP-сервера, защищенного паролем, укажите имя пользователя и пароль, как показано ниже:

Создание зеркала веб-сайта

Чтобы создать зеркало веб-сайта с помощью wget , используйте параметр -m . Это создаст полную локальную копию веб-сайта, следуя и загружая все внутренние ссылки, а также ресурсы веб-сайта (JavaScript, CSS, изображения).

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

Параметр -k заставит wget преобразовать ссылки в загруженных документах, чтобы сделать их пригодными для локального просмотра. Параметр -p сообщает wget нужно загрузить все необходимые файлы для отображения HTML-страницы.

Пропуск проверки сертификата

Если вы хотите загрузить файл по HTTPS с хоста с недействительным сертификатом SSL, используйте параметр —no-check-certificate :

Загрузка на стандартный вывод

В следующем примере wget незаметно (флаг -q ) загрузит и выведет последнюю версию WordPress на стандартный вывод (флаг -O — ) и направит ее в утилиту tar , которая распакует архив в каталог /var/www .

Выводы

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

Чтобы узнать больше о Wget, посетите страницу руководства GNU wget .

Источник

Оцените статью