LINUX

Cómo configurar el servidor SFTP MySecureShell en Ubuntu 18.04

En este artículo, le explicaré cómo configurar un servidor SFTP usando MySecureShell en Ubuntu 18.04. SFTP es una forma segura de transferir archivos mediante una conexión SSH cifrada. Aunque es ampliamente compatible con los clientes FTP modernos, es un protocolo completamente diferente al FTP (Protocolo de transferencia de archivos).

Puede preguntarme por qué MySecureShell en lugar del servidor FTP tradicional. Estas son algunas de las características

  • Transferencia de datos segura mediante SSH
  • No es necesario administrar certificados SSL
  • Fácil de instalar y configurar
  • Limitar el uso de ancho de banda
  • Restricciones de archivos y carpetas
  • Lista de control de acceso usando IP / Nombre de usuario / Grupos / VirtualHost
  • Restringir a los usuarios para que solo tengan sftp (el acceso al shell está deshabilitado de forma predeterminada)
  • Sistema de registro mejorado

Así que comencemos con la instalación primero, el conocimiento básico de FTP es suficiente para comprender este tutorial.

Instalación

Desde ubuntu 15.04 y superior, MySecureShell está disponible en los repositorios predeterminados. Estamos usando ubuntu 18.04 para esta instalación. Simplemente ejecute los siguientes comandos para instalar MySecureShell.

apt-get install mysecureshell

Si no está disponible, siga los pasos, asegúrese de que todos los pasos siguientes se ejecuten como usuario root.

vim /etc/apt/sources.list

Agregue las siguientes 2 líneas,

deb http://mysecureshell.free.fr/repository/index.php/ubuntu testing main
deb-src http://mysecureshell.free.fr/repository/index.php/ubuntu testing main

Ahora agregue la clave gpg como,

gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys E328F22B; gpg --export E328F22B | apt-key add
gpg: keybox '/root/.gnupg/pubring.kbx' created
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key 7601D76CE328F22B: public key "MySecureShell repository " imported
gpg: Total number processed: 1
gpg:           	imported: 1
OK

Una vez que se agrega el repositorio, puede comenzar con la instalación

apt-get update
apt-get install mysecureshell

Ahora está todo listo para iniciar el servicio y verificar su estado.

systemctl start mysecureshell.service
systemctl status mysecureshell.service

Salida de muestra

# systemctl start mysecureshell.service
root@li1004-153:~# systemctl status mysecureshell.service
* mysecureshell.service - LSB: MySecureShell SFTP Server
   Loaded: loaded (/etc/init.d/mysecureshell; generated)
   Active: active (exited) since Fri 2018-05-18 01:02:17 UTC; 4min 44s ago
     Docs: man:systemd-sysv-generator(8)
    Tasks: 0 (limit: 2322)
   CGroup: /system.slice/mysecureshell.service

May 18 01:02:17 004-153 systemd[1]: Starting LSB: MySecureShell SFTP Server...
May 18 01:02:17 004-153 mysecureshell[1314]: Starting MySecureShell SFTP Server: mysecureshell is now online with restricted features
May 18 01:02:17 004-153 mysecureshell[1314]: Note: To enable all features you have to change mysecureshell binary rights to 4755
May 18 01:02:17 004-153 systemd[1]: Started LSB: MySecureShell SFTP Server.

# systemctl status mysecureshell.service
* mysecureshell.service - LSB: MySecureShell SFTP Server
   Loaded: loaded (/etc/init.d/mysecureshell; generated)
   Active: active (exited) since Fri 2018-05-18 01:02:17 UTC; 50min ago
     Docs: man:systemd-sysv-generator(8)
    Tasks: 0 (limit: 2322)
   CGroup: /system.slice/mysecureshell.service

May 18 01:02:17 004-153 systemd[1]: Starting LSB: MySecureShell SFTP Server...
May 18 01:02:17 004-153 mysecureshell[1314]: Starting MySecureShell SFTP Server: mysecureshell is now online with restricted features
May 18 01:02:17 004-153 mysecureshell[1314]: Note: To enable all features you have to change mysecureshell binary rights to 4755
May 18 01:02:17 004-153 systemd[1]: Started LSB: MySecureShell SFTP Server.
#

Utilice los siguientes comandos para detener y reiniciar el servicio mysecureshell

