Перейти к содержимому

Как поднять ftp сервер на ubuntu

  • автор:

How to create an FTP server on Ubuntu?

Sujit Patel

File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host to another over a TCP-based network, such as the internet. An FTP server is a computer that is running FTP server software and is connected to a network. It stores and manages files that can be accessed and transferred over the network using FTP clients. FTP servers are often used to transfer files between computers or to transfer large files that are too large to be sent as email attachments.

To access an FTP server, you will need an FTP client, which is a piece of software that allows you to connect to and transfer files from an FTP server. There are many FTP clients available, both free and paid, and they can be used on a variety of operating systems. Once you have an FTP client, you can connect to the FTP server by entering the server’s address, your username, and your password. From there, you can browse the files and directories on the server, upload and download files, and perform other file-related tasks.

Overview:

— Update system packages

— Install vsftpd Server on Ubuntu

— Backup Configuration Files

— Create FTP User

— Configure and secure vsftpd server

— Restart vsftpd server (FTP)

Steps:

1. Update system packages

To update your repositories run the below command in terminal

2. Install vsftpd Server(FTP) on Ubuntu

To install vsftpd, run below command

3. Backup Configuration Files

Before making any changes, make sure to back up your configuration files. Run below command to create backup.

4. Create FTP User

Create a new FTP user using the below command.

you’ll be prompted to create a password for the user ftp-user account.

Note: Make sure to allow access on Port 20 and Port 21 in your cloud provider firewall. These are the listening ports for the FTP service.

5. Configure and secure vsftpd server

Create vsftpd.conf file with the below content

To change the FTP home directory, enter the following.

6. Restart vsftpd server (FTP)

Restart the vsftpd service to apply the changes.

you can check status by using below command.

Run the below command to start FTP server on system startup.

Note: To access you can use FTP Client tools like FileZilla, WinSCP, or a built-in ftp command line utility.

Setup FTP Server with VSFTPD on Ubuntu 20.04

FTP (File Transfer Protocol) is a standard network protocol used to transfer files to and from a remote network. There are several open-source FTP servers available for Linux. The most known and widely used are PureFTPd , ProFTPD , and vsftpd . We’ll be installing vsftpd (Very Secure Ftp Daemon), a stable, secure, and fast FTP server. We will also show you how to configure the server to restrict users to their home directory and encrypt the entire transmission with SSL/TLS.

Although FTP is a very popular protocol, for more secure and faster data transfers, you should use SCP or SFTP .

Installing vsftpd on Ubuntu 20.04

The vsftpd package is available in the Ubuntu repositories. To install it, execute the following commands:

The ftp service will automatically start once the installation process is complete. To verify it, print the service status:

The output should show that the vsftpd service is active and running:

Configuring vsftpd

The vsftpd server configuration is stored in the /etc/vsftpd.conf file.

Most of the server settings are well documented inside the file. For all available options, visit the vsftpd documentation page.

In the following sections, we will go over some important settings needed to configure a secure vsftpd installation.

Start by opening the vsftpd configuration file:

1. FTP access

We’ll allow access to the FTP server only to the local users. Search for the anonymous_enable and local_enable directives in /etc/vsftpd.conf and verify your configuration match to lines below:

2. Enabling uploads

Locate and uncomment the write_enable directive to allow filesystem changes, such as uploading and removing files:

3. Chroot jail

To prevent local FTP users to access files outside of their home directories, uncomment the lne starting with chroot_local_user:

By default, for security reasons, when chroot is enabled, vsftpd will refuse to upload files if the directory that the users are locked in is writable.

Use one of the solutions below to allow uploads when chroot is enabled:

  • Method 1. — The recommended option is to keep the chroot feature enabled and configure FTP directories. In this example, we will create an ftp directory inside the user home, which will serve as the chroot and a writable uploads directory for uploading files:
  • Method 2. — Another option is to enable the allow_writeable_chroot directive:

Use this option only if you must grant writable access to your user to its home directory.

4. Passive FTP Connections

By default, vsftpd uses active mode. To use passive mode, set the minimum and maximum range of ports:

You can use any port for passive FTP connections. When the passive mode is enabled, the FTP client opens a connection to the server on a random port in the range you have chosen.

5. Limiting User Login

You can configure vsftpd to permit only certain users to log in. To do so, add the following lines at the end of the file:

When this option is enabled, you need to explicitly specify which users can log in by adding the user names to the /etc/vsftpd.user_list file (one user per line).

6. Securing Transmissions with SSL/TLS

To encrypt the FTP transmissions with SSL/TLS, you’ll need to have an SSL certificate and configure the FTP server to use it.

