2008-11-23

Split Silgle Flac+cue to a separate Flac with id3 Tagging

apt-get install nice flac shntool


#!/bin/bash
# split image file (flac, ape, wav, etc.) according to cue-file


if [ -f "$1" ]; then
i=0
for cuefile in *.cue; do
i=$(($i + 1))
done
if [ $i -eq 1 ]; then
# precies 1 cuesheet gevonden
if grep -q "INDEX 01 00:00:00" *.cue ; then
nice shntool split -t "%n %t" -f *.cue "$1"
else
echo "The first track has a pre-gap. Shntool will cut that off and put it in a seperate file."
echo "You don't want that. Please modify the cuesheet from:"
grep -m1 "INDEX 00" *.cue
grep -m1 "INDEX 01" *.cue
echo "to:"
echo " INDEX 01 00:00:00"
exit 1
fi
elif [ $i -eq 0 ]; then
echo "No cuesheet found in the current directory."
exit 1
elif [ $i -gt 1 ]; then
echo "$i cuesheets found in the current directory. Please remove the superfluous cuesheets."
exit 1
fi
else
echo "Split image file (flac, ape, wav, etc.) according to cue-file."
echo "Output files are in FLAC."
echo "Usage: `basename $0` "
exit 1
fi

echo
album=`grep -m 1 TITLE *.cue | cut -d\" -f2`
artist=`grep -m 1 PERFORMER *.cue | cut -d\" -f2`

for file in [0-9]*.wav; do
echo "Encoding $file"

if [[ ${file:0:1} == 0 ]] ; then
tracknr=${file:1:1}
else
tracknr=${file:0:2}
fi
title=`echo ${file:2} | sed -e "s/.wav$//"`

nice flac -s -T "artist=$artist" -T "album=$album" -T "title=$title" \
-T "tracknumber=$tracknr" "$file" && rm "$file"
done

Source: Speek

2008-11-19

агрегация сетевых интерфейсов

Объединение нескольких жестких дисков для повышения производительности и надежности является широко распространенной практикой. В то же время многими администраторами незаслуженно забыта такая полезная вещь, как агрегация сетевых интерфейсов. Эта методика позволяет объединить несколько сетевых интерфейсов в один. В ОС Linux за ее реализацию отвечает драйвер «bonding».

Итак, первое, что вам понадобится для агрегации — это два сетевых интерфейса. Довольно часто можно встретить серверы с двумя сетевыми картами: одной встроенной и одной платой расширения. Для начала надо убедиться, что Linux видит обе карты. Для этого запустите ifconfig и проверьте, есть ли в списке eth0 и eth1. Если в списке присутствуют не все интерфейсы, проверьте, загружены ли необходимые модули ядра.
Установите пакет ifenslave (далее речь пойдет о дистрибутиве Debian и ifenslave-2.6).

Перед тем как приступить к работе, убедитесь, что драйвер «bonding» скомпилирован для вашего ядра. Попробуйте выполнить modprobe bonding. Если все в порядке, эта команда загрузит драйвер. Если же этого не произойдет, вам придется наведаться в конфигурацию ядра, в раздел «Device Drivers» и включить «Bonding driver support» модулем.

Количество опций слишком велико, чтобы описывать все в статье, поэтому за подробностями отправляем читателя смотреть файл Documentation/networking/bonding.txt, который поставляется с исходными кодами ядра Linux. Опции передаются модулю как параметры при загрузке. Первая опция определяет имя объединенного интерфейса, например, bond0. Необходимо также указать метод, с помощью которого драйвер будет осуществлять мониторинг состояния соединений и обнаруживать сбои. Метод MII (Media Independent Interface) неплохо зарекомендовал себя. Еще одна опция — mode, указывает драйверу, по каким правилам выбирать интерфейс для передачи пакетов. Также необходимо указать машине, как обрабатывать полученные пакеты. Каждая сетевая плата имеет свой собственный MAC-адрес. Машина, передающая пакет, должна указать адрес получателя. Для того чтобы использовать оба интерфейса для приема пакетов, вам понадобится умный Ethernet-коммутатор, или же вам придется перекрыть ARP. При написании статьи автор использовал режим balance-alb (перекрытие ARP). Подробнее об опциях можно почитать в вышеуказанном файле.

