пятница, 6 февраля 2015 г.

Установка и настройка консольного торрент клиента и веб-морды

Будем ставить rtorrent т.к судя по отзывам и тому как он работает все замечательно а в качестве вебморды wtorrent итак, приступим!

Мой сервак стоит на: debian 7 (64)

Установка и настройка RTorrent

# sudo apt-get install rtorrent

Теперь нам нужно определиться под каким пользователем у нас будет запускаться торрент клиент например genadiy т.к я не хочу сильно замарачиваться с выставлением прав на дерриктории то веб сервер и торрент клиент у меня будет под одним пользователем genadiy например. 

# cd /home/genadiy
# nano .rtorrent.rc

А теперь вписываем туда вот это и не забудьте про пользователя genadiy 

min_peers = 1
max_peers = 1000
download_rate = 0
upload_rate = 0
directory = /home/genadiy/media-server/download/
session = /home/genadiy/.rtorrent_session/
schedule = watch_directory,5,5,load_start=/home/genadiy/media-server/torrents/*.torrent

port_range = 40890-40890
port_random = no
check_hash = yes
session_save = yes
encryption = allow_incoming,enable_retry,prefer_plaintext 
use_udp_trackers = yes
dht = auto
dht_port = 6881
encoding_list = UTF-8
scgi_port = 127.0.0.1:5000

Жмем ctrl + x, потмо  shift + y и жмем enter

Теперь нам нужно создать 4е папки 
если вы все делаете по порядку, то вы должны быть в дерриктории /home/genadiy

# mkdir .rtorrent_session
# mkdir media-server
# mkdir media-server/donwload
# mkdir media-server/torrents

В общем rtorrent настроен, теперь возьмите любой торрент файл и закиньте его в /home/genadiy/media-server/torrents

после чего запустите rtorrent и убедитесь что в папку /home/genadiy/media-server/download пошла закачка файла/ов

# rtorrent

Для выхода из программы нажмите пару раз ctrl+ q

Первая часть завершена, во второй части мы заставим  rtorrent запускаться при старте системы
И напоследок, если хотите что бы торрент работал на заднем фоне, то пропишите
# screen -dmUS torrent /usr/bin/rtorrent

Это обеспечит работу клиента до перезагрузки или закрытия сессии 

# screen -ls
Эта команда покажет какие сессии сейчас активны

# screen -X -S 2889 quit

2889 это первые цифры ID сессии эти цифры можно посмотреть в screen -ls


Вторая часть, автозапуск rtorrent после старта системы

Теперь нам нужно что бы rtorrent работал всегда

# cd /etc/init.d/
# sudo nano rtorrent.sh

Далее вписываем то что указано выше и не забудьте поменять user="genadiy" скрипт с небольшим фиксов в заголовке, по этому все должно заработать без проблем

#!/bin/sh
### BEGIN INIT INFO
# Provides:          skeleton
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.
### END INIT INFO
#############
###<Notes>###
#############
# This script depends on screen.
# For the stop function to work, you must set an
# explicit session directory using ABSOLUTE paths (no, ~ is not absolute) in your rtorrent.rc.
# If you typically just start rtorrent with just "rtorrent" on the
# command line, all you need to change is the "user" option.
# Attach to the screen session as your user with 
# "screen -dr rtorrent". Change "rtorrent" with srnname option.
# Licensed under the GPLv2 by lostnihilist: lostnihilist _at_ gmail _dot_ com
##############
###</Notes>###
##############

#######################
##Start Configuration##
#######################
# You can specify your configuration in a different file 
# (so that it is saved with upgrades, saved in your home directory,
# or whateve reason you want to)
# by commenting out/deleting the configuration lines and placing them
# in a text file (say /home/user/.rtorrent.init.conf) exactly as you would
# have written them here (you can leave the comments if you desire
# and then uncommenting the following line correcting the path/filename 
# for the one you used. note the space after the ".".
# . /etc/rtorrent.init.conf

#Do not put a space on either side of the equal signs e.g.
# user = user 
# will not work
# system user to run as
user="genadiy"

# the system group to run as, not implemented, see d_start for beginning implementation
# group=`id -ng "$user"`

# the full path to the filename where you store your rtorrent configuration
config="`su -c 'echo $HOME' $user`/.rtorrent.rc"

# set of options to run with
options=""

# default directory for screen, needs to be an absolute path
base="`su -c 'echo $HOME' $user`"

# name of screen session
srnname="rtorrent"

# file to log to (makes for easier debugging if something goes wrong)
logfile="/var/log/rtorrentInit.log"
#######################
###END CONFIGURATION###
#######################
PATH=/usr/bin:/usr/local/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin
DESC="rtorrent"
NAME=rtorrent
DAEMON=$NAME
SCRIPTNAME=/etc/init.d/$NAME

checkcnfg() {
    exists=0
    for i in `echo "$PATH" | tr ':' '\n'` ; do
        if [ -f $i/$NAME ] ; then
            exists=1
            break
        fi
    done
    if [ $exists -eq 0 ] ; then
        echo "cannot find rtorrent binary in PATH $PATH" | tee -a "$logfile" >&2
        exit 3
    fi
    if ! [ -r "${config}" ] ; then 
        echo "cannot find readable config ${config}. check that it is there and permissions are appropriate" | tee -a "$logfile" >&2
        exit 3 
    fi 
    session=`getsession "$config"` 
    if ! [ -d "${session}" ] ; then
        echo "cannot find readable session directory ${session} from config ${config}. check permissions" | tee -a "$logfile" >&2
        exit 3
    fi
}

d_start() {
  [ -d "${base}" ] && cd "${base}"
  stty stop undef && stty start undef
  su -c "screen -ls | grep -sq "\.${srnname}[[:space:]]" " ${user} || su -c "screen -dm -S ${srnname} 2>&1 1>/dev/null" ${user} | tee -a "$logfile" >&2
  # this works for the screen command, but starting rtorrent below adopts screen session gid
  # even if it is not the screen session we started (e.g. running under an undesirable gid
  #su -c "screen -ls | grep -sq "\.${srnname}[[:space:]]" " ${user} || su -c "sg \"$group\" -c \"screen -fn -dm -S ${srnname} 2>&1 1>/dev/null\"" ${user} | tee -a "$logfile" >&2
  su -c "screen -S "${srnname}" -X screen rtorrent ${options} 2>&1 1>/dev/null" ${user} | tee -a "$logfile" >&2
}

d_stop() {
    session=`getsession "$config"`
    if ! [ -s ${session}/rtorrent.lock ] ; then
        return
    fi
    pid=`cat ${session}/rtorrent.lock | awk -F: '{print($2)}' | sed "s/[^0-9]//g"`
    if ps -A | grep -sq ${pid}.*rtorrent ; then # make sure the pid doesn't belong to another process
        kill -s INT ${pid}
    fi
}

getsession() { 
    session=`cat "$1" | grep "^[[:space:]]*session[[:space:]]*=" | sed "s/^[[:space:]]*session[[:space:]]*=[[:space:]]*//" `
    echo $session
}