systemctl stop mysecureshell.service
systemctl restart mysecureshell.service

Creación de usuarios de MySecureShell SFTP

Primero, tenemos que encontrar la ubicación de instalación de MySecureShell,

whereis mysecureshell

Como puede ver en el resultado a continuación, la ruta de instalación de mysecureshell es / usr / bin / mysecureshell.

mysecureshell: /usr/bin/mysecureshell /usr/share/man/man8/mysecureshell.8.gz

Ahora, después de verificar la ruta, creemos un usuario

useradd -m -s /usr/bin/mysecureshell testsftpuser
passwd testsftpuser

Como puede ver en el comando anterior, estamos creando un usuario y asignando la ruta de ubicación de mysecureshell. Además, puede asignar a los usuarios existentes para acceder y usar MySecureShell usando el comando:

sudo usermod -s /usr/bin/mysecureshell testsftpuser

Conexión de usuario

Ahora el usuario «testsftpuser» puede conectarse a su servidor SFTP desde sus clientes como se muestra a continuación con la dirección IP de su máquina,

sftp testsftpuser@45.33.54.153

La IP de su máquina

Connected to 45.33.54.153
sftp>

Además, puede iniciar sesión en su servidor SFTP con cualquier cliente gráfico como FileZilla desde su sistema cliente.

Comandos de MySecureShell

MySecureShell tiene el siguiente conjunto de comandos para administrar su servidor SFTP.

  • sftp-admin
  • sftp-kill
  • estado-sftp
  • sftp-usuario
  • sftp-verif
  • sftp-quien

sftp-admin

Este comando permite administrar un MySecureShell de forma remota.

sftp-admin [ssh options] user@hostname

sftp-kill

Desconectará al usuario del servidor FTP.

sftp-kill testsftpuser
Kill testsftpuser on PID 1961
(Press "Y" when requested)

estado-sftp

Mostrar el estado del servidor ftp

# sftp-state

Salida de muestra

# sftp-state
Server is up
#

sftp-usuario

Este comando te permite crear un usuario SFTP, sin especificar la ruta que hicimos antes.

sftp-user create test

Lista de usuarios de SFTP

sftp-user list
test
testsftpuser

El comando eliminará la prueba del usuario

sftp-user delete test

sftp-verif

Este comando verificará y corregirá problemas en un servidor MySecureShell.

sftp-verif
################################################################################
MySecureShell Verification Tool
################################################################################

### Verifing file existance ###

/bin/MySecureShell                                                       [ OK ]
/bin/sftp-who                                                            [ OK ]
/bin/sftp-kill                                                           [ OK ]
/bin/sftp-state                                                          [ OK ]
/bin/sftp-admin                                                          [ OK ]
/bin/sftp-verif                                                          [ OK ]
/bin/sftp-user                                                           [ OK ]

### Verifing rights ###

Verifing file rights of /etc/ssh/sftp_config                             [ OK ]
Verifing file rights of /bin/sftp-who                                    [ OK ]
Verifing file rights of /bin/sftp-verif                                  [ OK ]
Verifing file rights of /bin/sftp-user                                   [ OK ]
Verifing file rights of /bin/sftp-kill                                   [ OK ]
Verifing file rights of /bin/sftp-state                                  [ OK ]
Verifing file rights of /bin/sftp-admin                                  [ OK ]
Verifing file rights of /bin/MySecureShell                               [ OK ]

### Verifing rotation logs ###
Rotation logs have been found                                            [ OK ]
### Verifing server status ###
Verifing server status (ONLINE)                                          [ OK ]
[...]

sftp-quien

Este comando le dirá quién está conectado actualmente al servidor FTP.

sftp-who
# sftp-who
--- 1 / 10 clients ---
Global used bandwidth : 0 bytes/s / 0 bytes/s
PID: 2207   Name: testsftpuser   IP: pa39-178-9-194.pa.nsw.optusnet.com.au
        Home: /home/testsftpuser
        Status: idle    Path: /
        File:
        Connected: 2018/05/18 01:30:50 [since 03mins 59s]
        Speed: Download: 0 bytes/s [5.00 kbytes/s]  Upload: 0 bytes/s [unlimited]
        Total: Download: 924 bytes   Upload: 100 bytes
#

Configuración