Когда драйвер установлен, необходимо настроить его автоматическую загрузку при запуске компьютера. Сделать это можно с помощью утилиты module- init-tools. Также необходимо указать опции. Например:

alias bond0 bonding
options bond0 mode=balance-alb miimon=100


Этим задается имя bond0 для интерфейса, режим работы balance-alb и мониторинг MII каждые 100 миллисекунд.
Bond0 настраивается с помощью ifconfig точно так же, как если бы вы настраивали обычный интерфейс. Например:

ifconfig bond0 123.123.123.4 netmask 255.255.255.0 up


Наконец, необходимо добавить «подчиненные» сетевые интерфейсы:

ifenslave bond0 eth0 eth1

Если все в порядке, интерфейс bond0 должен заработать. Чтобы интерфейс автоматически запускался при загрузке ОС, запустите ifenslave из /etc/network/interfaces с ключом up. Вот пример того, что получилось у автора (реальные IP-адреса в целях безопасности заменены на «xxx»):

auto bond0
iface bond0 inet static
address xxx.xxx.xxx.xxx
netmask 255.255.255.0
network xxx.xxx.xxx.0
broadcast xxx.xxx.xxx.255
gateway xxx.xxx.xxx.1
up /sbin/ifenslave bond0 eth0 eth1


Итак, теперь все готово и настало время тестирования. Попробуйте запустить ping, отключите по очереди сетевые кабели и наслаждайтесь результатом.
OPK, перевод Дмитрия Герусса. Source

Bash Scripts

Transliteration

cat - | sed "y/абвгдезийклмнопрстуфхцы/abvgdezijklmnoprstufxcy/" | sed "y/АБВГДЕЗИЙКЛМНОПРСТУФХЦЫ/ABVGDEZIJKLMNOPRSTUFXCY/" | \
sed "s/ч/ch/"|sed "s/Ч/CH/"|sed "s/ш/sh/"|sed "s/Ш/SH/"|sed "s/ё/jo/"|sed "s/Ё/JO/"|sed "s/ж/zh/"|sed "s/Ж/ZH/"|sed "s/щ/sh\'/" | \
sed "s/Щ/SH/"|sed "s/э/je/"|sed "s/Э/JE/"|sed "s/ю/ju/" |sed "s/Ю/JU/"|sed "s/я/ja/"|sed "s/Я/JA/" |sed "s/ъ/\`/"|sed "s/ъ/\`/" | \
sed "s/ь/\'/"|sed "s/Ь/\'/"


Конвертим все теги mp3-файлов в текущем каталоге с быдло-cp1251 на ПравоСлавный unicode (необходим mp3unicode!): 
%find . -name "*.mp3" -exec mp3unicode –source-encoding windows-1251 –id3v1-encoding none –id3v2-encoding unicode {} \;
Инструкция по сборке (В конце статьи бинарный пакет...)
Update: mp3unicode - Гавно  (поганит уже UTF8 теги)
find . -name "*.mp3" -exec java -jar ~/Bash_sc/id3iconv-0.2.1.jar {}\;
нужны id3iconv и Java (apt-get install sun-java6-jre) из non-free

Конверт имен файлофф
convmv -r --notest -f cp1251 -t utf8 

Место на диске
Иногда приходится смотреть, кто больше всего занимает место, причём интересуют кандидаты весом в несколько Mb или Gb:
du -hs * | grep "^[0-9,]\+[MG]\+"
du --max-depth=1 $1|sort -n -k 1 |awk '{ printf "%.3f Mb \t%s\n", (0+$1)/1024.0/1024.0, $0 }' -