You can use an existing SSL certificate signed by a trusted Certificate Authority or create a self-signed certificate. If you have a domain or subdomain pointing to the FTP server’s IP address, you can quickly generate a free Let’s Encrypt SSL certificate. We will generate a 2048-bit private key and self-signed SSL certificate that will be valid for ten years:

Both the private key and the certificate will be saved in the same file.

Once the SSL certificate is created open the vsftpd configuration file:

Find the rsa_cert_file and rsa_private_key_file directives, change their values to the pam file path and set the ssl_enable directive to YES:

If not specified otherwise, the FTP server will use only TLS to make secure connections.

Restart the vsftpd Service

Once you are done editing, the vsftpd configuration file (excluding comments) should look something like this:

Save the file and restart the vsftpd service for changes to take effect:

Opening the Firewall

If you are running a UFW firewall , you’ll need to allow FTP traffic.

To open port 21 (FTP command port), port 20 (FTP data port), and 30000-31000 (Passive ports range), run the following commands:

Создание FTP-сервера в Linux

Как создать FTP-сервер в Linux

Передача файлов в сети осуществляется благодаря правильно настроенному FTP-серверу. Такой протокол работает с применением TCP по архитектуре клиент-сервер и задействует различные сетевые соединения для обеспечения передачи команд между подключенными узлами. Пользователи, которые подключились к определенному хостингу, сталкиваются с надобностью настройки личного FTP-сервера по требованиям компании, предоставляющей услуги обеспечения работы сайта или другого обеспечения. Далее мы продемонстрируем, как создается такой сервер в Linux на примере одной из утилит.

Создаем FTP-сервер в Linux

Сегодня мы будем использовать инструмент под названием VSftpd. Преимущества такого FTP-сервера в том, что он по умолчанию работает на многих ОС, обслуживает официальные репозитории различных дистрибутивов Linux и относительно просто настраивается для корректного функционирования. К слову, на ядре Линукс официально применяется именно этот FTP, и многие хостинги рекомендуют ставить VSftpd. Поэтому давайте обратим внимание на пошаговый процесс инсталляции и настройки необходимых компонентов.

Шаг 1: Установка VSftpd

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

Переход к взаимодействию с консолью в операционной системе Linux

    Откройте «Терминал» любым удобным методом, например, через меню.

Обращаем внимание обладателей CentOS, которые задействуют выделенный виртуальный сервер от любого хостинга. Вам потребуется произвести обновление модуля ядра ОС, поскольку без этой процедуры во время инсталляции отобразится критическая ошибка. Последовательно вводите такие команды:

yum update
rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-2.el7.elrepo.noarch.rpm
yum install yum-plugin-fastestmirror
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-3.15.6-1.el7.elrepo.x86_64.rpm
yum install kernel-ml-3.15.6-1.el7.elrepo.x86_64.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-devel-3.15.6-1.el7.elrepo.x86_64.rpm
yum install kernel-ml-devel-3.15.6-1.el7.elrepo.x86_64.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-doc-3.15.6-1.el7.elrepo.noarch.rpm
yum install kernel-ml-doc-3.15.6-1.el7.elrepo.noarch.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-headers-3.15.6-1.el7.elrepo.x86_64.rpm
yum install kernel-ml-headers-3.15.6-1.el7.elrepo.x86_64.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-tools-3.15.6-1.el7.elrepo.x86_64.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-tools-libs-3.15.6-1.el7.elrepo.x86_64.rpm
yum install kernel-ml-tools-libs-3.15.6-1.el7.elrepo.x86_64.rpm
yum install kernel-ml-tools-3.15.6-1.el7.elrepo.x86_64.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/kernel-ml-tools-libs-devel-3.15.6-1.el7.elrepo.x86_64.rpm
yum install kernel-ml-tools-libs-devel-3.15.6-1.el7.elrepo.x86_64.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/perf-3.15.6-1.el7.elrepo.x86_64.rpm
yum install perf-3.15.6-1.el7.elrepo.x86_64.rpm
wget http://mirrors.neterra.net/elrepo/kernel/el7/x86_64/RPMS/python-perf-3.15.6-1.el7.elrepo.x86_64.rpm
yum install python-perf-3.15.6-1.el7.elrepo.x86_64.rpm
yum —enablerepo=elrepo-kernel install kernel-ml

После окончания всей этой процедуры запустите любым удобным образом конфигурационный файл /boot/grub/grub.conf . Измените его содержимое таким образом, чтобы в итоге следующие параметры имели соответствующие значения:

default=0
timeout=5
title vmlinuz-4.0.4-1.el7.elrepo.x86_64
root (hd0,0)
kernel /boot/vmlinuz-4.0.4-1.el7.elrepo.x86_64 console=hvc0 xencons=tty0 root=/dev/xvda1 ro
initrd /boot/initramfs-4.0.4-1.el7.elrepo.x86_64.img

Далее вам останется только перезагрузить выделенный сервер и переходить к непосредственной инсталляции FTP-сервера на компьютер.

Шаг 2: Первоначальная настройка FTP-сервера

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

Запустить конфигурационный файл VSftpd в операционной системе Linux

  1. В операционных системах Debian или Ubuntu конфигурационный файл запускается так: sudo nano /etc/vsftpd.conf . В CentOS и Fedora он находится по пути /etc/vsftpd/vsftpd.conf , а в Gentoo — /etc/vsftpd/vsftpd.conf.example .
  2. В консоли или текстовом редакторе отобразится сам файл. Здесь обратите внимание на указанные ниже пункты. В вашем конфигурационном файле они должны иметь такие же значения.

Шаг 3: Добавление пользователя с расширенными правами

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

  1. Запустите «Терминал» и введите команду sudo adduser user1 , где user1 — имя новой учетной записи. Создать нового пользователя через терминал в Linux
  2. Задайте для него пароль, после чего подтвердите его. Кроме этого, настоятельно рекомендуем запомнить домашний каталог учетной записи, в дальнейшем может понадобиться обращение к нему через консоль. Ввести пароль для нового пользователя в операционной системе Linux
  3. Заполните основную информацию — полное имя, номер комнаты, номера телефонов и прочую информацию, если требуется. Дополнительные данные нового пользователя в Linux
  4. После этого присвойте пользователю расширенные права путем ввода команды sudo adduser user1 sudo . Предоставить новому пользователю расширенные права Linux
  5. Создайте для юзера отдельную директорию под хранение его файлов через sudo mkdir /home/user1/files . Создать для пользователя главную папку в Linux
  6. Далее переместитесь в свою домашнюю папку через cd /home и там сделайте нового пользователя владельцем своей директории, введя chown root:root /home/user1 . Задать владение для папки нового пользователя в Linux
  7. Перезапустите сервер после осуществления всех изменений sudo service vsftpd restart . Только в дистрибутиве Gentoo утилита перезагружается через /etc/init.d/vsftpd restart . Перезапустить FTP-сервер через консоль в Linux

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

Шаг 4: Настройка Firewall (Только для Ubuntu)

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

  1. В консоли поочередно активируйте команды sudo ufw disable и sudo ufw enable , чтобы перезапустить Firewall. Перезапустить Firewall в операционной системе Ubuntu
  2. Добавьте правила входящих соединений, используя sudo ufw allow 20/tcp и sudo ufw allow 21/tcp . Добавить новые правила в Firewall в операционной системе Ubuntu
  3. Проверьте, были ли применены введенные правила, просмотрев статус фаервола sudo ufw status . Проверить статус Firewall в операционной системе Ubuntu

Отдельно хочется отметить несколько полезных команд:

Команды Описание
/etc/init.d/vsftpd start Анализ конфигурационного файла
service vsftpd start
netstat -tanp | grep LISTEN Проверка корректности установки FTP-сервера
man vsftpd Вызов официальной документации VSftpd для поиска необходимой информации касаемо работы утилиты
service vsftpd restart Перезагрузка сервера
/etc/init.d/vsftpd restart

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

На этом статья подходит к концу. Сегодня мы разобрали процедуру установки сервера VSftpd без привязки к какому-либо хостингу, поэтому учтите это при выполнении наших инструкций и сравнивайте их с теми, что предоставляет компания, содержащая ваш виртуальный сервер. Кроме всего, советуем ознакомиться с другим нашим материалом, в котором разбирается тема установки компонентов LAMP.

How to Set Up FTP Server on Ubuntu VPS: The Ultimate Guide

How to Set Up FTP Server on Ubuntu VPS: The Ultimate Guide

In this article, you are going to learn how to set up an FTP server on an Ubuntu VPS. We’ll be using a vsftpd server, which is widely regarded as the fastest and most secure FTP server for UNIX-like systems.

What Is FTP?

FTP, or File Transfer Protocol, is a means to share files between computers over an internet connection using the TCP/IP protocol. It also makes use of a client-server framework and SSL/TLS security to ensure secure and reliable data transfer.

This is somewhat similar to HTTP (HypertText Transfer Protocol) or SMTP (Simple Mail Transfer Protocol). The difference is that FTP is responsible for transporting files through the internet while HTTP and SMTP handle the transfer of web pages and emails, respectively.

Before we begin, keep in mind that we will guide you through configuring an FTP server on Ubuntu 18.04. Therefore, you need to make sure your VPS is running on that particular OS.

How to Set Up an FTP Server on Ubuntu

This tutorial requires you to know how to connect to a server through SSH. If you own Hostinger’s VPS, the login details are available in the Server tab of the hPanel.

Step 1 – Installing vsftpd

  1. First of all, we’ll have to get our package updates before we proceed with the vsftpd installation. To begin, run the following command:

Wait for all the processes to complete, and you will see a confirmation as soon as the update finishes.

You will be prompted with a confirmation message, which will require you to type Y and hit Enter to continue with the installation.

Now we are ready to configure the firewall.

Step 2 – Allowing FTP Traffic from the Firewall

  1. To allow the Ubuntu FTP server to communicate via the internet, it needs to make its way through the firewall. But first, let’s just see whether the firewall is already enabled on your machine or not. Simply run this command to verify the status:

If you see the following message:

It means that the firewall is not installed. You can install and enable it by typing:

This series of commands will open up several ports:

  • OpenSSH is required if you still wish to access your server via SSH. Sometimes, this option is enabled by default.
  • ports 20 and 21 for the FTP traffic.
  • ports 40000:50000 will be reserved for the range of passive ports that will eventually be set in the configuration file.
  • port 990 will be used when TLS is enabled.

The output should look something like this:

Step 3 – Creating the User Directory

  1. Once the firewall is set up, we must create the user who is going to use the FTP access. This is how to do it:

Remember to change the username according to your own preference.

Then, set the ownership using:

Finally, remove the write permission:

Now, use the following command to verify the permissions:

The output should look something like:

Finally, add a test file to the directory which will be used when we test everything later on:

Step 4 – Configuring vsftpd

The next step is to configure vsftpd and our FTP access. In this example, we will allow a single user to connect using a local shell account. The two key configurations required for this are already set in the configuration (vsftpd.conf) file.

    To begin, use the nano command to open vsftpd configuration file.

Verify that the content has similar settings to this:

In the same file, we will remove # (uncomment) and make sure we enable the write_enable.

When you set userlist_deny flag to NO, only specified users will be allowed access. Once done, click CTRL+X followed by Y to save it, then Enter to confirm the file changes.

Verify that the user is indeed active by running the following command:

Verifying user on userlist on a VPS

The output should be “hostinger” as shown in this screenshot:

Step 5 – Making FTP Secure

  1. By default, FTP doesn’t encrypt data, so we will be using SSL/TLS certificate to secure data transfer. The first step is we need to create the SSL certificate for the Ubuntu FTP server.

The –days flag makes the certificate valid for a year and we have included a 2048-bit private RSA key in the same command.

The end of the file should contain two lines that start with rsa.

Now, we will point the configuration file to the certificate that we just created. Add the following directories right below the previous lines:

Then, add the following lines to ban any anonymous connections over SSL:

Configure the server to use TLS using:

Save the file again by pressing CTRL+X followed by Y, then hit Enter.

Great work! You have now configured the FTP server on your Ubuntu VPS to work with SSL/TLS protocol.

Step 6 – Testing Connection with FileZilla

Nowadays, most FTP clients support TLS encryption configurations. It’s a great way to test whether your Ubuntu FTP server is working properly. To test out the connection, we will be using a FileZilla FTP Client.

  1. To start, launch FileZilla and click on the Site Manager icon. Then, click the New Site button in the prompted window to enter the Ubuntu FTP server details.
    FileZilla quick connect window
  2. Fill in all the required columns with your newly created Ubuntu FTP server information. Since we configured it to use TLS, we may also choose the Use explicit FTP over TLS option. The final configuration should look like this:
    FileZilla connection settings
  3. Once ready, click Connect, and a screen asking to enter the FTP user’s password will appear. After that, hit OK.
  4. Finally, you will need to verify the SSL certificate of your FTP server on Ubuntu VPS. After confirming, the root directory with the test file should now appear on your screen.
    Test file on Ubuntu FileZilla client

That’s all! Now, you can perform various files transfers from your computer to the Ubuntu FTP server and vice versa.

Conclusion

Having an Ubuntu FTP server makes it easy for you to share files between your Ubuntu VPS/server and computer. It is a secure and reliable method of data transfer, thanks to SSL/TLS security and the TCP/IP protocol.

In this tutorial, you have learned how to set up an FTP server on Ubuntu 18.04 using vsftpd. There are five steps that you should follow. Let’s take a look at them once again.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *