Note to Self

Linux/PHP and more
  • Home
  • Coding
  • Linux
  • Other
  • Archives

Irssi config

2010/11/26 | 09:36

After the last power failure of our server I decided to work out how to make Irssi autoreconnect to the channels/servers of my choice. This was pretty easily done.

vim .irssi/config

#Here you define the servers you want to use
#Chatnet is just an alias, you can write whatever here
servers = (
{
        address = "irc.url.se";
        chatnet = "SOMEALIAS";
        port = "6667";
        password = "XXX";
        use_ssl = "no";
        ssl_verify = "no";
        autoconnect = "yes";
}
{
        address = "irc.url2.se";
        chatnet = "SOMEOTHERALIAS";
        port = "6667";
        use_ssl = "no";
        ssl_verify = "no";
        autoconnect = "yes";
}
);

chatnets = {
        SOMEALIAS = { type = "IRC"; };
        SOMEOTHERALIAS = { type = "IRC"; };
};

channels = (
        { name = "#CHANNELNAMEHERE"; chatnet = "SOMEALIAS"; autojoin = "yes"; },
        { name = "#CHANNELNAMEHERE"; chatnet = "SOMEOTHERALIAS"; autojoin = "yes"; },
);
#THIS SECTIONS DEALS WITH YOUR CHANNELS.  THE NUMBER IS THE WINDOW NUMBER
#A CHANNEL WILL APPEAR IN.
windows = {
  1 = { immortal = "yes"; name = "(status)"; level = "ALL"; };
  2 = {
    items = (
      {
        type = "CHANNEL";
        chat_type = "IRC";
        name = "#CHANNELNAMEHERE";
        tag = "SOMEALIAS";
      }
    );
  };
  3 = {
    items = (
      {
        type = "CHANNEL";
        chat_type = "IRC";
        name = "#CHANNELNAMEHERE";
        tag = "SOMEOTHERALIAS";
      }
    );
  };
};
mainwindows = { 1 = { first_line = "1"; lines = "22"; }; };
Comments
No Comments »
Categories
Linux
Comments rss Comments rss

apt-file

2010/11/17 | 23:01

Great little command for finding weird includes.

apt-file search
#for example
apt-file search libgtk-x11-2.0.so

Comments
No Comments »
Categories
Linux
Comments rss Comments rss

Samba

2010/11/17 | 11:26

Samba is great for sharing your files from Linux to Windows. This configuration seems to work very well with Windows 7 & Ubuntu 11.10.

apt-get install samba samba-common samba-common-bin samba-doc

/etc/samba/smb.conf

[global]
name resolve order = wins lmhosts hosts bcast
netbios name = some_name
wins support = yes
workgroup = WORKGROUP
server string = %h server (Samba, Ubuntu)
domain master = yes
unix extensions  = no
#bind interfaces only = True
#interfaces = eth0 192.168.1.3
hosts deny = ALL
hosts allow = 192.168.1.0/24 127.0.0.1 10.0.0.1
log file = /var/log/samba/%m.log
max open files = 100000
log level = 2
follow symlinks = no
security = share
encrypt passwords = true
smb passwd file = /etc/samba/smbpasswd
socket options = TCP_NODELAY IPTOS_LOWDELAY
level2 oplocks = True
read raw = no
panic action = /usr/share/samba/panic-action %d
local master = Yes
preferred master = Yes
os level = 255
dns proxy = No
load printers = No
printing = bsd
printcap name = /dev/null
disable spoolss = yes

[folder]
        comment = some_name
        printable = no
        available = yes
        browseable = yes
        writeable = yes
        force user = user
        force group = user
        public = yes
        read only = no
        create mask = 0777
        directory mask = 0777
        path = /home/user/folder
Comments
No Comments »
Categories
Linux
Comments rss Comments rss

Apache2 rewrite+ssl+roundcube

2010/10/21 | 10:32

Decided to write down how I made the rewrite + ssl for an e-mail server. What I want to do is instead of getting to roundcube with http://hostname.se/webmail I only want to use webmail.hostname.se. Aswell I want it to go to HTTPS by itself.

This is tested and working on Ubuntu 10.04 and 10.10 server edition.

Here we go.

First create the certs and copy them to the necessary folders

sudo -s
openssl req -new -x509 -nodes -out /etc/ssl/certs/server.crt -keyout /etc/ssl/private/server.key
#OBS! Common name should be your servers hostname
a2enmod rewrite
a2enmod ssl
a2ensite default-ssl
chmod 400 /etc/ssl/private/server.key
#Rest will be done in the apache2 folder
cd /etc/apache2

ports.conf

NameVirtualHost *:80
Listen 80
<IfModule mod_ssl.c>
NameVirtualHost *:443
    Listen 443
</IfModule>

apache2.conf

#leave most as is, just add servername
#ServerRoot "/etc/apache2"
ServerName yourhostname

sites-available

touch sites-available/webmail
touch sites-available/webmail-ssl
cd sites-available

sites-available/webmail

<VirtualHost *:80>
        ServerAdmin user@hostname.se
        ServerName webmail.hostname.se
RewriteEngine   on
RewriteCond     %{SERVER_PORT} ^80$
RewriteRule     ^(.*)$ https://webmail.hostname.se$1 [L,R]
RewriteLog      "/var/log/apache2/rewrite.log"
RewriteLogLevel 2
</VirtualHost>

sites-available/webmail-ssl

<IfModule mod_ssl.c>
<VirtualHost *:443>
        ServerAdmin user@hostname.se
        Servername webmail.hostname.se
        DocumentRoot /var/lib/roundcube
    <Directory /var/lib/roundcube>
        Options -Indexes IncludesNOEXEC FollowSymLinks
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/server.crt
SSLCertificateKeyFile /etc/ssl/private/server.key
BrowserMatch ".*MSIE.*" \
        nokeepalive ssl-unclean-shutdown \
        downgrade-1.0 force-response-1.0
</VirtualHost>
</IfModule>

Enabling the sites

a2ensite webmail
a2ensite webmail-ssl
#check that your sites is enabled
ls -l /etc/apache2/sites-enabled/
#output should be like this
000-default -&gt; ../sites-available/default
default-ssl -&gt; ../sites-available/default-ssl
webmail -&gt; ../sites-available/webmail
webmail-ssl -&gt; ../sites-available/webmail-ssl
#restart the webserver, all should be well
/etc/init.d/apache2 restart
#now test it out by entering webmail.url.com in a webbrowser
Comments
2 Comments »
Categories
Linux
Comments rss Comments rss

