- Работа с FTP из терминала Linux
- Основные FTP команды в Linux
- FTP соединение
- Команды для навигации
- Удаление файлов на ftp сервере
- Скачивание файлов с ftp
- Загрузка файлов на ftp сервер
- Connecting to FTP via the Linux command line
- 3 Answers 3
- How to use FTP from the command-line on Linux
- Install FTP CLI
- Ubuntu
- Debian
- Arch Linux
- Fedora
- OpenSUSE
- Generic Linux
- Connect to FTP server over CLI
- Download FTP files over CLI
- Upload FTP files over CLI
- Linux ftp connect console
Работа с FTP из терминала Linux
Иногда необходимо работать с FTP из консоли, когда под рукой нет доп. программ и FTP менеджеров. Обычно это бывает нужно что бы перемести сайт с одного хостинга на другой, да есть более правильный способ создать архив всех файлов:
И после забрать все wget -ом на новый хостинг.
Но так можно сделать только том случае если сайт с которого мы забираем архив еще торчит мордой в интернет, что бывает не всегда, например домен не продлен или ns сервера уже другие.
В таких случаях мы можем воспользоваться старым дедовским способом подключения к ftp прямо из терминала:
Попросит логин и пароль и мы в ftp.
Is — Выводит список файлов и директорий.
get — Скачивает файл, с удаленной машины.
mget — Скачивает файлы по маске (например mget * все файлы, mget *. php файлы php)
cd — Это здесь работает исключительно на удаленной машине.
lcd — тоже самое что cd но только для локальной машины (да да это у них разные вещи).
put — Заливает файл на удаленную машину.
mput — Заливает несколько файлов по маске (аналогично mget).
mkdir — Создает каталог.
rmdir — Удалить каталог.
delete — Удаляет файл.
bye — Завершает сеанс FTP–сервером.
binary — Устанавливает бинарный режим передачи файлов.
close — Завершает сеанс FTP и возвращается в контест командной строки FTP.
status — Статус FTP клиента.
Еще один вариант для маргиналов это примаунтить FTP диск:
выставляем на всякий случай максимальные права каталогу в который собираемся монтировать:
Теперь если вы дочитали до конца покажу простой вариант того же самого.
Понадобится Midnight Commander, если не установлен ставим:
Теперь переходим во вкладку Right/Left, без разницы выбираем «FTP link..» :
Адрес хоста можно вводить как что называется без ничего (он сам все попросит логин и пароль), так и как в скриншоте все и сразу
Единственный минус этого способа может быть отрисовка прогресса закачки файла , не проверял, но думаю она не много тормозит процесс в случае если файлов много, но обычно это не критично.
Источник
Основные FTP команды в Linux
FTP (File Transfer Protocol — протокол передачи файлов) — это популярный сетевой протокол, который используется для копирования файлов с одного компьютера на другой в локальной сети, либо в сети Интернет. FTP является одним из старейших прикладных протоколов, появившимся задолго до HTTP, и даже до TCP/IP, в 1971 году.
Протокол FTP уязвим, то есть FTP не может зашифровать свой трафик, все передачи — открытый текст, поэтому имена пользователей, пароли, команды и данные могут быть прочитаны кем угодно, способным перехватить пакет по сети. Для безопасной передачи данных, используется протокол SFTP (Secure File Transfer Protocol). В отличие от стандартного FTP он шифрует и команды, и данные, защищая пароли и конфиденциальную информацию от открытой передачи через сеть. По функциональности SFTP похож на FTP, но так как он использует другой протокол, клиенты стандартного FTP не могут связаться с SFTP-сервером и наоборот. Далее рассмотрим основные команды для работы с FTP программой.
FTP соединение
FTP клиент входит в большинство дистрибутивов Linux. Начнем с запуска программы и ftp соединением и, конечно, рассмотрим основные команды для скачивания с фтп-сервера и загрузки на фтп, создание директорий, удаление файлов и т.п. В этой статье опишем лишь основные команды, а в конце статьи приведем хелп и мануал из консоли — Вы всегда можете узнать о назначении команды и ее синтаксисе, а также обо всех доступных командах на конкретном ftp-сервере.
Для начала фтп соединения достаточно ввести команду ftp например:
После нажатия клавиши enter вывод команды будет следующим:
Другой способ для соединения — это запуск ftp из консоли, а после этого соединение с ftp-сервером с помощью команды open :
Кроме того, возможно соединиться и по ip:
Или с таким обращением ftp user@ftp.site.com , то есть:
Далее необходимо ввести логин и пароль ftp-соединения.
После успешной авторизации будет сообщение такого вида:
Из сообщения видно, что для передачи файлов используется двоичный (бинарный) тип передачи. Двоичный режим передачи файлов — это передача файлов в том виде, в котором они хранятся на FTP сервере. Режим Ascii (текстовый) используется для передачи только текстовых файлов. Вы можете вводить команды ascii или binary для переключения между режимами передачи. Бинарный режим (binary) необходимо использовать для всех нетекстовых типов файлов — изображения, архивы, программы и т.д.
Команды для навигации
Итак, перейдем к командам для навигации и перехода по каталогам ftp-сервера:
pwd — команда покажет текущую директорию на ftp-сервере:
ls — команда покажет список файлов и каталогов в текущей директории:
cd – команда для перехода в нужную директорию:
Проверяем командой pwd :
mkdir — создание новой директории (каталога):
rmdir — удаление директории (каталога):
Удаление файлов на ftp сервере
delete — удаляет файл на удаленном ftp сервере:
Скачивание файлов с ftp
get — скачать файл на локальную машину. get fileName или get fileName newFileName
Скачиваем file.zip на локальную машину как file2.zip:
С помощью команды get с удаленного ftp сервера файлы копируются в текущую локальную директорию. Чтобы изменить текущую локальную директорию нужно использовать команду lcd :
lcd – изменить текущую директорию на локальной машине:
Чтобы скачать несколько файлов с удаленного ftp сервера на локальную машину можно использовать команду mget :
Скачивание каждого файла необходимо подтверждать (да / нет) y/n .
Еще один вариант скачивания mget :
Загрузка файлов на ftp сервер
put — команда для загрузки одного файла на ftp сервер:
Для загрузки нескольких файлов сразу можно использовать команду mput :
Загрузку каждого файла необходимо подтверждать y / n (да / нет).
Еще один вариант команды mput :
Если на фтп загружаются файлы большого размера, то неплохо было бы наблюдать за ходом загрузки. Для этого можно использоваться команды hash и tick .
hash — команда после которой ftp будет печатать символ «#» каждые 1024 байт данных:
tick — команда будет отображать счетчик байтов:
Вот и весь базовый набор команд для работы с ftp в консоле. Для просмотра списка доступных команл на данном FTP сервере можно использовать команду help :
Также, можно получить короткую справку по каждой команде help :
И в завершение, две команды, которые выше quit или bye для закрытия ftp-сессии и выхода:
Подробную информацию с описанием команд можно получить с помощью man ftp в командной строке:
Источник
Connecting to FTP via the Linux command line
I need to upload files via FTP from the command line. I have this information: a URL, a username, a password, a port, and the fact that I am supposed to use passive mode.
How do I upload a file given this information?
Note that I am having to do this from a script, so I need to be able to enter this information automatically.
3 Answers 3
There’s many CLI (command line) clients out there. Most common is simply ftp . You’ve got ,
and «passive mode». Using ftp you should do:
-p switch means «use passive mode». Then you’ll be asked about your username and password. After successful login (server let you know about that), you are able to give some commands. Type help and press «enter» to get list of commands available. You can use e.g. cd , ls , mkdir ftp commands to change working directory (on the server), list its contents and create a new directory. If before running ftp you were in the same directory as you files you want to send, you can use put or mput command to start actual transfer. First command sends one file, second multiple files using globbing (e.g. mput *pdf will send all pdf files in current directory). To get simple help about command you can use help from within ftp app. I’d say that’s enough for starters. For the rest use man ftp or info ftp . To end ftp session type bye . There are other ways to do that but I think this one is just elegant :).
As for the other clients, some interesting choices were pointed here, but I personally use lftp . It’s just solid, good, flexible and easy to use ftp client. If you prefer more visual approach while still being under command line, you can go for mc or «Midnight Command». It’s general application file manager utilizing Norton Commander paradigm, but can be also used to access ftp servers.
Источник
How to use FTP from the command-line on Linux
Apr 11, 2019
Comment
Working with FTP from the command-line might sound trivial, as there are a lot of excellent FTP clients on Linux that provide a GUI to work with. Still, many users of the File Transfer Protocol use it over SSH and servers so that a GUI app won’t work.
There are a few useful command-line FTP clients on Linux. In fact, in the past, I talked about one great command-line app in my list of the best FTP clients for Linux. That said, in this post, we will not be focusing on that app, as it’s much too complicated for what we need it for; basic upload and download. Instead, we will use the standard GNU FTP client.
Note: the GNU FTP client will not work with SFTP or FTPS. It can only connect to FTP servers.
Install FTP CLI
The GNU FTP app is widely used, so, this package may already be pre-installed on quite a few distributions. That said, not every single distribution has the client pre-installed, so it’s a good idea to go over how to get it working before going over how to use it.
To install the FTP app on your Linux operating system, open up a terminal window by pressing the Ctrl + Alt + T or Ctrl + Shift + T keyboard combination. From there, follow the detailed instructions that correspond with the OS you are currently using.
Ubuntu
On Ubuntu Linux, the CLI FTP client is available in the “Ubuntu Main” software repository. To install it on your system, you must use the Apt terminal command.
Debian
The CLI FTP client has supported Debian Linux for a very long time. As a result, it’s easily installable via the “Debian Main” software repository.
To install the CLI FTP app on your Debian PC, use the Apt-get command below.
Arch Linux
Arch Linux users won’t be able to search the package repositories for an “FTP” package if they want to use this app, as the developers do not package the CLI FTP app separately. Instead, to use FTP from the command-line on Arch Linux, you must install the “inetutils” package with Pacman.
Fedora
The command-line FTP client is available to Fedora Linux users through the “Fedora x86_64” and “Fedora i386” software repositories. If you’re a Fedora user, install the package with the following Dnf command in a terminal window.
OpenSUSE
OpenSUSE users looking to use the CLI FTP client on their operating system will be happy to know that the program is installable on Leap 15.0, Leap 42.3 and Tumbleweed via the “OpenSUSE Oss All” software repository.
To start the installation on your SUSE system, launch a terminal window and use the Zypper command below.
Generic Linux
The standard command-line FTP client used on Linux that we will be covering in this article is part of the GNU Project. For this reason, it’s very easy to track down this app for all Linux operating systems out there.
To install the CLI FTP client on your Linux operating system, open up a terminal. Then, search for and install “ftp” or “inetutils”. Alternatively, if you can’t find the app anywhere in software sources, check out how to grab the source code from GNU.org.
Connect to FTP server over CLI
To start a new connection with your server in the FTP CLI application, go to the terminal and use the ftp command along with the IP address of the remote server.
Note: can’t figure out the remote IP address of your FTP server. Check out our guide about how to find out an IP address on Linux.
Assuming the address is successful, the FTP app will prompt the user to enter a username and password. Write in your server’s username and password, and you’ll gain access over CLI to the FTP server.
Download FTP files over CLI
Downloading files over FTP in the command-line is done with the get command. To start a download, try out the following command syntax.
Let the FTP client download the file(s) to your system. When successful, they’ll appear in the directory the terminal on your Linux PC started in (usually /home/username/).
Upload FTP files over CLI
Uploading files with the FTP command-line application uses the send command. To send a file or folder to a remote server, follow the command syntax below.
Sending files over FTP will take a few minutes. When the process is done, you’ll see it in the default upload directory on the remote server.
Источник
Linux ftp connect console
A quick guide to using ftp.
The standard ftp program is the original ftp client. It comes standard with most Linux distributions. It first appeared in 4.2BSD, which was developed by the University of California, Berkeley.
It’s easy to use ftp. Let’s say you want to connect to the anonymous ftp site metalab.unc.edu, to download the latest Linux kernel source.
At the command line, type:
The ftp program will attempt to connect to metalab.unc.edu. Another way to do this is to run ftp from the command line with no parameters, and use the open command, with the site name as an argument:
When you connect to an FTP site, it will ask you for a login (pressing enter will log in as your local user name, in this case, foo : We log in as anonymous or ftp , to get to the public archive.
Now, we enter a complete e-mail address as the password (this is what most public FTP sites request).
After a successful login, the following information is given to us:
After you log in to an ftp site, ftp will print out the file transfer type. In our case, it is binary. Binary mode transfers the files, bit by bit, as they are on the FTP server. Ascii mode, however, will download the text directly. You can type ascii or binary to switch between the types.
You want to download the kernel source, so you leave the file transfer type at binary. The binary type is also what you would use for any non-text files — such as graphic images, zip/gzip archives, executable programs, etc. If in doubt, use binary mode.
You do an ls to see a list of the files. The ls command on ftp servers is executed on the remote server, so the command line options that you can use with it vary from server to server. The most common options are generally available, check the manpage for ls for details.
If the ls command lists so many files that they scroll off the top of the screen, you can use Shift-PageUp to scroll up. This works in Linux console mode as well as in xterm or rxvt.
On public FTP archives, the downloadable resources are usually held in the /pub directory. In this example, you already know that the kernel sources are in the directory /pub/Linux/kernel , so you type the following to get into that directory:
The messages you see, which begin with «250», are information messages sent by the server. In this case, the ftp server is configured to automatically send you the README file when you cd into the directory.
Now, after doing another ls , you see that you want to cd into the v2.2 directory. You do yet another ls , and find the file you want to download. It is linux-2.2.13.tar.gz . So you type this:
The ftp program has started saving the remote file linux-2.2.13.tar.gz as the local file linux-2.2.13.tar.gz .
If you wanted to save it as the local file foo.tar.gz , you could have specified it like this:
If you want to download more than one file at a time, you’ll have to use the mget (multiple get) command. You can use mget together with a space-delimited list of filenames you want to download, or you can use wildcards with the mget command. For example:
Would get all files starting with the string «linux». Normally, mget will prompt you for each file before it downloads it. You can toggle this by using the prompt command.
Now let’s say you’ve written a piece of software, and you want to upload it to MetaLab to be included in their Linux software archive. First, you’d change to the /incoming directory (most public FTP servers have a directory, usually called incoming or uploads, where files can be uploaded), then you’d use the put command:
The put command works the same way as the get command, so you can use mput to upload multiple files at the same time. You can also upload a local file with a different filename on the server by specifying the remote filename and/or pathname as an argument.
What if the file foo.tar.gz is not in your current local directory when you try to upload it? You can switch local directories by using the lcd (local change directory) command:
The ftp client supports using the bang (!) to run local commands. For example, to get a listing of files in your current local directory, do this:
The way this works is that ftp calls the shell (specified in the $SHELL environment variable), and it is the shell which runs ls . Thus, you can run any command-line which works with your shell simply by prepending «!» to it (the default shell in most Linux distributions is bash, the Bourne Again SHell). Please note that !cd does not work as you would expect, this is why the lcd command exists.
Wouldn’t it be nice if you could watch the progress while you’re downloading a file with ftp? You can use the hash command to print out hash marks as you download a file:
As you can tell, ftp will print a hash mark for every 1024 bytes of data you download.
There is also a tick option.
There are many other ftp commands. If you have the permissions to do so (which you should, if you are connected to your own private shell account), you can make a directory on the remote server using the mkdir command. You can remove a file on the remote server using the delete command, or rmdir to remove a directory. You can also change file permissions using the chmod command.
For more elaborate information on using ftp, please see the online help in the ftp program (accessible by typing help with no arguments for a list of commands, or help for specific help on a command). You can also read the Unix man page for ftp by typing man ftp at your command prompt.
Источник