Обо всем

Всё что было и будет интересно

среда, 24 октября 2012 г.

Pure-ftpd Server + Mysql + UserManager


Сегодня я наконец настроил FTP сервер на базе PureFTPd и MySQL на Ubuntu 12.04.
Данный сервер поддерживает виртуальных пользователей, квоты и возможность управления скоростью раздачи для отдельных пользователей, также мы будем управлять FTP сервером с помощью вэб-интерфейса (UserManager).

О самом сервере читаем здесь:
http://www.pureftpd.org/project/pure-ftpd

О UserManager более подробно можно почитать здесь:


Начнем:

1. Перед началом установки обновляем систему.
sudo apt-get update
sudo apt-get -y upgrade


2. Устанавливаем необходимы пакеты.

sudo apt-get -y install apache2 php5 libapache2-mod-php5 mysql-server libapache2-mod-auth-mysql libapache2-mod-auth-mysql php5-mysql build-essential 
libmysqlclient15-dev libmysqlclient15off openssl libssl-dev

Во время установки необходимо задать пароль для пользователя root  для управления базой MySQL.

3. Установка PureFTPd сервера с поддержкой MySQL

sudo apt-get install pure-ftpd-mysql

Далее нужно создать ftp группу (ftpgroup) и ftp пользователя (ftpuser), это необходимо для использования для всех ваших виртуальных пользователей.

groupadd -g 2001 ftpgroup
useradd -u 2001 -s /bin/false -d /bin/null -c "pureftpd user" -g ftpgroup ftpuser

4. Установка вэб-интерфейса к PureftpD (UserManager)

Необходимо скачать исходники c сайта на данный момент последняя версия 2.1.

wget http://machiel.generaal.net/files/pureftpd/ftp_v2.1.tar.gz

Распаковываем:

tar -xvf ftp_v2.1.tar.gz

Переносим каталог \
mv /home/user/ftp_v2.1 /var/www/ftp

Создаем в конфигурационный файл и задаем Алиас для Апача

mcedit /etc/apache2/conf.d/pure-ftpd.conf

Alias /ftp /var/www/ftp

<Directory /var/www/ftp>
    Options +FollowSymLinks
    Options Indexes FollowSymlinks MultiViews
    AllowOverride AuthConfig
    order allow,deny
    allow from all

    AddType application/x-httpd-php .php

    <IfModule mod_php5.c>
        php_flag magic_quotes_gpc On
        php_flag short_open_tag On
        php_flag register_globals On
        php_flag register_argc_argv On
        php_flag track_vars On
        # this setting is necessary for some locales
        php_value mbstring.func_overload 0
        php_value include_path .
    </IfModule>

    DirectoryIndex index.php
</Directory>

Также необходимо проверить чтобы в php.ini был включен short_open_tag

short_open_tag = On

Перезагружаем apache

/etc/init.d/apache2 restart

Открываем браузер и переходим по адресу

http://ip-address-ftp-server/ftp/install.php

Следуя инструкции устанавливаем и проверяем всё что от нас требуют, при правильно раскладе все должно выгладить так.

This configuration script has carried out a few checks to see if everything is ready to start the configuration. 
Checking if config.php exists OK! 
Checking if config.php is writable OK! 
Checking if PHP Extension MYSQL is enabled OK! 
Checking if PHP Extension PCRE is enabled OK! 
Checking if PHP Extension POSIX is enabled OK! 
Checking if PHP Extension SESSION is enabled OK!
Следующим шагом нас попросят создать БД.

New installation, create a new database.

Если у вас возникла  проблема с созданием таблиц в базе данных то тогда их придется добавить вручную.

Checking connection to MySQL server OK! 
Create user FTP OK! 
Create database ftpusers OK! 
Create table admin Failed! 
Create table users Failed!

Открываем файл extra/script.mysql

Так как у нас mysql версии 5, необходимо поправить синтаксис в таблицах с 
TYPE=MyISAM; -> ENGINE=MyISAM;
--
-- Table structure for table 'admin'
--

CREATE TABLE admin (
  Username varchar(35) NOT NULL default '',
  Password char(32) binary NOT NULL default '',
  PRIMARY KEY  (Username)
) ENGINE=MyISAM;

--
-- Data for table 'admin'
--

INSERT INTO admin VALUES ('Administrator',MD5('tmppasswd'));

--
-- Table structure for table 'users'
--

CREATE TABLE `users` (
  `User` varchar(16) NOT NULL default '',
  `Password` varchar(32) binary NOT NULL default '',
  `Uid` int(11) NOT NULL default '14',
  `Gid` int(11) NOT NULL default '5',
  `Dir` varchar(128) NOT NULL default '',
  `QuotaFiles` int(10) NOT NULL default '500',
  `QuotaSize` int(10) NOT NULL default '30',
  `ULBandwidth` int(10) NOT NULL default '80',
  `DLBandwidth` int(10) NOT NULL default '80',
  `Ipaddress` varchar(15) NOT NULL default '*',
  `Comment` tinytext,
  `Status` enum('0','1') NOT NULL default '1',
  `ULRatio` smallint(5) NOT NULL default '1',
  `DLRatio` smallint(5) NOT NULL default '1',
  PRIMARY KEY  (`User`),
  UNIQUE KEY `User` (`User`)
) ENGINE=MyISAM;