Cacti 0.8.7g + WeatherMap 0.97a

2010/09/28 | 11:09

To get this to work you need a very old version of Ubuntu. These days I recommend Observium with Weathermap addon.

Here’s one which have explained how to install it very nicely: http://blog.best-practice.se/2014/07/using-php-weathermap-with-observium.html

/V

First we download the programs and install the plugin structure:

sudo -s
mkdir cacti_weathermap
cd cacti_weathermap
apt-get install cacti-spine
wget http://mirror.cactiusers.org/downloads/plugins/cacti-plugin-0.8.7g-PA-v2.8.tar.gz
tar xvf cacti-plugin-0.8.7g-PA-v2.8.tar.gz
wget http://www.network-weathermap.com/files/php-weathermap-0.97a.zip
unzip php-weathermap-0.97a.zip
cd cacti-plugin-arch/files-0.8.7g
sudo cp -R * /usr/share/cacti/site/
cd ..
mysql cacti < pa.sql -u root -p
sudo vim /usr/share/cacti/site/include/global.php
#row 107:
$config["rra_path"] = $config["base_path"]."/rra";
#change it to:
$config["rra_path"] = '/var/lib/cacti/rra';
#row 197
include($config["library_path"]."/adodb/adodb.inc.php");
#change it to:
include("/usr/share/php/adodb/adodb.inc.php");
#row 100
$config['url_path'] = $url_path;
#change to
$config['url_path'] = '/cacti/';
#below row 42 $cacti_session_name = "Cacti"; add
/* Weathermap */
$plugins = array();
$plugins[] = 'monitor';
$plugins[] = 'weathermap';
#save and quit
sudo chmod 644 /usr/share/cacti/site/lib/plugins.php
sudo chmod 644 /usr/share/cacti/site/include/plugins.php

Source: http://58.96.99.76/joomla/index.php/tech-a-it-stuff/networking-other/66-cacti-plugin-architecture-install-on-ubuntu

Then we install weathermap:

cd ..
mv weathermap/ /usr/share/cacti/site/plugins
chown -R www-data:www-data /usr/share/cacti/site/plugins

#http://url.to.host/cacti/index.php should greet you with http://url.to.host/cacti/install.php. Just press next etc and all should be well.

Now login and set the permissions for your user

mv /usr/share/cacti/site/plugins/weathermap/editor-config.php-dist /usr/share/cacti/site/plugins/weathermap/editor-config.php
chmod u+w /usr/share/cacti/site/plugins/weathermap/configs
#Now we need to secure the editor
vim /etc/apache2/conf.d/weathermap
<Directory /usr/share/cacti/site/plugins/weathermap>
        <Files editor.php>
            Order Deny,Allow
            Deny from all
            Allow from 127.0.0.1
        </Files>
    </Directory>
/etc/init.d/apache2 restart
vim /usr/share/cacti/site/plugins/weathermap/editor.php
#change
$ENABLED=false;
#to
$ENABLED=true;
#change
$cacti_base = 'C:/httpd-.2_x64/htdocs/cacti';
#to
$cacti_base = '/usr/share/cacti/site';
#change
$cacti_url = "http://support.company.net/cacti/";
#to
$cacti_url = "http://url.to.host/cacti/";

Source: http://www.network-weathermap.com/manual/latest/pages/install-cacti-editor.html

Tips:
After the installation of everything you might need to go into Cacti and set Spine as poller again.

Here is how my rudimentary homenetwork looks like (I just used icons that are included, you can use your own pictures).

Comments
8 Comments »
Categories
Linux
Comments rss Comments rss

Postfix with SMTP auth (TLS/SASL)

2010/05/28 | 13:09

I’ve removed the other guide, easier to maintain one guide. This server will allow relay for specified nets and also TLS encrypted login for users.

Highlighted rows is where you need to make your personalized changes.

Passwords are finally encrypted and working. Thanks to No1Viking @ this thread Ubuntu.se

Update for Ubuntu 11.10 (Dovecot wasn’t working):

Begin with generating a new dovecot.conf from your old one with:

cd /etc/dovecot
doveconf -n > dovecot-new.conf
mv dovecot.conf dovecot.conf_old
mv dovecot-new.conf dovecot.conf
#Then edit the dovecot.conf and search for service auth {
#Comment out this row
#       user = nobody
/etc/init.d/dovecot restart
#Now dovecot should restart and work.

These are the programs I used to do it:
Amavis, Dovecot, SpamAssassin, Clamav, Postfixadmin, Postfix, Mailgraph and Roundcube for webmail.

Install the necessary packages

sudo -s
apt-get install dovecot-common dovecot-imapd dovecot-pop3d postfix postfix-mysql mysql-server spamassassin clamav mailgraph roundcube roundcube-mysql amavisd-new php5-imap clamav-daemon
#Choose Internetsystem when postfix asks.
#Allow roundcube to setup the database with db-common.

Setting up

Create the necessary folders, user and permission

useradd -r -u 150 -g mail -d /var/vmail -s /sbin/nologin -c "Virtual mailbox" vmail
sudo mkdir /var/vmail
sudo chmod 770 /var/vmail/
sudo chown -R vmail:mail /var/vmail/
sudo mysql -u root -p
CREATE DATABASE mail;
GRANT ALL PRIVILEGES ON mail.* TO 'mail'@'localhost' IDENTIFIED BY 'mail';
exit

Dovecot

Dovecot is the program that gets the mails from the local folder to your client.

/etc/dovecot/dovecot.conf

## Dovecot configuration file
#
base_dir = /var/run/dovecot/
#
protocols = imaps pop3s
protocol imap {
        #listen = *:143
        ssl_listen = *:993
}
protocol pop3 {
        #listen = *:110
        ssl_listen = *:995
}
ssl_cert_file = /etc/ssl/certs/smtpd.crt
ssl_key_file = /etc/ssl/private/smtpd.key

log_timestamp = "%Y-%m-%d %H:%M:%S "
syslog_facility = mail

# Where the mailboxes are located
mail_location = maildir:/var/vmail/%d/%n

mail_access_groups = mail
mail_debug = no
first_valid_uid = 150
last_valid_uid = 150
maildir_copy_with_hardlinks = yes

protocol imap {
        login_executable = /usr/lib/dovecot/imap-login
        mail_executable = /usr/lib/dovecot/imap
        imap_max_line_length = 65536
}
protocol pop3 {
        login_executable = /usr/lib/dovecot/pop3-login
        mail_executable = /usr/lib/dovecot/pop3
        pop3_uidl_format = %08Xu%08Xv
}
protocol lda {
        postmaster_address = info@hostname.com
        sendmail_path = /usr/lib/sendmail
        auth_socket_path = /var/run/dovecot/auth-master
}

