Servidor FTP externo no Ubuntu 12.04 - Criação e configuração

Neste artigo, vou mostrar como fazer as principais configurações para ter um servidor FTP externo, ou seja, acessível de qualquer lugar (que tenha Internet). Estou usando o Ubuntu 12.04 e supondo que você tenha um IP fixo ou sabe usar algum serviço, como o NO-IP.

[ Hits: 58.986 ]

Por: Paulo Dias em 02/06/2014 | Blog: http://naotenhosite.eu.nao.tenho


Instalação e configuração



Instalando e configurando o proftpd

O primeiro passo é instalar o ProFTPD, para isso, digite no terminal:

sudo apt-get install proftpd

Com o ProFTPD instalado, o próximo passo é alterar o arquivo /etc/proftpd/proftpd.conf, mas antes, faça um backup da configuração padrão:

sudo cp /etc/proftpd/proftpd.conf /etc/proftpd/proftpd.conf-original
$ sudo nano /etc/proftpd/proftpd.conf


Nesse arquivo, verifique se as seguintes linhas estão presentes e com essa configuração:

ServerName    "Nome para o seu servidor"
ServerIdent   on "Mensagem para os usuarios"
ServerAdmin   root@localhost
ServerType    standalone
DefaultRoot   ~
RequireValidShell  off

Onde:
  • ServerName: É o nome do seu servidor. Ex.: Servidor FTP
  • ServerIdent: É a mensagem que é mostrada quando um usuário vai conectar no servidor.
  • ServerAdmin: É o e-mail do administrador do servidor.
  • ServerType: É a forma que o ProFTPD vai trabalhar.
  • DefaultRoot: É o diretório onde o usuário do FTP vai ter acesso.
  • RequireValidShell: Diz se o usuário precisa ter um shell válido. Ex.: bash, sh, csh...

Obs.: essas linhas não estão uma embaixo da outra no arquivo, você vai precisar procurar por elas.

Com o arquivo configurado, crie um usuário especificamente para acessar o FTP, com os comandos:

sudo useradd -m -s /bin/false usuario_ftp
$ sudo passwd usuario_ftp


No primeiro comando, a flag -m indica que deve ser criada uma pasta para esse usuário em /home e a flag -s, especifica o shell desse usuário (nesse caso sem shell). No segundo comando, é definida a senha do novo usuário.

Feito isso, reinicie o ProFTPD com o comando:

sudo etc/init.d/proftpd restart

Pronto, com isso seu servidor FTP já deve estar funcionando na rede interna (se não, deixe um comentário).

Para testar, acesse a URL com seu navegador padrão: ftp://localhost

Com tudo funcionando na rede interna, agora vou mostrar como configurar para ter acesso de forma externa.

Habilitando o acesso externo

Para que seja possível acessar o servidor FTP de fora da sua rede, é necessário saber o seu IP externo, para isso acesse esse site:
O mais provável, é que o seu IP externo não seja fixo, toda vez (ou quase) que você desligar o seu modem, ele recebe um IP diferente, se esse for o caso, você vai precisar utilizar o NO-IP ou algo semelhante... (NO-IP??? clique aqui e veja como usar).

Mesmo que seu IP não seja fixo e que você não tenha o NO-IP, é possível continuar com esse tutorial, apenas verifique seu IP externo e não desligue nada (se acontecer de algo ser desligado, será necessário verificar o IP novamente).

Altere ou crie as seguinte linhas no arquivo /etc/proftpd/proftpd.conf:

MasqueradeAddress             aqui.vaiSeu.ip.externo
PassivePorts                       65500 65534

Obs.: essas linhas, se existirem, podem ter um # no início. Você precisa retirar esse caractere.

O seu IP externo, na verdade, corresponde ao seu modem/roteador. Será necessário configurar esse aparelho de forma que, ao receber uma conexão FTP, ele envie para o seu computador (onde está o ProFTPD).

Para isso, é necessário saber o IP da rede interna do seu computador e do seu roteador. Você pode usar os comandos ifconfig e o route para localizar essas informações:
Linux: Servidor FTP externo no Ubuntu 12.04 - Criação e configuração   Linux: Servidor FTP externo no Ubuntu 12.04 - Criação e configuração
Para acessar seu roteador, coloque o IP interno dele no seu navegador. Vai precisar saber o login e a senha para acessar as configurações (se você não sabe, tente usuário admin e senha admin, ou clique aqui).