--
-- Data for table 'users'
--

INSERT INTO ftpusers.users VALUES ('ftpuser_1',MD5('tmppasswd'),65534, 31, '/usr           ', 100, 50, 75, 75, '*', 'Ftp user (for example)', '1', 0, 0);

Далее:

mysql -u root -p

USE ftpusers;

Вставляем данные из файла extra/script.mysql или просто mysql -u root -p < script.mysql
после этого опять запускаем установку в через web и проверяем что ошибок больше нет обе таблицы в базу добавлены.

Checking connection to MySQL server OK!
Сreate user FTP OK! 
Create database ftpusers OK! 
Create table admin OK!
Create table users OK!

Возвращаемся к установке с вэб страницы, вводим данные пользователя ,бд и его пароль.
На данном этапе будут генериться конфиг файл для pure-ftpd-mysql.conf.
Устанавливаем все что необходимо.
Далее сохраняем настройки — нажимаем Save, настройки будут сохранены в файле
/var/www/ftp/config.php 
Правим содержимое /etc/pure-ftpd/db/mysql.conf

/etc/pure-ftpd/db/mysql.conf
############################################################################
#                                                                          #
# PureFTPd MySQL configuration file.                                       #
# Generated by the installation wizard for the 'User manager for PureFTPd' #
# See http://machiel.generaal.net for more info                            #
# or read the README.MySQL for explanations of the syntax.                 #
#                                                                          #
############################################################################

# Optional : MySQL server name or IP. Don't define this for unix sockets.

MYSQLServer     127.0.0.1

# Optional : MySQL port. Don't define this if a local unix socket is used.

# MYSQLPort       3306

# Optional : define the location of mysql.sock if the server runs on this host.

MYSQLSocket     /tmp/mysql.sock

# Mandatory : user to bind the server as.

MYSQLUser      ftpuser

# Mandatory : user password. You must have a password.

MYSQLPassword   password

# Mandatory : database to open.

MYSQLDatabase  ftpusers

# Mandatory : how passwords are stored
# Valid values are : "cleartext", "crypt", "md5" and "password"
# ("password" = MySQL password() function)
# You can also use "any" to try "crypt", "md5" *and* "password"

MYSQLCrypt      md5

# In the following directives, parts of the strings are replaced at
# run-time before performing queries :
#
# \L is replaced by the login of the user trying to authenticate.
# \I is replaced by the IP address the user connected to.
# \P is replaced by the port number the user connected to.
# \R is replaced by the IP address the user connected from.
# \D is replaced by the remote IP address, as a long decimal number.
#
# Very complex queries can be performed using these substitution strings,
# especially for virtual hosting.

# Query to execute in order to fetch the password

MYSQLGetPW      SELECT Password FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Query to execute in order to fetch the system user name or uid

MYSQLGetUID     SELECT Uid FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Optional : default UID - if set this overrides MYSQLGetUID

#MYSQLDefaultUID 1000

# Query to execute in order to fetch the system user group or gid

MYSQLGetGID     SELECT Gid FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Optional : default GID - if set this overrides MYSQLGetGID

#MYSQLDefaultGID 1000

# Query to execute in order to fetch the home directory

MYSQLGetDir     SELECT Dir FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Optional : query to get the maximal number of files
# Pure-FTPd must have been compiled with virtual quotas support.

MySQLGetQTAFS  SELECT QuotaFiles FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Optional : query to get the maximal disk usage (virtual quotas)
# The number should be in Megabytes.
# Pure-FTPd must have been compiled with virtual quotas support.

MySQLGetQTASZ  SELECT QuotaSize FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Optional : ratios. The server has to be compiled with ratio support.

MySQLGetRatioUL SELECT ULRatio FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MySQLGetRatioDL SELECT DLRatio FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Optional : bandwidth throttling.
# The server has to be compiled with throttling support.
# Values are in KB/s .

MySQLGetBandwidthUL SELECT ULBandwidth FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MySQLGetBandwidthDL SELECT DLBandwidth FROM users WHERE User="\L" AND Status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

# Enable ~ expansion. NEVER ENABLE THIS BLINDLY UNLESS :
# 1) You know what you are doing.
# 2) Real and virtual users match.

# MySQLForceTildeExpansion 1

Также проверьте что пользователь ftpuser добавлен в систему и ему даны права на базу ftpuser 
(пользователь создается как обычно через adduser)
Следующий этап - это создание админского аккаунта для доступа на вэб панель.

Конфиги для Pure-Ftpd

echo "50001 50091" > /etc/pure-ftpd/conf/PassivePortRange
echo "yes" > /etc/pure-ftpd/conf/ChrootEveryone
echo "yes" > /etc/pure-ftpd/conf/DontResolve
echo "etc/pure-ftpd/db/mysql.conf " > /etc/pure-ftpd/conf/MySQLConfigFile
echo "1000" > /etc/pure-ftpd/conf/MinUID
echo "yes" > /etc/pure-ftpd/conf/NoAnonymous
echo "UTF-8" > /etc/pure-ftpd/conf/FSCharset

Перезапускаем pure-ftpd - /etc/init.d/pure-ftpd-mysql restart

Открываем наш браузер http://ip-address/ftp и вбиваем пароль который мы задали при утснавке.



Комментариев нет:

Отправить комментарий