auth_verbose = no
auth_debug = no
auth_debug_passwords = no

auth default {
        mechanisms = digest-md5 plain
        passdb sql {
        args = /etc/dovecot/dovecot-sql.conf
        }
        userdb sql {
        args = /etc/dovecot/dovecot-sql.conf
        }
        user = nobody
        socket listen {
                master {
                path = /var/run/dovecot/auth-master
                mode = 0660
                user = vmail
                group = mail
                }
                client {
                path = /var/spool/postfix/private/auth
                mode = 0660
                user = postfix
                group = postfix
                }
        }
}

/etc/dovecot/dovecot-sql.conf

driver = mysql
connect = host=localhost dbname=mail user=mail password=mail
# The new name for MD5 is MD5-CRYPT so you might need to change this depending on version
#default_pass_scheme = MD5-CRYPT #uncomment this if you want encrypted passwords in db
default_pass_scheme = MD5
# Get the mailbox
user_query = SELECT maildir, 150 AS uid, 8 AS gid FROM mailbox WHERE username = '%u'
#get the password
password_query = SELECT password FROM mailbox WHERE username = '%u' AND active = '1'
#EOF

Postfix

Postfix is the program that sends/recieve e-mail.

/etc/postfix/main.cf

content_filter = amavis:[127.0.0.1]:10024
smtpd_banner = $myhostname ESMTP $mail_name
biff = no
append_dot_mydomain = no
#delay_warning_time = 4h
myhostname = mail.hostname.com
myorigin = hostname.com
mydestination = localhost
relayhost =
mynetworks = 127.0.0.0/8 192.168.1.0/24
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
# Virtual mailbox settings
virtual_mailbox_domains = proxy:mysql:$config_directory/mysql_virtual_domains_maps.cf
virtual_mailbox_base = /var/vmail
virtual_mailbox_maps = proxy:mysql:$config_directory/mysql_virtual_mailbox_maps.cf
virtual_alias_maps = proxy:mysql:$config_directory/mysql_virtual_alias_maps.cf
virtual_minimum_uid = 150
virtual_uid_maps = static:150
virtual_gid_maps = static:8
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1
# SASL Authentication
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
alias_maps = hash:/etc/postfix/aliases
alias_database = hash:/etc/postfix/aliases
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, reject_unknown_recipient_domain
smtpd_data_restrictions =  reject_unauth_pipelining, reject_multi_recipient_bounce, permit
smtpd_client_restrictions = reject_unauth_pipelining
smtpd_sender_restrictions = reject_non_fqdn_sender, reject_unknown_sender_domain
smtpd_etrn_restrictions = reject
strict_rfc821_envelopes = yes
smtpd_helo_required = yes
disable_vrfy_command = yes
allow_percent_hack = no
smtpd_recipient_limit = 50
smtpd_soft_error_limit = 25
smtpd_hard_error_limit = 25
smtpd_client_connection_count_limit = 10
smtpd_client_connection_rate_limit = 20
message_size_limit = 104857600
# TLS
smtp_tls_security_level = may
smtpd_tls_security_level = may
smtpd_tls_auth_only = no
smtp_tls_note_starttls_offer = yes
smtpd_tls_key_file = /etc/ssl/private/smtpd.key
smtpd_tls_cert_file = /etc/ssl/certs/smtpd.crt
#smtpd_tls_CAfile = /etc/ssl/certs/cacert.pem #dunno if this really is needed to use, therefore commented out in my example
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom

/etc/postfix/master.cf

#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master").
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
#submission inet n       -       -       -       -       smtpd
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       -       -       -       smtpd
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628      inet  n       -       -       -       -       qmqpd
pickup    fifo  n       -       -       60      1       pickup
 -o content_filter=
 -o receive_override_options=no_header_body_checks
cleanup   unix  n       -       -       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
#qmgr     fifo  n       -       -       300     1       oqmgr
tlsmgr    unix  -       -       -       1000?   1       tlsmgr
rewrite   unix  -       -       -       -       -       trivial-rewrite
bounce    unix  -       -       -       -       0       bounce
defer     unix  -       -       -       -       0       bounce
trace     unix  -       -       -       -       0       bounce
verify    unix  -       -       -       -       1       verify
flush     unix  n       -       -       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       -       -       -       smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay     unix  -       -       -       -       -       smtp
        -o smtp_fallback_relay=
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       -       -       -       showq
error     unix  -       -       -       -       -       error
retry     unix  -       -       -       -       -       error
discard   unix  -       -       -       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       -       -       -       lmtp
anvil     unix  -       -       -       -       1       anvil
scache    unix  -       -       -       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
dovecot unix - n n - - pipe flags=DRhu user=vmail:mail argv=/usr/lib/dovecot/deliver -d $(recipient)
amavis unix - - - - 2 smtp
 -o smtp_data_done_timeout=1200
 -o smtp_send_xforward_command=yes
 -o disable_dns_lookups=yes
 -o max_use=20
127.0.0.1:10025 inet n - - - - smtpd
 -o content_filter=
 -o local_recipient_maps=
 -o relay_recipient_maps=
 -o smtpd_restriction_classes=
 -o smtpd_delay_reject=no
 -o smtpd_client_restrictions=permit_mynetworks,reject
 -o smtpd_helo_restrictions=
 -o smtpd_sender_restrictions=
 -o smtpd_recipient_restrictions=permit_mynetworks,reject
 -o smtpd_data_restrictions=reject_unauth_pipelining
 -o smtpd_end_of_data_restrictions=
 -o mynetworks=127.0.0.0/8
 -o smtpd_error_sleep_time=0
 -o smtpd_soft_error_limit=1001
 -o smtpd_hard_error_limit=1000
 -o smtpd_client_connection_count_limit=0
 -o smtpd_client_connection_rate_limit=0
 -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks

/etc/postfix/mysql_virtual_alias_maps.cf

user = mail
password = mail
hosts = localhost
dbname = mail
table = alias
select_field = goto
where_field = address
additional_conditions = and active = '1'

/etc/postfix/mysql_virtual_domains_maps.cf

user = mail
password = mail
hosts = localhost
dbname = mail
table = domain
select_field = domain
where_field = domain
additional_conditions = and backupmx = '0' and active = '1'

/etc/postfix/mysql_virtual_mailbox_limit_maps.cf

user = mail
password = mail
hosts = localhost
dbname = mail
table = mailbox
select_field = quota
where_field = username
additional_conditions = and active = '1'