Погода
lynx --dump http://weather.noaa.gov/weather/current/URWW.html | sed -n "/Temperature/s/[0-9][0-9]\? F (//p; /Humidity/p" | tr -d ")"

Права и разрешения
В текущей директории рекурсивно сменить разрешения на все директории
find ./ -type d -exec chmod 775 {} \;
то же для файлов
find ./ -type f -exec chmod 664 {} \; 
Владелетс
find ./ -exec chown user:group {} \; 

Как снять флаг executable только для файлов в каталоге
find . -type f -exec chmod -x {} \;
Эта команда снимет флажки x со всех файлов в текущем каталоге, но оставит в неприкосновенности каталоги, линки, пайпы и т.п. Вариация данной команды также может быть использована для следующей задачи.

Поиск файлов по содержимому
Используя тот же принцип, мы можем искать файлы не только по имени и типу, но и по содержимому. Пример:
find ~ -exec egrep -i "password" /dev/null {} \;


Echo и sudo
Довольно долго мучался по поводу следующей проблемы. Часто требуется выполнить команду такого рода:
sudo echo "hello world" >> /path/to/file
Т.е. от имени суперпользователя записать что-либо в файл иначе недоступный для записи. На это shell ругнется, сказав о нехватке прав. Это связанно с процессом выполнения данной команды: файл /path/to/file открывается от имени обычного пользователя, тогда как первая часть команды выполняется от рута. При перенаправлении stdout в открытый файл и возникает ошибка.

Ситуацию можно исправить следующим образом:
sudo sh -c 'echo "Hello world" >> /path/to/file'
Однако, есть и более элегантный способ. Для этого понадобится команда tee, читающая stdin и пишущая в stdout или файл:
echo "hello world" | sudo tee -a /path/to/file
Если необходимо перенаправление вида ">" вместо ">>", флажок "-a" не используем:
echo "hello world" | sudo tee /path/to/file
Лично мне эта конструкция экономит много полезных секунд :).

Создание и монтирование образа iso
mount -o loop, unhide -t iso9660 filename.iso /mnt/iso
dd if=/dev/cdrom of=file.iso
mkisofs ~/file.iso /tmp/directory

где file.iso - создаваемый образ, /tmp/directory - каталог с исходными файлами.

Копирование, локальное и не только
Кроме использования стандартной команды "cp" существует оригинальный способ копирования через пайпы (pipes):
cd /
tar -cf - | tar -C -xf -

Команда скопирует каталог в каталог . Этот способ очень полезен при копировании больших объемов данных. При необходимости можно добавить и архивацию ключиком "-z" или "-j":
tar -czf - | tar -C -xzf -
Этот рецепт можно немного дополнить. При необходимости передачи файлов по сети из локальной машины на удаленную можно использовать следующую конструкцию:
cd /
tar czf - | ssh tar xzf - -C 

В результате получился некий аналог scp.


X Forwarding

Полезная и простая фича. Если нужно запустить на удаленной машине что-то, требующее X'ы, добавляем к стандартной команде ssh пару ключиков:
ssh -X -Y 
и спокойно запускаем графические приложения на удаленной машине remote_box.

Поиск дублирующихся файлов fdupes (app-misc/fdupes в gentoo portages) - очень полезно на разного рода файлопомойках...

Проверка работы регулярного выражения
echo "somestring" | egrep "regexp" && echo "true" || echo "false"

Debian IP Tunnelling

IP Tunelling
We will do IPv4 tunneling using GRE.
GRE is a tunneling protocol that was originally developed by Cisco, and it can do a few more things than IP-in-IP tunneling. For example, you can also transport multicast traffic and IPv6 through a GRE tunnel.

We are using Debian with linux kernel 2.4.26.
In Linux, you'll need the ip_gre.o module.

Starting Configuration