checkcnfg

case "$1" in
  start)
    echo -n "Starting $DESC: $NAME"
    d_start
    echo "."
    ;;
  stop)
    echo -n "Stopping $DESC: $NAME"
    d_stop
    echo "."
    ;;
  restart|force-reload)
    echo -n "Restarting $DESC: $NAME"
    d_stop
    sleep 1
    d_start
    echo "."
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0


Теперь жмем ctrl+x потом shift + y и enter
Теперь нужно что бы этот скрипт запускался при старте системы

# sudo chmod +x rtorrent.sh
# sudo chown root:root rtorrent.sh
update-rc.d rtorrent.sh defaults
/etc/init.d/rtorrent.sh start

Вот и все, в первой строке мы разрешили выполнение скрипта, во второй указали что запуск идет от root в третьей поставили на автозагрузку а в 4й мы запустили торрент клиент


Третья часть, установка и настройка wtorrent

У меня веб-сервер имеет сл. структуру /home/genadiy/поддомен/public_html
И новый поддомен будет называться torrent

Заходим на трекер github и качаем zip архив с исходниками https://github.com/wtorrent/wtorrent

Теперь нам надо установить модуль для apache

# sudo apt-get install php5-curl libapache2-mod-scgi sqlite3 php5-sqlite
# sudo nano /etc/apache2/apache2.conf

В самый конец запихиваем (с новой строки):
SCGIMount /RPC2 127.0.0.1:5000

# sudo a2enmod scgi
# sudo apache2ctl restart

Теперь когда в общем то все настроено берем тот архив что качали с гихаба и распаковываем содержимое в /home/genadiy/torrent/public_html
Там у нас должно быть 3и файла и примерно 7 папок. после чего заходим(в моем случае) torrent.localhost/install.php в общем то там ничего не нужно трогать, только не забудьте справа указать логин и пароль, вы будите под ним заходить
После всего этого удалите install.php
И на всякий случай перезагрузите сервер :)
На это все, возможно эта статья немного измениться, сейчас я пробую переустановить все и если будут какие то косяки я напишу о них.

На всякий случай

У вас могут возникнуть проблемы с закачкой торрента через веб морду, по этому тут выложу свой конфиг который у меня лежит например тут: /home/devjcat/torrent/public_html/conf/user.conf.php

<?php
define ('LANGUAGE', 'en');
define ('DB_FILE', 'db/database.db');
define ('RT_HOST', 'localhost');
define ('RT_PORT', 80);
define ('RT_DIR', '/RPC2');
define ('RT_AUTH', false);
define ('RT_USER', '');
define ('RT_PASSWD', '');
define ('NO_MULTICALL', true);
define ('EFFECTS', true);
define ('DIR_TORRENTS', '../../media-server/torrents/');
define ('DIR_EXEC', '/home/genadiy/torrent/public_html/');
define ('DIR_DOWNLOAD', '/home/genadiy/media-server/download/');
?>

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

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