Procure por Port Forwarding ou algo parecido, você vai ter que fazer a seguinte configuração:

Obs.: troque o 192.168.0.20 pelo IP interno do seu computador.
Linux: Servidor FTP externo no Ubuntu 12.04 - Criação e configuração
Obs.:
  • Usei a porta 2121, porque geralmente a porta padrão do FTP (21) é bloqueada pela operadora.
  • O IP do computador deve ser configurado manualmente e não por DHCP.

Agora, reinicie o ProFTPD novamente e pronto. Você já deve ser capaz de acessar seu servidor com o IP externo.

É necessário colocar o numero da porta junto do IP externo, ex.: ftp://xxx.xxx.xxx.xxx:2121


Bom, é isso.
Dúvida? Comenta aí! :)

   

Páginas do artigo
   1. Instalação e configuração
Outros artigos deste autor

Zoneminder: Substituindo um Unifi NVR

Programação com Shell Script

Como criar um box para o Vagrant

JavaScript - Programação orientada a objetos

MathML - Mathematical Markup Language

Leitura recomendada

Gravando conversas no Skype do Linux

Usando o Lynx para atualizar informações no seu site

Tor no Debian Squeeze - Instalação e Configuração

Configurando o Squid no Kurumin

O protocolo DHCP: evolução, características e seu funcionamento

  
Comentários
[1] Comentário enviado por osterno em 03/06/2014 - 07:29h

Valeu Paulo, obrigado por contribuir. Abração.

[2] Comentário enviado por Armlook em 20/07/2014 - 12:57h

Parabéns pelo tópico! Obrigado!

[3] Comentário enviado por regiz10 em 16/08/2014 - 08:21h

Caro colega, gostaria de saber como liberar o acesso remoto com o ip dinamico no meu roteador?
Onde devo colocar a informação do " masqueradeaddress"? ja que esse ip deve mudar?
Apenas instalando o NOIP já resolveria esse problema?
Grato.

[4] Comentário enviado por andresalvador em 30/09/2014 - 07:48h

Ola Amigos,

Instalei o proftpd e não estou conseguindo acessar nem pela rede interna. Alguem pode me ajudar? Obrigado!

[5] Comentário enviado por bomberloko em 10/03/2015 - 16:29h


Pode enviar seu proftpd.conf??

[6] Comentário enviado por helpdesk2 em 10/03/2015 - 23:31h


Boa noite amigos estou com o mesmo problema que o andresalvador,
se puderem me ajudar:

#
# /etc/proftpd/proftpd.conf -- This is a basic ProFTPD configuration file.
# To really apply changes, reload proftpd after modifications, if
# it runs in daemon mode. It is not required in inetd/xinetd mode.
#

# Includes DSO modules
Include /etc/proftpd/modules.conf

# Set off to disable IPv6 support which is annoying on IPv4 only boxes.
UseIPv6 on
# If set on you can experience a longer connection delay in many cases.
IdentLookups off

ServerName "teste"
ServerType standalone
DeferWelcome on

MultilineRFC2228 on
DefaultServer on
ShowSymlinks on

TimeoutNoTransfer 600
TimeoutStalled 600
TimeoutIdle 1200

DisplayLogin welcome.msg
DisplayChdir .message true
ListOptions "-l"

DenyFilter \*.*/

# Use this to jail all users in their homes
# DefaultRoot ~

# Users require a valid shell listed in /etc/shells to login.
# Use this directive to release that constrain.
# RequireValidShell off

# Port 21 is the standard FTP port.
Port 2121

# In some cases you have to specify passive ports range to by-pass
# firewall limitations. Ephemeral ports can be used for that, but
# feel free to use a more narrow range.
PassivePorts 65500 65534

# If your host was NATted, this option is useful in order to
# allow passive tranfers to work. You have to use your public
# address and opening the passive ports used on your firewall as well.
MasqueradeAddress 179.178.183.42

# This is useful for masquerading address with dynamic IPs:
# refresh any configured MasqueradeAddress directives every 8 hours
<IfModule mod_dynmasq.c>
# DynMasqRefresh 28800
</IfModule>