We have 2 routers X and Y, and intermediate network C (or let's say, Internet).

router X

Router X is connected to the Internet on interface eth0 and network A on eth1.

interface eth0 :: address 169.229.255.134 on the Internet (or network C)
interface eth1 :: address 10.0.2.1, network 10.0.2.0/24 (network A)
router Y

Router Y is connected to the Internet on interface eth0, network B on eth1 and network C on eth2.

interface eth0 :: address 207.241.237.37 on the Internet (or network C)
interface eth1 :: address 10.0.3.1, network 10.0.3.0/24 (network B)
interface eth2 :: address 10.0.4.1, network 10.0.4.0/24 (network C)

As far as network C is concerned, we assume that it will pass any packet sent from X to Y and vice versa. How and why, we do not care.

Tunnelling Objective

Create a tunnel between router X and Y, such that we can route traffic from network A (connected to X) to networks
B and C (connected to Y).
This tunnel will look just like a wire between the two routers with its own subnet (10.0.201.0/24

Create Tunnels

On router X, commands are

iptunnel add tunX mode gre remote 207.241.237.37 local 169.229.255.134 ttl 225
ifconfig tunX 10.0.201.1/24
ifconfig tunX up
ifconfig tunX pointopoint 10.0.201.2
ifconfig tunX multicast
In line 1, we added a tunnel device, and called it tunX.
Furthermore we told it to use the GRE protocol (mode gre), that the remote address is 207.241.237.37 (the router Y at the other end), that our tunneling packets should originate from 169.229.255.134 (which allows your router to have several interfaces and choose which one to use for tunneling) and that the TTL field of the packet should be set to 255 (ttl 255).

Line 2 gives the newly born interface tunY the address 10.0.201.1.

Line 3 enables the device.

Line 4 is necessary to set the IP address of the peer. Need when using dynamic routing with RIP/OSPF with Zebra. Refer to Routing HOWTO for more details.

Line 5 is necessary to enable multicast - so that routing with Zebra works (they normally multicast routing updates).

One router Y, commands are

iptunnel add tunY mode gre local 207.241.237.37 remote 169.229.255.134 ttl 225
ifconfig tunY 10.0.201.2/24
ifconfig tunY up
ifconfig tunY pointopoint 10.0.201.1
ifconfig tunY multicast

Tunnel X<->Y
Now we created a tunnel on the 10.0.201.0/24 network from router X to Y and vice versa.

routerX ----------------tunnel-----------------routerY
10.0.201.1 10.0.201.2
(tunX) (tunY)
We can send packets on the 10.0.201.0/24 network from router X to Y and vice versa.
So we can ping router X from Y on the tunnel interface.
routerX# ping 10.0.201.2
routerY# ping 10.0.201.1
Additional Routes

However, if we to send packets to network B or C from router X, we need to add routes so that traffic
for these networks is sent on the tunnelling interface.

On router X:

route add -net 10.0.3.1/24 gw 10.0.201.1 dev tunX
route add -net 10.0.4.1/24 gw 10.0.201.1 dev tunX

Similarily, to send packets to network A from router Y, we need to add a route.

On router Y:

route add -net 10.0.2.1/24 gw 10.0.201.2 dev tunY
Delete Tunnels

On router X:

ifconfig tunX down
iptunnel del tunX
Network Diagram
(network A) 10.0.2.1, eth1
|
___|_________
| Router X |
|_____________|
| 169.229.255.134 (eth0)
| (Internet or network C)
|
|
| | 10.0.201.1 (tunX)
| |
| |
| | (gre tunnel: 169.229.255.134 <-> 207.241.237.37)
| |
| |
| | 10.0.201.2 (tunY)
|
| (Internet or network C)
| 207.241.237.37 (eth0)
___|___________
| Router Y |
|_______________|
| |
| |
10.0.3.1 10.0.4.1
eth1 eth2
(network B) (network C)
Debian Configuration
  • router X: /etc/network/interfaces
auto tun0
iface tun0 inet static
address 10.0.201.1
netmask 255.255.255.0
broadcast 10.0.201.255
up ifconfig tun0 multicast
pre-up iptunnel add tun0 mode gre remote 207.241.237.37 local 169.229.255.134 ttl 255
pointopoint 10.0.201.2
post-down iptunnel del tun0

  • router Y: /etc/network/interfaces
auto tun0
iface tun0 inet static
address 10.0.201.2
netmask 255.255.255.0
broadcast 10.0.201.255
up ifconfig tun0 multicast
pre-up iptunnel add tun0 mode gre local 207.241.237.37 remote 169.229.255.134 ttl 255
pointopoint 10.0.201.1
post-down iptunnel del tun0

Microdc2 debian

Hi everyone.

I noticed there were no tutorials on the forums explaining how to do this, so I'll go through the steps I used to make this work here.

Introduction

Microdc2 is an excellent command line based directconnect client, just like dc++ for windows, linuxdc++ for linux or shakespeer for mac. Now linuxdc++ is a very nice, fairly stable (later versions anyway) full featured client, so you might think why would you need something else.

Answer: Command line apps are great because

a) They take very little resources so you can run them as server daemons on older hardware
b) You can control them from anywhere in the world over an ssh connection
c) They are generally much much more stable and reliable than their graphical counterpart.
d) They're often (but not always) more configurable than their graphical alternatives.