El archivo de configuración principal de MySecureShell es / etc / ssh / sftp_config. Puede configurar el ancho de banda de carga y descarga, los usuarios de chroot, la cantidad máxima de conexiones, etc.en el archivo de configuración. Puede configurar estas opciones para todos o solo para un grupo en particular.

cat /etc/ssh/sftp_config

Etiqueta predeterminada

La etiqueta predeterminada se usa si desea aplicar una configuración para todos sus usuarios

#Default rules for everybody
Default
        GlobalDownload          50k     #total speed download for all clients
                                        # o -> bytes   k -> kilo bytes   m -> mega bytes
        GlobalUpload            0       #total speed download for all clients (0 for unlimited)
        Download                5k      #limit speed download for each connection
        Upload                  0       #unlimit speed upload for each connection
        StayAtHome              true    #limit client to his home
        VirtualChroot           true    #fake a chroot to the home account
        LimitConnection         10      #max connection for the server sftp
        LimitConnectionByUser   1       #max connection for the account
        LimitConnectionByIP     2       #max connection by ip for the account
        Home                    /home/$USER     #overrite home of the user but if you want you can use
                                                #       environment variable (ie: Home /home/$USER)
        IdleTimeOut             5m      #(in second) deconnect client is idle too long time
        ResolveIP               true    #resolve ip to dns
        LogFile         /var/log/sftp-server_ftp.log
#       IgnoreHidden            true    #treat all hidden files as if they don't exist
#       DirFakeUser             true    #Hide real file/directory owner (just change displayed permissions)
#       DirFakeGroup            true    #Hide real file/directory group (just change displayed permissions)
#       DirFakeMode             0400    #Hide real file/directory rights (just change displayed permissions)
                                        #Add execution right for directory if read right is set
        HideNoAccess            true    #Hide file/directory which user has no access
#       MaxOpenFilesForUser     20      #limit user to open x files on same time
#       MaxWriteFilesForUser    10      #limit user to x upload on same time
#       MaxReadFilesForUser     10      #limit user to x download on same time
        DefaultRights           0640 0750       #Set default rights for new file and new directory
#       MinimumRights           0400 0700       #Set minimum rights for files and dirs

        ShowLinksAsLinks        false   #show links as their destinations
#       ConnectionMaxLife       1d      #limits connection lifetime to 1 day

#       Charset                 "ISO-8859-15"   #set charset of computer

Default

Nota: Los registros no están habilitados de forma predeterminada, puede definir la ubicación del archivo de registro en el archivo de configuración.

Etiqueta FileSpec

La etiqueta FileSpec está hecha para crear filtros en archivos y directorios.

    # Only check against filenames/folder names only
FileSpec
    UseFullPath false

    # we can use multiple deny/allow directives for clarity
    Order DenyAllow
    Deny ".*.exe$"
    Deny ".*.sh$"
    Allow all
FileSpec

Etiqueta de usuario
La etiqueta de usuario se define para una carpeta de inicio de usuario específica

User tom 
Home /home/tom 
User

Etiqueta de VirtualHost

La etiqueta VirtualHost puede establecer limitaciones según el nombre del host virtual

    # Set home directory for this virtualhost
VirtualHost
    Home                    /var/www/html/www.mysftpsite.com
    # Set dedicated log file
    LogFile                 /var/log/sftp/www.mysftpsite.com
    # Override the maximum number of connection per user
    LimitConnectionByUser   5
VirtualHost

Instalación de gFTP

Ahora, intentemos la instalación de gFTP en Ubuntu 18.04, siga los pasos a continuación,

sudo apt-get install gftp
  • Abra gFTP desde Aplicaciones
  • Ingrese la dirección IP del servidor SFTP, el número de puerto (predeterminado / especificado al configurar el servidor), el nombre de usuario y la contraseña y use SSH2. Presione Enter para iniciar sesión
  • Si el intento de inicio de sesión es exitoso. Estamos conectados a SFTP usando gFTP

Eso es todo por ahora. En esta etapa, tendrá un servidor SFTP en funcionamiento. Espero que te haya gustado este tutorial y te he dejado una parte de configuración para el autoaprendizaje, comenten amablemente la configuración que hiciste por ti mismo que ayuda a nuestra Comunidad Linoxide a aprender y crecer. Gracias.

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba
Cerrar