/etc/postfix/mysql_virtual_mailbox_maps.cf

user = mail
password = mail
hosts = localhost
dbname = mail
table = mailbox
select_field = CONCAT(domain,'/',maildir)
where_field = username
additional_conditions = and active = '1'

Creating the certs for TLS

touch smtpd.key
chmod 600 smtpd.key
openssl genrsa 1024 > smtpd.key
openssl req -new -key smtpd.key -x509 -days 3650 -out smtpd.crt # has prompts
openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650 # has prompts
sudo mv smtpd.key /etc/ssl/private/
sudo mv smtpd.crt /etc/ssl/certs/
sudo mv cakey.pem /etc/ssl/private/
sudo mv cacert.pem /etc/ssl/certs/

Amavis

/etc/amavis/conf.d/15-content_filter_mode

#uncomment these lines, no need to change or replace them
@bypass_virus_checks_maps = (
\%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);
@bypass_spam_checks_maps = (
\%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

/etc/amavis/conf.d/50-user

use strict;
$sa_spam_subject_tag = '***SPAM*** ';
$myhostname = 'hostname.dnsname.com';
@local_domains_maps = ( read_hash("/var/vmail/local_domains") );
@inet_acl = qw(127.0.0.1 [::1]);
$enable_dkim_verification = 1;  # enable DKIM signatures verification
$enable_dkim_signing = 1;    # load DKIM signing code, keys defined by dkim_key
$sa_tag_level_deflt = 2.0;
$sa_tag2_level_deflt = 3.0;
$sa_kill_level_deflt = 4.3;
$sa_dsn_cutoff_level = 10;
$sa_quarantine_cutoff_level = 20;
$sa_local_tests_only = 0;
$final_virus_destiny = D_DISCARD;
$final_banned_destiny = D_BOUNCE;
$final_spam_destiny = D_BOUNCE;
$final_bad_header_destiny = D_PASS;
$warnvirusrecip = 1;
$clean_quarantine_to = undef;
$virus_quarantine_to = undef;
$banned_quarantine_to = undef;
$bad_header_quarantine_to = undef;
$spam_quarantine_to = undef; #here you can specify a e-mail if you want to collect the spam, for instance = 'spam\@host.domain.com';
$spam_quarantine_bysender_to = undef;
$X_HEADER_TAG = 'X-Virus-Scanned';
$X_HEADER_LINE = "by Amavis+SpamAssassin+ClamAV and more at $mydomain";
$undecipherable_subject_tag = '[**CONTENTS NOT ANALYSED**]';
##### Do not modify anything below this #####
1;  # ensure a defined return

Spamassassin

vim /etc/default/spamassassin
ENABLED=1

/etc/spamassassin/local.cf

#uncomment
use_bayes 1
bayes_auto_learn 1

Clamav

sudo adduser clamav amavis
vim /etc/group
#make sure clamav is a part of amavis group
clamav:x:nr:amavis
amavis:x:nr:clamav

No more should be needed to get clamav running.

Postfixadmin

Download and install postfixadmin, it should ask for the database to use and setup the necessary tables.

http://downloads.sourceforge.net/project/postfixadmin/postfixadmin/postfixadmin-2.3.2/postfixadmin-2.3.2_all.deb?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fpostfixadmin%2Ffiles%2F&ts=1283411400&use_mirror=cdnetworks-us-1
dpkg -i postfixadmin_2.3.2_all.deb
vim /etc/apache2/conf.d/postfixadmin
#replace all with
Alias /postfixadmin /usr/share/postfixadmin
 <Directory /usr/share/postfixadmin>
  Options FollowSymLinks Indexes
  AllowOverride Limit Options FileInfo
  <Limit GET POST>
        order deny,allow
        deny from all
        allow from ip.to.host.X
        allow from range.if.youlike.0/24
  </Limit>
</Directory>

I’m pretty sure postfixadmin installs it’s database to “postfixadmin”. This will not work in our example. It’s very easy to fix that though.

vim /etc/postfixadmin/config.inc.php
#change lines 50-54 to these
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'mail';
$CONF['database_password'] = 'mail';
$CONF['database_name'] = 'mail';
#now we also need to run http://url.to.host/postfixadmin/setup.php and check so all goes well. Then choose a superadmin password so you get the hash.
#Then change row 31 to the hash 
$CONF['setup_password'] = 'false'; #change this to the hash row
#also you might to want to change
$CONF['admin_email'] = 'admin@your.host.com';
$CONF['encrypt'] = 'md5crypt'
$CONF['authlib_default_flavor'] = 'md5raw';
#check the file, there is alot of easy options to choose and change

Roundcube

/etc/roundcube/main.inc.php

change these lines:
$rcmail_config['default_host'] = 'ssl://localhost:993';
$rcmail_config['default_port'] = 143;
$rcmail_config['auto_create_user'] = TRUE;
$rcmail_config['imap_auth_type'] = auth;
$rcmail_config['smtp_server'] = 'localhost';
$rcmail_config['smtp_port'] = 25;
$rcmail_config['smtp_helo_host'] = 'host.name.com';
$rcmail_config['date_long'] = 'Y.m.d H:i';
$rcmail_config['product_name'] = 'My Webmail';
$rcmail_config['create_default_folders'] = TRUE;
also fix roundcube in apache
#uncomment
Alias /roundcube /var/lib/roundcube
#change begin from row 18->26 under  <Directory /var/lib/roundcube/>
<Directory /var/lib/roundcube/>
  Options +FollowSymLinks
  # This is needed to parse /var/lib/roundcube/.htaccess. See its
  # content before setting AllowOverride to None.
  AllowOverride All
  order deny,allow
  deny from all
  allow from ip.to.host.X
  allow from range.if.youlike.0/24
</Directory>

Misc fixes

Now we’re almost done, just need to create the aliases

vim /var/vmail/local_domains
#insert the name of your domain.
cp /etc/aliases /etc/postfix/aliases
#or just create it, seems to be the same for most
vim /etc/postfix/aliases
# /etc/aliases
mailer-daemon: postmaster
postmaster: root
nobody: root
hostmaster: root
usenet: root
news: root
webmaster: root
www: root
ftp: root
abuse: root
noc: root
security: root
root: (yourusername)
clamav: root
#Now we need to create the aliases.db file. It's done with the postalias command.
postalias /etc/postfix/aliases

Restart everything!

/etc/init.d/clamav-daemon restart
/etc/init.d/clamav-freshclam restart
/etc/init.d/dovecot restart
/etc/init.d/postfix restart
/etc/init.d/apache2 restart

Add accounts and test webmail

Login to postfixadmin with http://url/postfixadmin. Here you can add your e-mail accounts, do this before trying to login to roundcube 🙂
After that login to roundcube, http://url/roundcube
If you experience any problems, check /var/log/mail.log

Sources

Most of this material is taken from other webpages which also contains great guides (will list more as I recall them):

  • Postfix guide
  • Ubuntu community Postix guide
Comments
3 Comments »
Categories
Linux
Comments rss Comments rss

SSH wo password + backup.sh

2010/04/21 | 10:01

This is the easiest way I know how to SSH/SCP between hosts without using passwords. When using ssh-keygen just hammer enter, we want a key without password for this to work.

ssh-keygen
ssh-copy-id -i .ssh/id_rsa.pub backupuser@ip.to.host
#Test it out by invoking
ssh backupuser@ip.to.host

You should have gotten in without password. This can then be used to for instance backup from one machine to another easily (without using Bacula). Yes, I know it’s quick and dirty but until I understand Bacula this is the way to do it 🙂
So I created this bash script for my e-mail server backup (thanks vho for the mysqldump script!). I placed the file in /root/ and called it backup.sh
(As you can see I compress a folder called IP_TO_FTP_SERVER, this is a folder created by wget from a local FTP running FileZilla server. This is because it’s running Windows XP and a Swedish billing system called Scrollan.)

Backup.sh

#!/bin/sh
MYSQLDUMP="/usr/bin/mysqldump"
GZIP="/bin/gzip"
MYSQL="/usr/bin/mysql"
dbUser="user_here"
dbPasswd="your_password_here"
dbHost="localhost"
backupDir="/home/backup/your_folder"
#backupDir2="/home/backup/your_second_folder"
time="$(date +"%Y-%m-%d")"
rm $backupDir/$time.*

#kolla revisionerna
/usr/bin/find $backupDir/* -type f -mtime +0 -exec rm {} \;
/usr/bin/find $backupDir2/* -type f -mtime +2 -exec rm {} \;

#Fetch files from local ftp (uncomment to use)
#rm -r /home/backup/192.168.1.254
#wget --directory-prefix=/home/backup --user=backup --password='password_here' --timeout=5 -t 1 -r ftp://192.168.1.254/folder1
#wget --directory-prefix=/home/backup --user=backup --password='password_here' --timeout=5 -t 1 -r ftp://192.168.1.254/folder2

# Fixa dumpningen
allDB="$($MYSQL -u $dbUser -h $dbHost -p$dbPasswd -Bse 'show databases')"

for db in $allDB
do
   $MYSQLDUMP --single-transaction -u $dbUser -h $dbHost -p$dbPasswd $db | $GZIP > "$backupDir/$time.mysql.$db.gz"
done

tar czf $backupDir/$time.dovecot.tgz /etc/dovecot/
tar czf $backupDir/$time.postfix.tgz /etc/postfix/
tar czf $backupDir/$time.mail.tgz /var/vmail/
tar czf $backupDir/$time.apache2.tgz /etc/apache2/
tar czf $backupDir/$time.www.tgz /var/www/
tar czf $backupDir/$time.shorewall.tgz /etc/shorewall/
tar czf $backupDir/$time.dhcp3.tgz /etc/dhcp3/
tar czf $backupDir/$time.roundcube.tgz /etc/roundcube/
tar czf $backupDir/$time.amavis.tgz /etc/amavis/
tar czf $backupDir/$time.spamassassin.tgz /etc/spamassassin/
tar czf $backupDir/$time.clamav.tgz /etc/clamav/
tar czf $backupDir/$time.user.tgz /home/user
tar czf $backupDir/$time.htpasswd.tgz /home/htpasswd
tar czf $backupDir/$time.root.tgz /root/
tar czf $backupDir/$time.samba.tgz /etc/samba
tar czf $backupDir/$time.bind.tgz /etc/bind
tar czf $backupDir/$time.ssl.tgz /etc/ssl
#tar czf $backupDir/$time.scrollan_server.tgz /home/backup/192.168.1.254
cp /etc/pptpd.conf $backupDir/$time.pptpd.conf
cp /etc/hosts $backupDir/$time.hosts
cp /etc/smartd.conf $backupDir/$time.smartd.conf

#säkerhetskopiera dem till servern
scp $backupDir/$time* backupuser@url.to.host:$backupDir

Don’t forget to make the script runnable by chmod +x /root/backup.sh
Then I made the folder /home/backup and added the work to run in cron.

mkdir /home/backup
crontab -e
00 04 * * * /root/backup.sh

Now on the backupservers I’ve done like this (user backup already exists on Ubuntu)

adduser backupuser
mkdir -p /home/backup/hostname
chown -R backupuser:backupuser /home/backup

You should now get some backups, spread the backups around between different secure servers and your good to go when the next HDD crash arrives 🙂

Comments
No Comments »
Categories
Linux, Linux script
Comments rss Comments rss

XBMC + Antec veris + MCE + i3

2010/03/18 | 11:04

This weekend I started having fun with moving my old HTPC from Windows to the Linux world. And I immediately started having problems. The problems is almost always the fun part with Linux though, it can be very frustrating at first but very rewarding when you solve them 🙂

Less chat, more explaining.

I chose Ubuntu after trying Xubuntu because it’s much easier to resize the menus/fonts in Ubuntu so I dont have to squint to read the text on my 40? LCD 1080p TV. But the downside is that Ubuntu provides alot of junk you don’t need.

I find pulseaudio still causing problems, so I just remove it.

sudo apt-get purge pulseaudio
#then reboot

After the reboot you only need to activate the Digital out. This is easily done with alsamixer.

sudo alsamixer

Then scroll right until you can see ie958 o and press m to unmute it (MM is mute) so it says 00?. Now the digital out should work.

Now to install XBMC:

sudo add-apt-repository ppa:team-xbmc
sudo apt-get update
sudo apt-get install xbmc xbmc-standalone

If you are running XBMC on lower end hardware you might want to skip logging in to Gnome. To do this just logout and press the name for your user. Before you login change the session to XBMC in the bottom of the screen and login. This way you only login to XBMC.

Have fun! Dont forget to add ie958 in sound output settings in XBMC!

Microsoft Remote

This is how I made my MCE work with Ubuntu 10.04.1 and XBMC (doesn’t work with 10.10)

sudo apt-get install lirc
#select antec veris on first screen and use default (none on second)
vim /etc/udev/rules.d/99-lirc.rules
#add this
#Prevent the USBHID driver from loading for the Antec Veris
SYSFS{idVendor}=="15c2", SYSFS{idProduct}=="0038", MODE="0666", PROGRAM="/bin/sh -c 'echo -n $id:1.0 >/sys/bus/usb/drivers/usbhid/unbind;\
echo -n $id:1.1 >/sys/bus/usb/drivers/usbhid/unbind'"
#then reboot the HTPC
vim /etc/modprobe.d/lirc_imon.conf
#add this
options lirc_imon ir_protocol=1
vim /etc/lirc/hardware.conf
#change REMOTE_LIRCD_CONF="imon/lircd.conf.imon-antec-veris" to REMOTE_LIRCD_CONF="imon/lircd.conf.imon-mceusb"
vim /etc/lirc/lircd.conf
#Change include "/usr/share/lirc/remotes/imon/lircd.conf.imon-antec-veris" to include "/usr/share/lirc/remotes/imon/lircd.conf.imon-mceusb"
#now restart lirc
/etc/init.d/lirc restart
#try the remote out with irw and push some buttons, you should get output in a terminal window.
#to get the remove to work optimally for XBMC use this lircmap
sudo wget -q http://www.stpit.com/public/Lircmap.xml -O ~/.xbmc/userdata/Lircmap.xml
#now reboot for the modprobe to accept the new values

Credit for lircmap and how-to for MCE goes to stpfarms@forums.xbmc.org

You can try the remote out with the command irw and then just press buttons on it and should get an output. Like this:

mce3

LCD

Now for the LCD we need to install
apt-get install lcdproc

/etc/LCDd.conf

#NOTE: These are just the values I changed and used, leave most of the file intact to avoid bugs.
[server]
DriverPath=/usr/lib/lcdproc/
Driver=imonlcd
Bind=127.0.0.1
Port=13666
ReportLevel=2
ReportToSyslog=yes
User=nobody
Hello="  Ubuntu 10.04"
Hello="    X B M C"
GoodBye="Thanks for using"
GoodBye="   X B M C"
WaitTime=60
ServerScreen=blank
Backlight=open
Heartbeat=off
TitleSpeed=2
ToggleRotateKey=Enter
PrevScreenKey=Left
NextScreenKey=Right
[imon]
Device=/dev/lcd0
Size=16x2
[imonlcd]
Protocol=1
OnExit=0
Device=/dev/lcd0
Contrast=200
DiscMode=1

XBMC

cd /home/user/.xbmc/userdata/

advancedsettings.xml

<advancedsettings>
        <lcd>
                <rows>2</rows><!-- Number of rows to use for the LCD. -->
                <columns>16</columns><!-- Number of columns to use for the LCD. -->
                <scrolldelay>3</scrolldelay><!-- Delay of the scroller widget. Defaults to 1. -->
        </lcd>
</advancedsettings>

LCD.xml

<lcd>
<disableonplay>General</disableonplay>
  <Navigation>
     <line>$INFO[System.CurrentControl]</line>
     <line>$INFO[System.Time] | $INFO[Weather.Temperature]</line>
  </Navigation>
  <Music>
     <line>$INFO[LCD.PlayIcon]$INFO[Player.Time]/$INFO[Player.Duration] Track# $INFO[MusicPlayer.TrackNumber]</line>
     <line>$INFO[MusicPlayer.Title]</line>
     <line>$INFO[MusicPlayer.Artist] - $INFO[MusicPlayer.Album] ($INFO[MusicPlayer.Year])</line>
  </Music>
  <Video>
     <line>$INFO[System.Time]</line>
     <line>$INFO[LCD.PlayIcon] $INFO[Player.Time]/$INFO[Player.Duration]</line>
  </Video>
  <General>
     <line>$INFO[System.CurrentControl]</line>
     <line>$INFO[System.Time] | $INFO[Weather.Temperature]</line>
  </General>
</lcd>

This is how we get pretty icons on the LCD

vim /etc/init.d/imon.perl

#!/usr/bin/perl
use HTTP::Request::Common;
use LWP::UserAgent;
use IO::Socket;

my $sockres;
my $sock;

#see here for details of imon lcd driver output control bits
#http://lcdproc.cvs.sourceforge.net/viewvc/lcdproc/lcdproc/server/drivers/imonlcd.c?view=markup


$sock = new IO::Socket::INET (PeerAddr => 'localhost', PeerPort => '13666', Proto => 'tcp', );

die "Could not create socket: $!\n" unless $sock;

print $sock "hello\n";

$sockres = readline $sock;

do
{

my $output = "";

my $progress = 0;
my $icondata = 0;

my $ua = LWP::UserAgent->new;
my $res = $ua->request(GET 'http://localhost:8080/xbmcCmds/xbmcHttp?command=GetCurrentlyPlaying');

if ($res->is_success)
{
$output = $res->content;

#remove html tags
$output =~ s/<html>//gi;
$output =~ s/<.html>//gi;
$output =~ s/<li>//gi;
}

my @lines = split(/\n/, $output);

foreach my $val (@lines)
{
if ($val =~ /Filename:/i)
{
if ($val =~ /.mpg/i) { $icondata = $icondata | (1<<19) }; #turn on MPG icon
if ($val =~ /.mpeg/i) { $icondata = $icondata | (1<<19) }; #turn on MPG icon
if ($val =~ /.avi/i) { $icondata = $icondata | (2<<19) }; #turn on DIVX icon
if ($val =~ /.wmv/i) { $icondata = $icondata | (4<<19) }; #turn on WMV icon

if ($val =~ /.wma/i) { $icondata = $icondata | (3<<13) }; #turn on WMA icon
if ($val =~ /.mp3/i) { $icondata = $icondata | (1<<13) }; #turn on MP3 icon
if ($val =~ /.ogg/i) { $icondata = $icondata | (2<<13) }; #turn on OGG icon
if ($val =~ /.wav/i) { $icondata = $icondata | (4<<13) }; #turn on WAV icon
}

if ($val =~ /Type:/)
{
if ($val =~ /Video/i) { $icondata = $icondata | (2<<1) }; #turn on MOVIE icon
if ($val =~ /Video/i) { $icondata = $icondata | 1 }; # enable play animation
if ($val =~ /Audio/i) { $icondata = $icondata | (1<<1) }; # turn on MUSIC icon
if ($val =~ /Audio/i) { $icondata = $icondata | 1 }; # enable play animation
if ($val =~ /Picture/i) { $icondata = $icondata | (3<<1) }; # turn on PHOTO icon
}

if ($val =~ /Percentage:/)
{
$val =~ s/Percentage://i;
$progress = $val *32 / 100;
}
}


printf $sock "output %i\n",$icondata;

$sockres = readline $sock;

sleep 1;

printf $sock "output %i\n",(($progress <<6) | (1<<28)); # configure upper progress bar

$sockres = readline $sock;

sleep 1;

} while 1;

close $sock;

Thanks to Phantasm4489 at the XBMC forum for the Perl script.

cd /etc/init.d/
update-rc.d imon.perl defaults 65 65

Dont forget to activate web server and LCD in XBMC, user XBMC, no password, 8080 as port.

Comments
1 Comment »
Categories
Linux
Comments rss Comments rss

rTorrent + ruTorrent 3.4 @Ubuntu 12.04

2010/03/18 | 11:04

In 11.10+ it’s pretty easy to use rTorrent. We don’t need to download and compile rTorrent anymore, apt-get works just fine.

sudo apt-get install rtorrent libapache2-mod-scgi

Now to make the .rtorrent.rc file which should be in the home folder of the user running rtorrent (/home/usernameofyouruser/.rtorrent.rc). In my example I have my download folder as /home/user/nedladdat/torrents/downloads.

# Maximum and minimum number of peers to connect to per torrent.
min_peers = 40
max_peers = 120
# Same as above but for seeding completed torrents (-1 = same as  downloading)
min_peers_seed = 10
max_peers_seed = 50
# Maximum number of simultanious uploads per torrent.
max_uploads = 20
# Global upload and download rate in KiB. "0" for unlimited.
download_rate = 0
upload_rate = 0
# Default directory to save the downloaded torrents.
directory = ~/nedladdat/torrents/downloads
# Default session directory.
session = ~/nedladdat/torrents/rtorrent.session
# Watch a directory for new torrents, restart torrents that have been  copied back and stop those that have been
# deleted.
schedule =  watch_directory,10,10,"load_start=~/nedladdat/torrents/torrentfiles/*.torrent"
schedule = tied_directory,10,10,start_tied=
schedule = untied_directory,10,10,close_untied=
# Close torrents when diskspace is low.
schedule = low_diskspace,5,60,close_low_diskspace=100M
#Stop torrents when reaching upload ratio 300 percent
ratio.enable=
ratio.min.set=300
# Port range to use for listening.
port_range = 6890-6999
# Start opening ports at a random position within the port range.
port_random = yes
# Set whetever the client should try to connect to UDP trackers.
use_udp_trackers = yes
# Encryption options. This can be useful when using an ISP that uses  traffic shaping.
encryption=allow_incoming,try_outgoing,enable_retry,prefer_plaintext
scgi_port = 127.0.0.1:5000
xmlrpc_dialect=i8
#DHT
dht = auto
dht_port = 6881
peer_exchange = yes

You also need to activate scgi support in Apache 2:

sudo a2enmod scgi

Next you need to add the SCGI mount for rTorrent.

sudo vim /etc/apache2/sites-available/default
#And add the following lines at the near-end of the document:
    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options -Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>
SCGIMount /RPC2 127.0.0.1:5000
<location /RPC2>
        <Limit GET POST>
        order deny,allow
        deny from all
        allow from 127.0.0.1
        allow from 192.168.1.254
        allow from 192.168.1.0/24
        </Limit>
</location>
</VirtualHost>

And restart Apache 2:

sudo /etc/init.d/apache2 restart

You are now done with rTorrent, try if it works by logging in the correct user and executing rtorrent. When you see it starts and that you can download for example Ubuntu via torrent then all is fine. You might as “but how do I start the download”, well that’s easy, just place the ubuntu.rtorrent file in /home/user/nedladdat/torrents/torrentfiles (as by my example) and rTorrent should start it by itself.

Now to get a nice GUI for rTorrent we need to download ruTorrent and move this folder to /var/www

wget http://rutorrent.googlecode.com/files/rutorrent-3.4.tar.gz
tar xvzf rutorrent-3.4.tar.gz
mv rutorrent /var/www/rtorrent

You need to change the ownership of the directory of rtorrent in /var/www to www-data.

chown -R www-data:www-data /var/www/rtorrent

Now you can login to http://yourip/rtorrent

Enjoy!

Comments
4 Comments »
Categories
Linux
Comments rss Comments rss

rTorrent + unpack/delete script for rar/zip/001

2010/03/18 | 11:03

A friend of mine said to me: I want a torrent client which will download, then unpack and when I remove the torrent or seed is done it will remove the rar files and keep the rest.

EDIT (2010-08-31): This guide is mostly obsolete now as you can easily just download the plugin unpack to the plugin folder where your rutorrent is installed (v.3.1 required) and it will unpack the files for you.

First you need to download the necessary applications

sudo apt-get install unzip unrar

So, to get your rTorrent to unpack the files on download and delete on
ratio/delete of torrent file you need to modify your .rtorrent.rc file
with these changes:

# Maximum and minimum number of peers to connect to per torrent.
#min_peers = 40
#max_peers = 100

# Same as above but for seeding completed torrents (-1 = same as downloading)
#min_peers_seed = 10
#max_peers_seed = 55
#max_downloads_global = 3
#max_uploads_global = 5

# Maximum number of simultanious uploads per torrent.
#max_uploads = 15

# Global upload and download rate in KiB. "0" for unlimited.
#download_rate = 3000
#upload_rate = 3000

# Default directory to save the downloaded torrents.
directory = /home/user/nedladdat/torrents/downloads

# Default session directory.
session = /home/user/nedladdat/torrents/rtorrent.session

# Watch a directory for new torrents, restart torrents that have been copied back and stop those that have been
# deleted.
schedule = watch_directory,10,10,"load_start=/home/user/nedladdat/torrents/torrentfiles/*.torrent"
schedule = tied_directory,10,10,start_tied=
schedule = untied_directory,10,10,close_untied=

#Extract rar/zip/001 files when download is complete
system.method.set_key = event.download.finished,unpack_rar,"execute=/home/user/rtorrent/unpack_files.sh,$d.get_base_path="

#Delete rar/zip/001 files when share is complete or torrent file is erased
system.method.set_key = event.download.erased,rm_files,"execute=/home/user/rtorrent/delete_files.sh,$d.get_base_path="

# Close torrents when diskspace is low.
schedule = low_diskspace,5,60,close_low_diskspace=1000M

#Stop torrents when reaching upload ratio 300 percent
ratio.enable=
ratio.min.set=300

# Port range to use for listening.
port_range = 6890-6890

# Start opening ports at a random position within the port range.
#port_random = yes

# Set whetever the client should try to connect to UDP trackers.
use_udp_trackers = yes
check_hash = no
hash_read_ahead = 8
hash_interval = 10
hash_max_tries = 5

#max_open_sockets = 32768
#send_buffer_size = 65536
#receive_buffer_size = 65536
max_open_files = 128

# Encryption options. This can be useful when using an ISP that uses traffic shaping.
encryption=allow_incoming,enable_retry,prefer_plaintext
scgi_port = 127.0.0.1:5000
xmlrpc_dialect=i8

#DHT
dht = auto
dht_port = 6881
peer_exchange = yes

Then you need to create the two scripts and chmod +x them so they are runnable.

unpack_files.sh

#!/bin/bash
#Skapat av Gymmarn 2010-02-11
#Variabel $1 is the folder sent
#Start to check if we're in the right folder (rTorrent seems to bug sometimes)
if [ "$(ls -d $1 | grep -F nedladdat/torrents/)" ]; then
        #Create only 1 instance of this script to avoid rTorrent crashing
        if [ ! "$(ls /home/user/ | fgrep -i pidfile)" ]; then
                yes no | nice -n 15 touch /home/user/pidfile
                #Find and repeat for all folders and subfolders
                for directory in $(find $1 -type d); do
                        #Check for .rar files and unpack them if found
                        if [ "$(ls $directory | fgrep -i .rar | head -n 1)" ]; then
                                rarFile=`ls $directory | fgrep -i .rar | head -n 1`;
                                searchPath="$directory/$rarFile"
                                yes no | nice -n 15 unrar x -o+ $searchPath $directory
                        #Check for .001 files and unpack them if found
                        elif [ "$(ls $directory | fgrep -i .001 | head -n 1)" ]; then
                                rarFile=`ls $directory | fgrep -i .001 | head -n 1`;
                                searchPath="$directory/$rarFile"
                                yes no | nice -n 15 unrar x -o+ $searchPath $directory
                        #Check for .zip files and unpack them if found
                        elif [ "$(ls $directory | fgrep -i .zip)" ]; then
                                for zipFiles in `ls $directory | fgrep -i .zip`; do
                                        searchPath="$directory/$zipFiles"
                                        yes no | nice -n 15 unzip -n $searchPath -d $directory
                                done
                                #When there is .zip files there is often .rar/.001 in them. Check and unpack if so
                                if [ "$(ls $directory | fgrep -i .rar | head -n 1)" ]; then
                                rarFile=`ls $directory | fgrep -i .rar | head -n 1`;
                                searchPath="$directory/$rarFile"
                                yes no | nice -n 15 unrar x -o+ $searchPath $directory
                                #Check for .001 files and unpack them if found
                                elif [ "$(ls $directory | fgrep -i .001 | head -n 1)" ]; then
                                rarFile=`ls $directory | fgrep -i .001 | head -n 1`;
                                searchPath="$directory/$rarFile"
                                yes no | nice -n 15 unrar x -o+ $searchPath $directory
                                fi
                        fi
                done
                yes no | nice -n 15 rm -f /home/user/pidfile
        fi
fi

delete_files.sh

#!/bin/bash
#Made by Gymmarn 2010-02-11
#Variable $1 is the folder which rTorrent specifies
#Check if we're in the right folder, rTorrent seems to bug sometimes
if [ "$(ls -d $1 | grep -F nedladdat/torrents/)" ]; then
        #Only invoke 1 instance of this script
        if [ ! "$(ls /home/user/ | fgrep -i pidfile)" ]; then
                yes no | nice -n 15 touch /home/user/pidfile
                for directory in $(find $1 -type d); do
                        #Find and delete .rar files
                        if [ "$(ls $directory | fgrep -i .rar)" ]; then
                                rarFile=`ls $directory | fgrep -i .rar`;
                                searchPath="$directory/*.r*"
                                yes no | nice -n 15 rm -f $searchPath
                                if [ "$(ls $directory | fgrep -i .zip)" ]; then
                                for zipFiles in `ls $directory | fgrep -i .zip`; do
                                        searchPath="$directory/$zipFiles"
                                        yes no | nice -n 15 rm -f $searchPath
                                done
                                fi
                        #Find and delete .001 files
                        elif [ "$(ls $directory | fgrep -i .001)" ]; then
                                rarFile=`ls $directory | fgrep -i .001`;
                                searchPath="$directory/*.0*"
                                yes no | nice -n 15 rm -f $searchPath
                                if [ "$(ls $directory | fgrep -i .zip)" ]; then
                                for zipFiles in `ls $directory | fgrep -i .zip`; do
                                        searchPath="$directory/$zipFiles"
                                        yes no | nice -n 15 rm -f $searchPath
                                done
                                fi
                        #Find and delete .zip files
                        elif [ "$(ls $directory | fgrep -i .zip)" ]; then
                                for zipFiles in `ls $directory | fgrep -i .zip`; do
                                        searchPath="$directory/$zipFiles"
                                        yes no | nice -n 15 rm -f $searchPath
                                done
                                #Find and delete .rar files
                                if [ "$(ls $directory | fgrep -i .rar)" ]; then
                                rarFile=`ls $directory | fgrep -i .rar`;
                                searchPath="$directory/*.r*"
                                yes no | nice -n 15 rm -f $searchPath
                                #Find and delete .001 files
                                elif [ "$(ls $directory | fgrep -i .001)" ]; then
                                rarFile=`ls $directory | fgrep -i .001`;
                                searchPath="$directory/*.0*"
                                yes no | nice -n 15 rm -f $searchPath
                                fi
                        fi
                done
        yes no | nice -n 15 rm -f /home/user/pidfile
        fi
fi

As you can see the two scripts are very similar. The first two checks were necessary because rTorrent freaks out when the script takes too long to complete and starts it again and again in an eternal loop 🙂

So first the scripts checks am I in the right download folder, in this case /nedladdat/torrents/ if so then it checks have I already been started? if not it makes a pidfile then it uses find to loop all folders and subfolders it can find and unpack rar/zip/001 files.

Comments
5 Comments »
Categories
Linux, Linux script
Comments rss Comments rss

Next Entries »

Ads & Posts

I'm using ads to keep this site running. Please don't block them and if you don't mind consider clicking an ad or two to support this blog.

Feel free to use any code I've posted, consider it GPL or whatever. All I ask is that if you find it useful or see improvements that you write a comment about it and credit me if you use it somewhere else :)

Thanks
/Viktor

Ads

rss Comments rss