# To prevent DoS attacks, set the maximum number of child processes
# to 30. If you need to allow more than 30 concurrent connections
# at once, simply increase this value. Note that this ONLY works
# in standalone mode, in inetd mode you should use an inetd server
# that allows you to limit maximum number of processes per service
# (such as xinetd)
MaxInstances 30

# Set the user and group that the server normally runs at.
User proftpd
Group nogroup

# Umask 022 is a good standard umask to prevent new files and dirs
# (second parm) from being group and world writable.
Umask 022 022
# Normally, we want files to be overwriteable.
AllowOverwrite on

# Uncomment this if you are using NIS or LDAP via NSS to retrieve passwords:
# PersistentPasswd off

# This is required to use both PAM-based authentication and local passwords
# AuthOrder mod_auth_pam.c* mod_auth_unix.c

# Be warned: use of this directive impacts CPU average load!
# Uncomment this if you like to see progress and transfer rate with ftpwho
# in downloads. That is not needed for uploads rates.
#
# UseSendFile off

TransferLog /var/log/proftpd/xferlog
SystemLog /var/log/proftpd/proftpd.log

# Logging onto /var/log/lastlog is enabled but set to off by default
#UseLastlog on

# In order to keep log file dates consistent after chroot, use timezone info
# from /etc/localtime. If this is not set, and proftpd is configured to
# chroot (e.g. DefaultRoot or <Anonymous>), it will use the non-daylight
# savings timezone regardless of whether DST is in effect.
#SetEnv TZ :/etc/localtime

<IfModule mod_quotatab.c>
QuotaEngine off
</IfModule>

<IfModule mod_ratio.c>
Ratios off
</IfModule>


# Delay engine reduces impact of the so-called Timing Attack described in
# http://www.securityfocus.com/bid/11430/discuss
# It is on by default.
<IfModule mod_delay.c>
DelayEngine on
</IfModule>

<IfModule mod_ctrls.c>
ControlsEngine off
ControlsMaxClients 2
ControlsLog /var/log/proftpd/controls.log
ControlsInterval 5
ControlsSocket /var/run/proftpd/proftpd.sock
</IfModule>

<IfModule mod_ctrls_admin.c>
AdminControlsEngine off
</IfModule>

#
# Alternative authentication frameworks
#
#Include /etc/proftpd/ldap.conf
#Include /etc/proftpd/sql.conf

#
# This is used for FTPS connections
#
#Include /etc/proftpd/tls.conf

#
# Useful to keep VirtualHost/VirtualRoot directives separated
#
#Include /etc/proftpd/virtuals.conf

# A basic anonymous configuration, no upload directories.

# <Anonymous ~ftp>
# User ftp
# Group nogroup
# # We want clients to be able to login with "anonymous" as well as "ftp"
# UserAlias anonymous ftp
# # Cosmetic changes, all files belongs to ftp user
# DirFakeUser on ftp
# DirFakeGroup on ftp
#
# RequireValidShell off
#
# # Limit the maximum number of anonymous logins
# MaxClients 10
#
# # We want 'welcome.msg' displayed at login, and '.message' displayed
# # in each newly chdired directory.
# DisplayLogin welcome.msg
# DisplayChdir .message
#
# # Limit WRITE everywhere in the anonymous chroot
# <Directory *>
# <Limit WRITE>
# DenyAll
# </Limit>
# </Directory>
#
# # Uncomment this if you're brave.
# # <Directory incoming>
# # # Umask 022 is a good standard umask to prevent new files and dirs
# # # (second parm) from being group and world writable.
# # Umask 022 022
# # <Limit READ WRITE>
# # DenyAll
# # </Limit>
# # <Limit STOR>
# # AllowAll
# # </Limit>
# # </Directory>
#
# </Anonymous>

# Include other custom configuration files
Include /etc/proftpd/conf.d/

[7] Comentário enviado por felipecs em 16/04/2015 - 21:23h


[3] Comentário enviado por regiz10 em 16/08/2014 - 08:21h

Caro colega, gostaria de saber como liberar o acesso remoto com o ip dinamico no meu roteador?
Onde devo colocar a informação do " masqueradeaddress"? ja que esse ip deve mudar?
Apenas instalando o NOIP já resolveria esse problema?
Grato.


Opa, você pode tentar colocar o endereço criado pelo no-ip. ex. seudominio.no-ip.info