This makes them excellent for things like running as daemons on unattended servers.

There are only two command line direct connect clients for linux. Microdc2 is one, and another one is nanodc. Nanodc appears to be under heavy development, whereas I think microdc2 may be stagnant now (correct me if I'm wrong here!). However, nanodc seems to be in pretty early beta from what I could see and although it uses a prettier ncurses interface that microdc2, its not actually as easy to use. Maybe in a little while nanodc will be a better choice, but for now, microdc2 is much better in my opinion.

Installing

First you need to download the source tarball. Go to the microdc2 website and download the latest version of the tarball. When I downloaded it, it was version 15.6, available here. So go into a command line, change to a suitable directory and download/unzip the tarball:

Code:
cd ~
mkdir microdc2
cd microdc2
wget http://corsair626.no-ip.org/microdc/microdc2-0.15.6.tar.gz
tar xvfz microdc2-0.15.6.tar.gz
cd microdc2-0.15.6

Ok, there's the source, but before we can compile it we need to download some libraries that the program needs:

Code:
sudo aptitude install build-essential libreadline5-dev checkinstall libxml2-dev libbz2-dev
Now you can start making the program. I like to use checkinstall instead of make install because it installs the program as a normal debian package so you can easily remove it later.

Code:
./configure
make
sudo checkinstall

Checkinstall will ask you some questions. You don't actually have to answer any of them, just say 'y' and press enter and it will automatically create a set of package docs for you.

Ok, now microdc2 is installed! If you used the default set of package docs in checkinstall, it will be called microdc2 in synaptic, and you can treat it like a normal package.

Usage

You can start microdc2 by just typing

Code:
microdc2
at the command line. As with most command line applications, it looks a bit empty and threatening at first, but don't worry! It really is extremely easy to use:

Code:
user@users-pc:~$ microdc2
Loading local FileList...done
Sharing 0 bytes (0B) totally
microdc2>

You can type help and press enter to get a list of commands, or type help and then a command to get detailed information about what the command does.

Code:
microdc2> help
alias [NAME[=VALUE] ...] browse [USER]
cancel CONNECTION ... cd [DIRECTORY]
connect HOST[:PORT] disconnect
exit find [FILE ...]
get FILE ... grantslot [USER ...]
help [COMMAND ...] lookup HOST ...
ls [OPTION...] [FILE...] msg USER MESSAGE...
pwd queue [USER ...]
raw DATA... results [INDEX ...]
retry USER ... say MESSAGE...
search WORD... set [NAME [VALUE...]]
share DIR shell [COMMAND [ARGUMENTS...]]
status transfers
unalias NAME ... unqueue USER [RANGE]
unsearch INDEX ... unshare DIR
who [USER ...] 
microdc2> help set
set: set [NAME [VALUE...]]

Without arguments, display a list of variables and their current values. With only NAME argument, display the
value of that variable. With NAME and VALUE arguments, change the value of a variable.
microdc2>

Microdc2 also supports tab completion so you press tab to finish commands or just press tab at an empty prompt to get help.

Ok, microdc2 is pretty useless at the moment, so let's tell it to connect to a hub:

Code:
microdc2> connect xxx.xxx.xxx.xxx:pppp
You should put in the ip address and port of the hub you would like to connect to. You can chat to people by doing:

Code:
microdc2> say This is a message broadcast to everyone
You can share files by doing this:

Code:
microdc2> share /home/user/sharedfiles/
Remember, microdc2 supports tab completion so it's very quick to use. These files will be instantly shared, but microdc2 will start hashing them in the background as a low priority task.

Now here's something important:

Microdc2 ONLY remembers shared directories. All other settings are forgotten on shutdown.

This is why you have to create a ~/.microdc2/config file with all the commands you would like microdc2 to execute on startup. So create and open this file in your favourite editor. I will use gedit it here:

Code:
cd ~/.microdc2
gedit config

I have made an example config file here, you can change the settings to whatever you would like microdc2 to do:

Code:
# You should make sure that this listen port is forwarded properly if you are behind a router. If you can't forward ports, set active off and use passive mode. This can work behind firewalls but is crippled and slower than a properly forwarded one. NOTE: the port MUST be set before active mode is set on.
set listenport xxxx
set active on

# The following address should be set to your EXTERNAL ip address. This can be found by visiting www.whatismyip.com.
set listenaddr xxx.xxx.xxx.xxx

# I like to turn autoreconnect on in case I get disconnected from the server for whatever reason.
set auto_reconnect on

# The following enables logging. Replace the logfile with wherever you want it to log to. You can of course turn it off by leaving the following two lines blank
set log_charset UTF-8
set logfile /home/user/.microdc2/log

# These should all be pretty self-explanatory. Nick is your nickname. If the hub requires a password, specify one here.
set description I'm using microdc2!
set email microdc2user@example.com
set nick microdc2user
set password xxxx
set downloaddir /home/user/Microdc2_downloads/

# The set speed option doesn't actually change anything, it only changes your REPORTED speed that other users see. The slot is how many simultaneous downloads people can get from you.
set speed somerandomstring
set slots 2

#This is the hub connect command, it should be left until last
connect xxx.xxx.xxx.xxx:pppp
Of course there a lot more options than these, but this should get you started. That's it if you want to leave it there and just run microdc2 normally!

Running as a daemon

apt-get install screen

/etc/init.d/microdc
---------------------------------
#!/bin/sh
# Start/stop/restart the services for MicroDC.

microdc_start() {
if [ -x /usr/local/bin/microdc2 ]; then
echo "Starting MicroDC"
/usr/bin/screen -d -m /usr/local/bin/microdc2
fi
}
microdc_stop() {
echo "Stoping MicroDC"
kill -9 `pidof SCREEN`
screen -wipe
}
microdc_restart() {
kill -9 `pidof SCREEN`
screen -wipe
sleep 2
/usr/bin/screen -d -m /usr/local/bin/microdc2
}

case "$1" in
'start')
microdc_start
;;
'stop')
microdc_stop
;;
'restart')
microdc_restart
;;
*)
# Default is "start", for backwards compatibility with previous
echo "start|stop|restart"

esac

---------------------------------

Based on article written by Sam

ЖЖ Гавно Фжёёппу йего

Переношу сюда последние посты