Download file from linux server

How to Download and Upload Files over SSH

SSH is the most secure protocol for accessing remote servers. It provides the highest level of end-to-end data security over communication channels. The SCP (Secure Copy) command uses the SSH protocol for copying files between remote and local servers.

The remote server must have a running SSH server. This tutorial will help you to understand download and upload files over SSH protocol.

Download file over SSH Protocol

Here are some useful examples for downloading files from the remote system over SSH protocol.

  • This will connect to example.com server with user “username” and copy the /backup/file.zip file to local system directory /local/dir. To use theis command replace the values as per your environment.
  • If the SSH is running on a non-standard port, You can specify the port using -P option with SCP command.
  • If your remote server required a private key to connect server, You can use -i followed by a private key file path to connect your server using the SCP command. This can be helpful for AWS servers.

Upload file using SSH

You can also upload files to the remote server using SSH protocol using the SCP command. Use the following example command for uploading files to the SSH server.

Similarity you can use -P switch to define port of the SSH server and -i to define private key for the user authentication.

Conclusion

In this tutorial, you have learned about transferring files between two systems over the SSH protocol.

Источник

Как скачать файл Linux

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

Что же делать, когда нужно скачать файл Linux через терминал? Для этого существует несколько утилит и даже консольных браузеров. В этой статье мы рассмотрим самые популярные способы загрузки файла в Linux, которые применяются наиболее часто. Рассмотрим примеры применения таких утилит и их возможности.

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

Утилита wget — это одна из самых популярных консольных утилит для загрузки файлов. Мы уже рассматривали как пользоваться этой утилитой в отдельной статье. С помощью wget можно сделать намного больше чем просто загрузить файл linux. Вы можете скачать все файлы со страницы или же полностью загрузить весь веб-сайт. Но сейчас нас будет интересовать только самая простая ситуация.

Чтобы скачать файл Linux консоль выполните такую команду:

$ wget адрес_файла

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

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

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

wget -O — http://www.tecmint.com/wp-content/scripts/Colorfull.sh | bash

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

wget -O script.sh http://www.tecmint.com/wp-content/scripts/Colorfull.sh

Только обратите внимание, что со скриптами, загруженными из интернета нужно быть аккуратными. Сначала проверяйте не совершают ли они каких-либо деструктивных действий в системе. Из особенностей wget можно отметить, что утилита поддерживает протоколы HTTP, HTTPS и FTP, а для шифрования может использоваться только GnuTLS или OpenSSL.

Читайте также:  Web client windows phone

Загрузка файла с помощью curl

Утилита curl предназначена для решения задач другого типа задач. Она больше подходит для отладки приложений и просмотра заголовков. Но иногда применяется и для загрузки файлов. По умолчанию, curl будет отправлять полученные данные сразу в стандартный вывод, поэтому она более удобна для загрузки скриптов:

curl http://www.tecmint.com/wp-content/scripts/Colorfull.sh | bash

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

curl -O https://github.com/torvalds/linux/archive/v4.11-rc6.tar.gz

Когда загрузка файла в linux будет завершена, он будет находится в текущей папке. Вывод утилиты состоит из нескольких колонок, по которым можно детально отследить как происходит процесс загрузки:

  • % — показывает на сколько процентов загрузка завершена на данный момент;
  • Total — полный размер файла;
  • Reсeived — количество полученных данных;
  • Xferd — количество отправленных на сервер данных, работает только при выгрузке файла;
  • Average Speed Dload — средняя скорость загрузки;
  • AVerage Speed Upload — скорость отдачи для выгрузки файлов;
  • Time Total — отображает время, которое уйдет на загрузку всего файла;
  • Time Spend — сколько времени потрачено на загрузку файла;
  • Time Left — время, которое осталось до конца загрузки файла;
  • Current Speed — отображает текущую скорость загрузки или отдачи.

Если вы хотите скачать файл из командной строки linux и сохранить его с произвольным именем, используйте опцию -o в нижнем регистре:

curl -o taglist.zip http://www.vim.org/scripts/download_script.php?src_id=7701

Например, если для этого файла не задать имя, то он запишется с именем скрипта, а это не всегда удобно. Если остановиться на отличиях curl от wget, то здесь поддерживается больше протоколов: FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS, FILE, POP3, IMAP, SMTP, RTMP и RTSP, а также различные виды шифрования SSL.

Скачивание файла с помощью aria2

Консольная утилита aria2 — это еще более сложный загрузчик файлов, чем даже curl. Здесь поддерживаются такие протоколы, как HTTP, HTTPS, FTP, SFTP, BitTorrent и Metalink. Поддержка BitTorrent позволяет загружать файлы и раздавать их даже по сети Torrent. Также утилита примечательна тем, что может использовать несколько каналов для загрузки файлов чтобы максимально использовать пропускную способность сети.

Например, чтобы скачать файл используйте такую команду:

Здесь тоже будет отображаться небольшой статус-бар с подробной информацией про состояние загрузки. Чтобы начать загрузку торрента. достаточно передать торрент файл или magnet ссылку:

aria2c http://example.org/mylinux.torrent
$ aria2c ‘magnet:?xt=urn:btih:248D0A1CD08284299DE78D5C1ED359BB46717D8C’

Еще одна ситуация, когда вам нужно скачать файл из командной строки linux, вы знаете где его найти, но у вас нет прямой ссылки. Тогда все ранее описанные утилиты не помогут. Но вы можете использовать один из консольных браузеров, например, elinks. Если эта программа еще не установлена, то вы можете найти ее в официальных репозиториях своих дистрибутивов.

Запустите браузер, например, с помощью команды:

В первом окне нажмите Enter:

Затем введите URL страницы, например, не будем далеко ходить и снова скачаем ядро с kernel.org:

Когда вы откроете сайт, останется только выбрать URL для загрузки:

Далее выберите что нужно сделать с файлом, например, сохранить (save), а также выберите имя для нового файла:

В следующем окне вы увидите информацию о состоянии загрузки:

Выводы

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

Источник

How to Download a File from a Server with SSH / SCP

Users can securely download a file from any remote server with SSH by using the scp tool at the command line. Essentially this means you can have a file stored securely on a remote server and transfer it to local storage without having to expose that file to the outside world, because scp offers the same level of security and requires the same authentication that ssh does.

Securely downloading files with scp is aimed primarily at advanced users who are using ssh and the command line regularly in either macOS X, bsd, or linux. For those with adequate command line experience, using ssh and scp to download remote files is easy and, conveniently, after the file transfer has completed, the remote connection will end. This makes scp preferential to sftp for quick file downloads, though you could obviously use sftp if you wanted to as well.

Читайте также:  Twice os puppy linux rus vistape

Downloading a File from Remote Server with SSH Secure Copy

This assumes the remote server has ssh active, and if you’re able to ssh into the machine then it will have likely have scp active as well. If you don’t have a remote server to try this with, you can try it out between Mac OS X machines or with localhost if you enable ssh and Remote Login on the Mac beforehand.

The basic syntax to use scp (secure copy) for securely downloading remote files is as follows, replacing user, server, path, and target as appropriate:

scp user@server:/path/to/remotefile.zip /Local/Target/Destination

For example, to download a file to the local desktop named “filename.zip” located in the home directory of remote user “osxdaily” on server IP 192.168.0.45, the syntax would be as follows:

/Desktop/
Password:
filename.zip 100% 126 10.1KB/s 00:00
%

Assuming authentication is correct, the target file will immediately start to download to the target destination, offering a percentage completion, download speed, and elapsed transfer time as the file download proceeds.

As usual with the command line, it’s important to specify exact syntax.

If the file or path has a space in the name, you can use quotations or escaping on the path like so:

scp osxdaily@192.168.0.45:»/some remote directory/filename.zip»

scp can also be used to securely place a file on a remote server by adjusting the syntax as well, but we’re focusing on downloading a file rather than uploading files here.

If you’re new to ssh and testing this out yourself, and if you have never connected to the remote server before, you will be asked to confirm whether or not you wish to actually connect to the remote machine. This looks like so, and requires a ‘yes’ or ‘no’ answer before the download begins.
% scp osxdaily@192.168.0.4:filename.zip

/Desktop/
The authenticity of host ‘192.168.0.4 (192.168.0.4)’ can’t be established.
ECDSA key fingerprint is SHA256:31WalRuSLR83HALK83AKJSAkj972JJA878NJHAH3780.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘192.168.0.4’ (ECDSA) to the list of known hosts.
Password:
filename.zip 100% 126 0.1KB/s 00:00
%

Again, assuming the connection is approve and the login is successful, the remote file will download from the target server to the localhost.

You can also use scp to download multiple files from a remote server:

Using ssh for remote file downloads like this is most appropriate for secure transfers which require authentication. Sure you can also downloading files with curl or wget from remote servers, but files accessible with curl and wget tend to be accessible from the outside world as well, whereas ssh and scp requires authentication or a key, and uses 3DES encryption, making it considerably more secure.

Источник

How to Download a File on Ubuntu Linux using the Command Line

Linux Command line offers more flexibility and control than GUI. A number of people prefer to use the command line than GUI because it is easier and quicker to use than GUI. Using the command line, it is easier to automate the tasks using one line. In addition, it utilizes fewer resources than GUI.

Downloading files is a routine task that is normally performed every day that can include file types like ZIP, TAR, ISO, PNG, etc. you can simply and quickly perform this task using the command line terminal. It requires only using your keyboard. So today, I will show you how you can download a file using the command line in Linux. There are normally two known ways to do this, that is using wget and curl utility. For this article, I am using Ubuntu 20.04 LTS for describing the procedure. But the same commands will work on other Linux distributions like Debian, Gentoo, and CentOS too.

Download files using Curl

Curl can be used to transfer data over a number of protocols. It supports many protocols including HTTP, HTTPS, FTP, TFTP, TELNET, SCP, etc. using Curl, you can download any remote files. It supports pause and resumes functions as well.

To get started with, first, you need to install the curl.

Install curl

Launch command line application in Ubuntu that is Terminal by pressing the Ctrl+Alt+T key combinations. Then enter the below command to install curl with sudo.

When prompted for a password, enter sudo password.

Once the installation is complete, enter the below command to download a file.

Download and save the file using the source file name

To save the file with the same name as the original source file on the remote server, use –O (uppercase O) followed by curl as below:

Читайте также:  Combining files in windows

Instead of -O, you can also specify, “–remote-name” as shown below. Both work the same.

Download and save the file with a different name

If you want to download the file and save it in a different name than the name of the file in the remote server, use -o (lower-case o) as shown below. This is helpful when the remote URL doesn’t contain the file name in the URL as shown in the example below.

[filename] is the new name of the output file.

Download multiple files

To download multiple files, enter the command in the following syntax:

Download files from an FTP Server

To download a file from FTP server, enter the command in following syntax:

To download files from user authenticated FTP servers, use the following syntax:

Pause and resume download

While downloading a file, you can manually pause it using Ctrl+C or sometimes it automatically gets interrupted and stopped due to any reason, you can resume it. Navigate to the same directory where you have previously downloaded the file then enter the command in the following syntax:

Download files using Wget

Using wget, you can download files and contents from Web and FTP servers. Wget is a combination of www and the get. It supports protocols like FTP, SFTP, HTTP, and HTTPS. Also it supports recursive download feature. This feature is very useful if you want to download an entire website for offline viewing or for generating a backup of a static website. In addition, you can use it to retrieve content and files from various web servers.

Install wget

Launch command line application in Ubuntu that is terminal by pressing the Ctrl+Alt+T key combinations. Then enter the below command to install wget with sudo.

When prompted for a password, enter the sudo password.

Download file or webpage using wget

To download a file or a webpage, open the Terminal and enter the command in the following syntax:

To save a single webpage, enter the command in the following syntax:

Download files with a different name

If you want to download and save the file with a different name than the name of the original remote file, use -O (upper-case O) as shown below. This is helpful especially when you are downloading a webpage that automatically get saved with the name “index.html”.

To download a file with a different name, enter the command in the following syntax:

Download files through FTP

To download a file from an FTP server, type the command in the following syntax:

To download files from user authenticated FTP servers, use the below syntax:

Recursively download files

You can use the recursive download feature to download everything under the specified directory whether a website or an FTP site. To use the recursive download feature, enter the command in the below syntax:

Download multiple files

You can use wget to download multiple files. Make a text file with a list of file URLs, then use the wget command in the following syntax to download that list.

For instance, I have the text file named “downloads.txt” in which there is a list of two URLs that I want to download using wget. You can see my text file content in the below image:

I will use the below command to download the file links contained in the text file:

You can see that it is downloading both links one by one.

Pause and Resume download

You can Press Ctrl + C to pause a download. To resume a paused download, go to the same directory where you were downloading the file previously and use –c option after wget as in the below syntax:

Using the above command, you will notice that your download has resumed from where it was paused.

So in this article, we have discussed the basic usage of two command-line methods using which you can download a file. One thing to Note that if you do not specify a directory while downloading a file, the files will be downloaded in the current directory in which you are working.

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

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