[8] Comentário enviado por felipecs em 16/04/2015 - 21:25h


[6] Comentário enviado por helpdesk2 em 10/03/2015 - 23:31h


Boa noite amigos estou com o mesmo problema que o andresalvador,
se puderem me ajudar:

#
# /etc/proftpd/proftpd.conf -- This is a basic ProFTPD configuration file.
# To really apply changes, reload proftpd after modifications, if
# it runs in daemon mode. It is not required in inetd/xinetd mode.
#

# Includes DSO modules
Include /etc/proftpd/modules.conf

# Set off to disable IPv6 support which is annoying on IPv4 only boxes.
UseIPv6 on
# If set on you can experience a longer connection delay in many cases.
IdentLookups off

ServerName "teste"
ServerType standalone
DeferWelcome on

MultilineRFC2228 on
DefaultServer on
ShowSymlinks on

TimeoutNoTransfer 600
TimeoutStalled 600
TimeoutIdle 1200

DisplayLogin welcome.msg
DisplayChdir .message true
ListOptions "-l"

DenyFilter \*.*/

# Use this to jail all users in their homes
# DefaultRoot ~

# Users require a valid shell listed in /etc/shells to login.
# Use this directive to release that constrain.
# RequireValidShell off

# Port 21 is the standard FTP port.
Port 2121

# In some cases you have to specify passive ports range to by-pass
# firewall limitations. Ephemeral ports can be used for that, but
# feel free to use a more narrow range.
PassivePorts 65500 65534

# If your host was NATted, this option is useful in order to
# allow passive tranfers to work. You have to use your public
# address and opening the passive ports used on your firewall as well.
MasqueradeAddress 179.178.183.42

# This is useful for masquerading address with dynamic IPs:
# refresh any configured MasqueradeAddress directives every 8 hours
&lt;IfModule mod_dynmasq.c&gt;
# DynMasqRefresh 28800
&lt;/IfModule&gt;

# To prevent DoS attacks, set the maximum number of child processes
# to 30. If you need to allow more than 30 concurrent connections
# at once, simply increase this value. Note that this ONLY works
# in standalone mode, in inetd mode you should use an inetd server
# that allows you to limit maximum number of processes per service
# (such as xinetd)
MaxInstances 30

# Set the user and group that the server normally runs at.
User proftpd
Group nogroup

# Umask 022 is a good standard umask to prevent new files and dirs
# (second parm) from being group and world writable.
Umask 022 022
# Normally, we want files to be overwriteable.
AllowOverwrite on

# Uncomment this if you are using NIS or LDAP via NSS to retrieve passwords:
# PersistentPasswd off

# This is required to use both PAM-based authentication and local passwords
# AuthOrder mod_auth_pam.c* mod_auth_unix.c

# Be warned: use of this directive impacts CPU average load!
# Uncomment this if you like to see progress and transfer rate with ftpwho
# in downloads. That is not needed for uploads rates.
#
# UseSendFile off

TransferLog /var/log/proftpd/xferlog
SystemLog /var/log/proftpd/proftpd.log

# Logging onto /var/log/lastlog is enabled but set to off by default
#UseLastlog on

# In order to keep log file dates consistent after chroot, use timezone info
# from /etc/localtime. If this is not set, and proftpd is configured to
# chroot (e.g. DefaultRoot or &lt;Anonymous&gt;), it will use the non-daylight
# savings timezone regardless of whether DST is in effect.
#SetEnv TZ :/etc/localtime

&lt;IfModule mod_quotatab.c&gt;
QuotaEngine off
&lt;/IfModule&gt;

&lt;IfModule mod_ratio.c&gt;
Ratios off
&lt;/IfModule&gt;


# Delay engine reduces impact of the so-called Timing Attack described in
# http://www.securityfocus.com/bid/11430/discuss
# It is on by default.
&lt;IfModule mod_delay.c&gt;
DelayEngine on
&lt;/IfModule&gt;

&lt;IfModule mod_ctrls.c&gt;
ControlsEngine off
ControlsMaxClients 2
ControlsLog /var/log/proftpd/controls.log
ControlsInterval 5
ControlsSocket /var/run/proftpd/proftpd.sock
&lt;/IfModule&gt;

&lt;IfModule mod_ctrls_admin.c&gt;
AdminControlsEngine off
&lt;/IfModule&gt;

#
# Alternative authentication frameworks
#
#Include /etc/proftpd/ldap.conf
#Include /etc/proftpd/sql.conf

#
# This is used for FTPS connections
#
#Include /etc/proftpd/tls.conf

#
# Useful to keep VirtualHost/VirtualRoot directives separated
#
#Include /etc/proftpd/virtuals.conf

# A basic anonymous configuration, no upload directories.

# &lt;Anonymous ~ftp&gt;
# User ftp
# Group nogroup
# # We want clients to be able to login with "anonymous" as well as "ftp"
# UserAlias anonymous ftp
# # Cosmetic changes, all files belongs to ftp user
# DirFakeUser on ftp
# DirFakeGroup on ftp
#
# RequireValidShell off
#
# # Limit the maximum number of anonymous logins
# MaxClients 10
#
# # We want 'welcome.msg' displayed at login, and '.message' displayed
# # in each newly chdired directory.
# DisplayLogin welcome.msg
# DisplayChdir .message
#
# # Limit WRITE everywhere in the anonymous chroot
# &lt;Directory *&gt;
# &lt;Limit WRITE&gt;
# DenyAll
# &lt;/Limit&gt;
# &lt;/Directory&gt;
#
# # Uncomment this if you're brave.
# # &lt;Directory incoming&gt;
# # # Umask 022 is a good standard umask to prevent new files and dirs
# # # (second parm) from being group and world writable.
# # Umask 022 022
# # &lt;Limit READ WRITE&gt;
# # DenyAll
# # &lt;/Limit&gt;
# # &lt;Limit STOR&gt;
# # AllowAll
# # &lt;/Limit&gt;
# # &lt;/Directory&gt;
#
# &lt;/Anonymous&gt;

# Include other custom configuration files
Include /etc/proftpd/conf.d/


*********************************************************************
Verifica e leia o seguinte:

# If your host was NATted, this option is useful in order to
# allow passive tranfers to work. *You have to use your public
# address and opening the passive ports used on your firewall as well.*
MasqueradeAddress 179.178.183.42

Você usa algum Firewall na rede? isso só pode ser bloqueio de firewall, pra acessar a maquina por ip local, coloca ali o ip local do seu servidor FTP e testa pra ver.

[9] Comentário enviado por felipecs em 16/04/2015 - 21:30h


Meu caro! muito bom! Fiz o teste em um VPS e rolou muito bem!

Algumas considerações:

No meu caso usando Ubuntu 12.04 Lts

algumas linhas nao estavam presentes no meu conf, adicionei e ficou show!

ServerName "Nome para o seu servidor"
ServerIdent on "Mensagem para os usuarios"
ServerAdmin root@localhost
ServerType standalone
DefaultRoot ~ ------> Essa linha, o "~" significa a pasta home do usuario que fica em /home/usuario_ftp, no meu caso, eu precisava liberar uma pasta do servidor web, então assim como eu, você pode alterar o "~" para "/var/www/" ou a pasta que você quiser, que no meu caso, ao logar no ftp, o usuário vai ter acesso a essa pasta pra hospedar arquivos do sistema web.

RequireValidShell off

[10] Comentário enviado por Willian_Pazinato em 06/05/2015 - 11:55h


Olá, estou rodando um servidor FTP no Ubuntu 14.04 LTS. Porém o mesmo para de rodar o serviço após 12 horas, me obrigando a reativar o serviço todos os dias. Até o momento não encontrei nenhuma opção para configurar isto. Saberia me dizer qual é o problema?
Desde já agradeço.

[11] Comentário enviado por n3g4_1 em 20/03/2016 - 02:37h

Fiz tudo conforme o combinado, porém:

Erro: Connection timed out after 20 seconds of inactivity
Erro: Não foi possível conectar ao servidor

Será que o Virtua não deixa eu ter FTP on line??

Obs: Tentei as portas 21 e 2121

[12] Comentário enviado por pjhorn@gmail.com em 24/06/2016 - 23:47h

Boa noite! Por algum motivo eu não estou conseguindo definir a senha para o usuário. Ele dá a seguinte mensagem: "530 Login incorrect.". Verifiquei nas pasta home o usuário está criado e já tentei inclusive inserir a senha direto pela home para ver se o resultado era positivo, porém, não tive sucesso. Muito Obrigado!


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts