Simple location check using geoip tool

#!/bin/bash

usage () {
    echo "usage: geoip <IP-address>"
}

ip_regexp=^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$

if [[ $1 =~ $ip_regexp ]]; then
    links -dump "http://www.geoiptool.com/en/?IP=$1" | grep -v "IMG" | head -n -1 | tail -n +9 | sed -e 's/[|]//g;s/+-*+//'
elif [[ $1 != $ip_regexp ]]; then
    echo "Specify valid IP address"
fi

Add commas to numeric strings

Добавить запятые ко всем строкам с цифрами в указанном файле, заменяя '30000' на '30,000' и т.д.:
sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' filename

Configure mpd4 in FreeBSD

[root@gw /usr/local/etc/mpd4]# cat mpd.conf
default:
    load PPPoE

PPPoE:
    new PPPoE PPPoE

    #set netflow export 10.0.1.4 9996
    set iface route default
    set iface disable on-demand
    set iface idle 0
    set iface enable tcpmssfix

    set ipcp yes vjcomp
    set ipcp ranges 0.0.0.0/0 0.0.0.0/0

    set bundle disable multilink
    set bundle disable noretry

    set auth authname login
    set auth password password

    set link no acfcomp protocomp
    set link disable pap chap
    set link accept chap
    set link keep-alive 10 60
    set link max-redial 0

    open
[root@gw /usr/local/etc/mpd4]# cat mpd.links
PPPoE:
    set phys type pppoe
    set pppoe iface rl0
    set pppoe service "*"
    set pppoe disable incoming
    set pppoe enable originate

Random FreeBSD 8.0 kernel panics

После обновления FreeBSD до 8.0 STABLE появились некоторые странности в работе системы, периодически падает ядро примерно следующим образом:
[root@gw /]# last | grep crash
user            pts/1 10.20.5.2 Tue Mar 23 01:49 - crash (1+00:39)
[root@gw ~]# cat /var/crash/info.13
Dump header from device /dev/ad0s1b
Architecture: i386
Architecture Version: 2
Dump Length: 136187904B (129 MB)
Blocksize: 512
Dumptime: Sun Mar 21 01:40:07 2010
Hostname: gw.mydomain.ru
Magic: FreeBSD Kernel Dump
Version String: FreeBSD 8.0-STABLE #0: Thu Mar 4 13:26:39 MSK 2010
root@gw:/usr/obj/usr/src/sys/gw
Panic String: privileged instruction fault
Dump Parity: 3613957471
Bounds: 13
Dump Status: good
[root@gw ~]# cat /var/crash/vmcore.13 | tail
Fatal trap 1: privileged instruction fault while in kernel mode
cpuid = 0; apic id = 00
instruction pointer = 0x20:0xc0857285
stack pointer = 0x28:0xc2e64ba0
frame pointer = 0x28:0xc2e64bc0
code segment = base 0x0, limit 0xfffff, type 0x1b
= DPL 0, pres 1, def32 1, gran 1
processor eflags = interrupt enabled, resume, IOPL = 0
current process = 12 (swi1: netisr 0)
trap number = 1
panic: privileged instruction fault
cpuid = 0
Uptime: 6d22h4m8s
Physical memory: 499 MB
Dumping 129 MB: 114 98 82 66 50 34 18 20
Очень похоже на кривость в планке памяти, нужно погонять memtest'ом. Также в одном из тредов freebsd-questions@freebsd.org посоветовали отключить superpages и посмотреть как будет себя вести:
[root@gw /]# echo "vm.pmap.pg_ps_enabled=0" >> /boot/loader.conf

Simple comparison with Perl

#!/usr/bin/perl

system "cat dict1.raw | awk {'print $1'} | uniq | sed 's/^[[:upper:]].*//g' > dict1";
system "cat dict2.raw | awk {'print $1'} | uniq | sed 's/^[[:upper:]].*//g' > dict2";

$dict1 = "dict1";
$dict2 = "dict2";

open (DICT1, $dict1) || die ("Could not open file!");
open (DICT2, $dict2) || die ("Could not open file!");

@dictionary_1 = <DICT1>;
@dictionary_2 = <DICT2>;

@equal = ();
@diff = ();
%count = ();

foreach $word (@dictionary_1, @dictionary_2) { $count{$word}++; }
foreach $word (keys %count) {
if ($count{$word} == 2) {
    push @equal, $word;
} else {
    push @diff, $word;
    }
}

print "\nDict1 = \n @dictionary_1\n";
print "\nDict2 = \n @dictionary_2\n";
print "\nEqual words = \n @equal\n";
print "\nDifferent words = \n @diff\n\n";
exit 0;

close (DICT1);
close (DICT2);

.Xresources rxvt colors

$ cat ~/.Xresources
Rxvt*background: Black
Rxvt*foreground: #D0D0D0

!Rxvt*font:-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-koi8-r
!Rxvt*font:-*-fixed-medium-r-normal-*-15-140-*-*-c-*-koi8-r
!Rxvt*font:-monotype-courier new-semilight-r-normal-*-17-120-*-*-*-*-koi8-r
Rxvt*font:-*-courier-medium-r-normal-*-18-180-75-75-m-110-koi8-r

Rxvt*saveLines: 5000

Rxvt*scrollBar: false

Rxvt*color0: #000000
Rxvt*color1: #aa0000
Rxvt*color2: #00aa00
Rxvt*color3: #aa5500
Rxvt*color4: #0000aa
Rxvt*color5: #aa00aa
Rxvt*color6: #00aaaa
Rxvt*color7: #aaaaaa
Rxvt*color8: #555555
Rxvt*color9: #ff5555
Rxvt*color10: #55ff55
Rxvt*color11: #ffff55
Rxvt*color12: #5555ff
Rxvt*color13: #ff55ff
Rxvt*color14: #55ffff
Rxvt*color15: #ffffff

cpufreq-set+sensors

#!/bin/bash

cpuexec=/usr/bin/cpufreq-set

usage () {
    printf "usage: cpu -p | -o | -pp | -f FREQ
    -p|--powersave      switch to powersave
    -o|--ondemand       switch to ondemand
    -pp|--perf          switch to performance
    -f|--freq           manually set freq
    -h|--help           show this help\n"
}

check () {
    sensors | grep '^temp'
    cat /proc/cpuinfo | grep '^cpu\ MHz'
    if [ -n "$governor" ]; then
        echo "Switched to $governor governor"
    elif [ -n "$freq" ]; then
        echo "Switched manually to $freq MHz"
    fi
}

set_governor () {
    if [ -s '$governor' ]; then
        usage
    elif [ -f $cpuexec ]; then
        sudo $cpuexec -g $governor && check
    fi
}

set_freq () {
    $cpuexec -f "$freq"MHz && check
}

while true ; do
    case "$1" in
        -p|--powersave) governor="powersave" && set_governor ; exit 1 ;;
        -o|--ondemand) governor="ondemand" && set_governor ; exit 1 ;;
        -pp|--performance) governor="performance" && set_governor ; exit 1 ;;
        -f|--freq) freq=$2 && set_freq ; exit 1 ;;
        -h|--help) usage ; exit 0 ;;
        *) check ; exit 0 ;;
    esac
done

Patch and compile mutt-1.5.20 with sidebar extension in GNU/Linux Debian

Пропатчить mutt-1.5.20:
callisto:~# cd build && wget ftp://ftp.mutt.org/mutt/devel/mutt-1.5.20.tar.gz
callisto:~/build# wget http://lunar-linux.org/~tchan/mutt/patch-1.5.20.sidebar.20090619.txt
callisto:~/build# extract mutt-1.5.20.tar.gz
callisto:~/build# cd mutt-1.5.20 && patch -p1 buffy.c ../patch-1.5.20.sidebar.20090619.txt
Удалить имеющийся mutt и заинсталлить необходимые для сборки пакеты:
callisto:~/build/mutt-1.5.20# apt-get remove mutt
callisto:~/build/mutt-1.5.20# apt-get build-dep mutt
callisto:~/build/mutt-1.5.20# apt-get install libssl-dev
Указать опции для сборки, собрать и установить:
callisto:~/build/mutt-1.5.20# ./configure --enable-pop --enable-imap --enable-smtp --with-gss --with-sasl --with-ssl --enable-locales-fix --enable-hcache
callisto:~/build/mutt-1.5.20# make && make install
Настроить muttrc:
$ cat ~/.muttrc
set realname = "Your Name"
set imap_user = "mailbox@gmail.com"
set imap_pass = "password"
set smtp_url = "smtp://mailbox@smtp.gmail.com:587"
set smtp_pass = "password"
set from = "mailbox@gmail.com"

set spoolfile = "imaps://imap.gmail.com:993/Inbox"
set folder = "imaps://imap.gmail.com:993"

set record = "+[Gmail]/Sent Mail"
set postponed = "+[Gmail]/Drafts"

set header_cache = ~/.mutt/cache/headers
set message_cachedir = ~/.mutt/cache/bodies
set certificate_file = ~/.mutt/certificates

set editor = "nano"
set charset = "koi8-r"
set imap_check_subscribed = yes
set move = no
set copy = yes
set delete = yes
set edit_hdrs
set include
set reply_to
#set nouse_domain
set abort_nosubject = yes
set attribution = " %n wrote:\n"
alternates '(username|altusername)([-+].*)?@.*'
set hdr_format = "%4C %Z %{%m/%d} %-15.15F (%4c) %s"
set pager_index_lines = 5

ignore *
unignore from subject to cc date x-mailer x-url user-agent
hdr_order from to cc date subject x-mailer user-agent

set sort = threads
set sort_aux = last-date-received

# Sidebar
set sidebar_width=34
set sidebar_visible = yes

# which mailboxes to list in the sidebar
#mailboxes =inbox =ml

# color of folders with new mail
#color sidebar_new yellow default

# ctrl-n, ctrl-p to select next, prev folder
# ctrl-o to open selected folder
bind index \CP sidebar-prev
bind index \CN sidebar-next
bind index \CO sidebar-open
bind pager \CP sidebar-prev
bind pager \CN sidebar-next
bind pager \CO sidebar-open

# I don't need these.  just for documentation purposes.  See below.
# sidebar-scroll-up
# sidebar-scroll-down

# Remap bounce-message function to "B"
bind index B bounce-message

# b toggles sidebar visibility
macro index b '<enter-command>toggle sidebar_visible<enter><refresh>'
macro pager b '<enter-command>toggle sidebar_visible<enter><redraw-screen>'

bind index g imap-fetch-mail
bind pager g imap-fetch-mail

# Colours for items in the index
color index brightcyan black ~N
# Hmm, don't like this.
#color index brightgreen black "~N (~x byers.world)|(~x byers.x)|(~x langly.levallois123.axialys.net)|(~x the.earth.li)"
color index brightyellow black ~F
color index black green ~T
color index brightred black ~D
mono index bold ~N
mono index bold ~F
mono index bold ~T
mono index bold ~D

# Highlights inside the body of a message.
# URLs
color body brightgreen black "(http|ftp|news|telnet|finger)://[^ \"\t\r\n]*"
color body brightgreen black "mailto:[-a-z_0-9.]+@[-a-z_0-9.]+"
mono body bold "(http|ftp|news|telnet|finger)://[^ \"\t\r\n]*"
mono body bold "mailto:[-a-z_0-9.]+@[-a-z_0-9.]+"

# email addresses
color body brightgreen black "[-a-z_0-9.%$]+@[-a-z_0-9.]+\\.[-a-z][-a-z]+"
#mono body bold "[-a-z_0-9.%$]+@[-a-z_0-9.]+\\.[-a-z][-a-z]+"

# header
color header green black "^from:"
color header green black "^to:"
color header green black "^cc:"
color header green black "^date:"
color header yellow black "^newsgroups:"
color header yellow black "^reply-to:"
color header brightcyan black "^subject:"
color header red black "^x-spam-rule:"
color header green black "^x-mailer:"
color header yellow black "^message-id:"
color header yellow black "^Organization:"
color header yellow black "^Organisation:"
color header yellow black "^User-Agent:"
color header yellow black "^message-id: .*pine"
color header yellow black "^X-Fnord:"
color header yellow black "^X-WebTV-Stationery:"
color header yellow black "^X-Message-Flag:"
color header yellow black "^X-Spam-Status:"
color header yellow black "^X-SpamProbe:"
color header red black "^X-SpamProbe: SPAM"


# Coloring quoted text - coloring the first 7 levels:
color quoted cyan black
color quoted1 yellow black
color quoted2 red black
color quoted3 green black
color quoted4 cyan black
color quoted5 yellow black
color quoted6 red black
color quoted7 green black


# Default color definitions
#color hdrdefault white green
color signature brightmagenta black
color indicator black cyan
color attachment black green
color error red black
color message white black
color search brightwhite magenta
color status brightyellow blue
color tree brightblue black
color normal white black
color tilde green black
color bold brightyellow black
#color underline magenta black
color markers brightcyan black
# Colour definitions when on a mono screen
mono bold bold
mono underline underline
mono indicator reverse

Configure extended bind9 logging

Добавить в /etc/namedb/named.conf:
logging {
    channel "xfer" {
        file "/var/named/var/log/xfer.log" versions 3 size 10m;
        print-time yes;
        print-severity yes;
        severity info;
    };

    channel "lame" {
        file "/var/named/var/log/lame.log" versions 2 size 10m;
        print-time yes;
        print-severity yes;
        severity info;
    };

    channel "config" {
        file "/var/named/var/log/conf.log" versions 3 size 10m;
        print-time yes;
        print-severity yes;
        severity info;
    };

    channel "security" {
        file "/var/named/var/log/security.log" versions 3 size 10m;
        print-time yes;
        print-severity yes;
        severity info;
    };

    category "xfer-in" { "xfer"; };
    category "xfer-out" { "xfer"; };
    category "notify" { "xfer"; };
    category "lame-servers" { "lame"; };
    category "config" { "config"; };
    category "security" { "security"; };
    category "default" { "default_syslog"; "default_debug"; };
};
Создать файлы, куда будут писаться логи и присвоить их пользователю, от которого запускается демон (в Linux bind:bind, в FreeBSD bind:wheel):
# touch /var/named/var/log/{xfer.log,lame.log,conf.log,security.log}
# chown -R bind:wheel /var/named/var/log
Если bind находится в chroot, после рестарта named в /var/log/messages могут появиться следующие ошибки:
May 30 16:27:42 srv named[6932]: starting BIND 9.4.2 -t /var/named -u bind
May 30 16:27:42 srv named[6932]: command channel listening on 127.0.0.1#953
May 30 16:27:42 srv named[6932]: command channel listening on ::1#953
May 30 16:27:42 srv named[6932]: logging channel 'xfer' file '/var/named/var/log/xfer.log': file not found
May 30 16:27:42 srv named[6932]: logging channel 'lame' file '/var/named/var/log/lame.log': file not found
May 30 16:27:42 srv named[6932]: logging channel 'config' file '/var/named/var/log/conf.log': file not found
May 30 16:27:42 srv named[6932]: logging channel 'security' file '/var/named/log/security.log': file not found
May 30 16:27:42 srv named[6932]: running
May 30 16:27:42 srv named[6932]: isc_log_open '/var/named/var/log/xfer.log' failed: file not found
В таком случае нужно проверить наличие символической ссылки в /var/named/var на /var/named, т.к. в пределах chroot-окружения bind'у нужно явно указать, где он находится:
# cd /var/named/var && ln -s .. named
# ls -l /var/named/var/ | grep named
lrwxr-xr-x 1 root wheel 2 May 30 2009 named -> ..

Useful netstat options

netstat -s [--tcp|-t] [--udp|-u] [--raw|-w]     # show statistics
netstat -v                                      # verbose output
netstat -e|-ee                                  # display additional info
netstat -c [-key]                               # print info continuously
netstat -p                                      # show PID and name of program on socket

chroot bind9 in GNU/Linux Debian

#!/bin/bash

mkdir -p /var/named/{etc,dev}
mkdir -p /var/named/var/cache/bind
mkdir -p /var/named/var/run/bind/{run,log}
mv /etc/bind /var/named/etc
ln -s /var/named/etc/bind /etc/bind
mknod /var/named/dev/null c 1 3
mknod /var/named/dev/random c 1 8
chmod 666 /var/named/dev/*
chown -R bind:bind /var/named/var/*
chown -R bind:bind /var/named/etc/bind

Prevent to upgrade selected packages in GNU/Linux Debian

# aptitude hold linux-image-2.6.26-2-686 linux-source-2.6.26
# aptitude safe-upgrade
Чтение списков пакетов... Готово
Построение дерева зависимостей
Чтение информации о состоянии... Готово
Чтение информации о расширенных состояниях
Инициализация состояний пакетов... Готово
Чтение описаний задач... Готово
Следующие пакеты будут обновлены:
cups cups-bsd cups-client cups-common dpkg dpkg-dev dselect libavcodec-dev libavcodec51 libavformat-dev libavformat52 libavutil-dev libavutil49 libcups2 libcupsimage2 libpango1.0-0 libpango1.0-common libpostproc51 libpulse0 libswscale0 linux-libc-dev
21 пакетов обновлено, 0 установлено новых, 0 пакетов отмечено для удаления, и 2 пакетов не обновлено.
Необходимо получить 15,7MB архивов. После распаковки 106kB будет занято.
Хотите продолжить? [Y/n/?] y
Запись информации расширенных состояний... Готово
...

# aptitude unhold linux-image-2.6.26-2-686 linux-source-2.6.26

nfs-kernel-server: kernel BUG at include/linux/module.h:386! on 2.6.26-2-amd64

Сегодня утром по невыясненным причинам упал nfsd в Lenny:
srv:~# cat /var/log/syslog
...
Mar 22 06:30:05 srv kernel: [1106281.550178] ------------[ cut here ]------------
Mar 22 06:30:05 srv kernel: [1106281.550178] kernel BUG at include/linux/module.h:386!
Mar 22 06:30:05 srv kernel: [1106281.550178] invalid opcode: 0000 [1] SMP
Mar 22 06:30:05 srv kernel: [1106281.550178] CPU 1
Mar 22 06:30:05 srv kernel: [1106281.550178] Modules linked in: snd_pcm_oss snd_mixer_oss snd_seq_dummy snd_seq_oss snd_seq_midi snd_rawmidi snd_seq_midi_event snd_seq snd_seq_device it87 hwmon_vid i2c_dev i2c_core nfsd lockd nfs_acl auth_rpcgss sunrpc exportfs ipt_REJECT xt_iprange xt_tcpudp xt_state iptable_nat nf_nat nf_conntrack_ipv4 nf_conntrack_ftp nf_conntrack iptable_filter ip_tables x_tables ipv6 ext2 loop pcspkr snd_pcm snd_timer snd soundcore snd_page_alloc k8temp shpchp pci_hotplug wmi button evdev ext3 jbd mbcache sd_mod ide_cd_mod cdrom 8139too ahci ata_generic libata scsi_mod dock 8139cp mii ide_pci_generic forcedeth amd74xx ide_core ehci_hcd ohci_hcd thermal processor fan thermal_sys [last unloaded: scsi_wait_scan]
Mar 22 06:30:05 srv kernel: [1106281.550178] Pid: 17940, comm: nfsd Not tainted 2.6.26-2-amd64 #1
Mar 22 06:30:05 srv kernel: [1106281.550178] RIP: 0010:[<ffffffffa0259e67>]  [<ffffffffa0259e67>] :sunrpc:svc_recv+0x41d/0x70e
Mar 22 06:30:05 srv kernel: [1106281.550178] RSP: 0018:ffff8100349bbe90  EFLAGS: 00010246
Mar 22 06:30:05 srv kernel: [1106281.550178] RAX: 0000000000000000 RBX: ffffffffa0271d80 RCX: 0000000000000000
Mar 22 06:30:05 srv kernel: [1106281.550178] RDX: 0000000000001000 RSI: ffff8100349bbdb0 RDI: ffffffffa0271d80
Mar 22 06:30:05 srv kernel: [1106281.550178] RBP: ffff81000201e000 R08: ffff810021f85240 R09: 0000000000000000
Mar 22 06:30:05 srv kernel: [1106281.550178] R10: ffff81000101b8f0 R11: ffffffff803feacc R12: ffff810035559c00
Mar 22 06:30:05 srv kernel: [1106281.550178] R13: ffff8100042e6600 R14: ffff810008848b40 R15: ffff810030a76380
Mar 22 06:30:05 srv kernel: [1106281.550178] FS:  00007f65c00d66e0(0000) GS:ffff8100376189c0(0000) knlGS:0000000000000000
Mar 22 06:30:05 srv kernel: [1106281.550178] CS:  0010 DS: 0000 ES: 0000 CR0: 000000008005003b
Mar 22 06:30:05 srv kernel: [1106281.550178] CR2: 00007f4b14f27000 CR3: 000000000ee4c000 CR4: 00000000000006e0
Mar 22 06:30:05 srv kernel: [1106281.550178] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
Mar 22 06:30:05 srv kernel: [1106281.550178] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Mar 22 06:30:05 srv kernel: [1106281.550178] Process nfsd (pid: 17940, threadinfo ffff8100349ba000, task ffff8100020a8c10)
Mar 22 06:30:05 srv kernel: [1106281.550178] Stack:  ffff81000ee4d018 00000000000dbba0 0000000000000000 ffff8100020a8c10
Mar 22 06:30:05 srv kernel: [1106281.550178]  ffffffff8022c108 0000000000100100 0000000000200200 ffffffff8042a284
Mar 22 06:30:05 srv kernel: [1106281.550178]  01000000ffffff66 0000000000000001 ffff81000201e000 ffffffffa029b67c
Mar 22 06:30:05 srv kernel: [1106281.550178] Call Trace:
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffff8022c108>] ? default_wake_function+0x0/0xe
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffff8042a284>] ? __down_read+0x12/0xa1
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffffa029b67c>] ? :nfsd:nfsd+0x0/0x2a4
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffffa029b767>] ? :nfsd:nfsd+0xeb/0x2a4
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffff8023008d>] ? schedule_tail+0x27/0x5c
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffff8020cf18>] ? child_rip+0xa/0x12
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffffa029b67c>] ? :nfsd:nfsd+0x0/0x2a4
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffffa029b67c>] ? :nfsd:nfsd+0x0/0x2a4
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffffa029b67c>] ? :nfsd:nfsd+0x0/0x2a4
Mar 22 06:30:05 srv kernel: [1106281.550178]  [<ffffffff8020cf0e>] ? child_rip+0x0/0x12
Mar 22 06:30:05 srv kernel: [1106281.550178]
Mar 22 06:30:05 srv kernel: [1106281.550178]
Mar 22 06:30:05 srv kernel: [1106281.550178] Code: 08 4c 89 e7 ff 50 08 48 85 c0 49 89 c5 0f 84 48 01 00 00 48 8b 00 48 8b 58 08 48 85 db 74 26 48 89 df e8 20 84 ff df 85 c0 75 04 <0f> 0b eb fe 65 8b 04 25 24 00 00 00 89 c0 48 c1 e0 07 48 ff 84
Mar 22 06:30:05 srv kernel: [1106281.550178] RIP  [<ffffffffa0259e67>] :sunrpc:svc_recv+0x41d/0x70e
Mar 22 06:30:05 srv kernel: [1106281.550178]  RSP <ffff8100349bbe90>
Mar 22 06:30:05 srv kernel: [1106281.550178] ---[ end trace 47bb10e8da28c2c1 ]---
Судя по архивам мэйл-листов наличие бага известно уже больше года, но всем как обычно похуй. После падения nfsd так и не смог придти в себя и отдавать шары клиентам, помог только ребут машины. Достаточно неожиданно после почти двух месяцев аптайма.

Build module for internal webcam Ricoh r5u870 on Sony Vaio VGN-FZ140E

Камеры, поддерживаемые драйвером:
05ca:1810 HP Pavilion Webcam - UVC
05ca:1830 Sony Visual Communication Camera VGP-VCC2 (for VAIO SZ)
05ca:1832 Sony Visual Communication Camera VGP-VCC3 (for VAIO UX)
05ca:1833 Sony Visual Communication Camera VGP-VCC2 (for VAIO AR1)
05ca:1834 Sony Visual Communication Camera VGP-VCC2 (for VAIO AR2)
05ca:1835 Sony Visual Communication Camera VGP-VCC5 (for VAIO SZ)
05ca:1836 Sony Visual Communication Camera VGP-VCC4 (for VAIO FE)
05ca:1837 Sony Visual Communication Camera VGP-VCC4 (for VAIO FZ)
05ca:1839 Sony Visual Communication Camera VGP-VCC6 (for VAIO CR)
05ca:183a Sony Visual Communication Camera VGP-VCC7 (for VAIO SZ)
05ca:183b Sony Visual Communication Camera VGP-VCC8 (for VAIO FZ)
05ca:1870 HP Pavilion Webcam / HP Webcam 1000

Для успешной установки потребуются заголовки ядра linux-headers-`uname -r`. Debian-way:
laptop:~/deb# wget http://download.tuxfamily.org/arakhne/pool/r/ricoh-webcam-r5u870/ricoh-webcam-r5u870-firmware_0.11.4-0arakhne1_i386.deb
laptop:~/deb# wget http://download.tuxfamily.org/arakhne/pool/r/ricoh-webcam-r5u870/ricoh-webcam-r5u870_0.11.4-0arakhne1_i386.deb

Ручная установка:
laptop:~/build# wget http://download.tuxfamily.org/arakhne/pool/r/ricoh-webcam-r5u870/ricoh-webcam-r5u870_0.11.4-0arakhne1.tar.gz
laptop:~/build# extract ricoh-webcam-r5u870_0.11.4-0arakhne1.tar.gz
laptop:~/build# extract ricoh-webcam-r5u870-0.11.4/r5u870-0.11.4.tar.bz2 && cd r5u870
laptop:~/build/r5u870# make && make install
laptop:~/build/r5u870# cp -R r5u870_*.fw /lib/firmware/
laptop:~/build/r5u870# modprobe r5u870
laptop:~/build/r5u870# lsmod | grep r5
r5u870                 21732  0
firmware_class          6816  3 iwl4965,pcmcia,r5u870
usbcam                 36608  1 r5u870
usbcore               118192  6 r5u870,usbcam,usbhid,ehci_hcd,uhci_hcd
laptop:~/build/r5u870# modinfo /lib/modules/`uname -r`/extra/r5u870.ko
filename:       /lib/modules/2.6.26-2-686/extra/r5u870.ko
license:        GPL
author:         Sam Revitch <samr7@cs.washington.edu>
description:    Driver for Ricoh R5U870-based Webcams
alias:          usb:v05CAp1841d*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp183Ed*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp183Bd*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp183Ad*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp1839d*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp1837d*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp1836d*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp1835d*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp1812d*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp1810d*dc*dsc*dp*ic0Eisc01ip00*
alias:          usb:v05CAp1870d*dc*dsc*dp*ic*isc*ip*
alias:          usb:v05CAp1834d*dc*dsc*dp*ic*isc*ip*
alias:          usb:v05CAp1833d*dc*dsc*dp*ic*isc*ip*
alias:          usb:v05CAp1832d*dc*dsc*dp*ic*isc*ip*
alias:          usb:v05CAp1830d*dc*dsc*dp*ic*isc*ip*
depends:        usbcam,usbcore,firmware_class
vermagic:       2.6.26-2-686 SMP mod_unload modversions 686
parm:           dv1000:HP dv1000 detect mode (0=no,1=yes,2=DMI) (int)
parm:           video_nr:=n[,n...] Force /dev/videoX IDs (array of int)
Также пришлось добавить в /etc/modprobe.d/blacklist модуль uvcvideo, который решил взять на себя управление камерой и перевернуть отдаваемое изображение на 180°

Quick text replacing via perl

perl -pi -e 's/pattern/replace/g' *.html

Check system load via ps

Вывести 10 процессов с сортировкой по использованию ресурсов процессора и потребляемой памяти в порядке убывания:
ps -eo user,pcpu,pmem,pid,cmd | sort -r -k2 | head -n 10

Get network interface IP address

ifconfig eth0 | awk '/inet addr/{print $2}' | cut -d: -f2

ifconfig | sed -rn 's/.*r:([^ ]+) .*/\1/p' # list all ifaces

ifconfig eth0 | sed -rn 's/.*r:([^ ]+) .*/\1/p' # variation

// Да уж, а ведь были времена, когда аналогичную задачу я решал следующим образом велосипедом:
ifconfig | grep "inet addr:10." > /root/grep.txt
find /root/grep.txt -type f -exec cat '{}' \; | tr -c '.[:digit:]' '\n' \
| grep '10.[^.][^.]*\.[^.][^.]*\.[^.][^.]*$' > /root/ip.txt
rm /root/grep.txt

C++ reserved keywords

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while, and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Set date

date MMDDhhmmCCYY.ss

MM — месяц, DD — день месяца, hh — часы, mm — минуты, CCYY — 4 цифры года, ss — секунды:
date 100615352006.30

Playing DVD with mplayer

Воспроизведение DVD с винта посредством mplayer:
$ mplayer dvd://1 -dvd-device /mnt/nas/movies/star_wars_I-VI_dvd9/episode_V/ -alang en -slang en -cache 8192 -af surround -channels 6 -ac a52 -af volume=20.1:0
...
audio stream: 0 format: ac3 (5.1) language: ru aid: 128.
audio stream: 1 format: ac3 (stereo) language: ru aid: 129.
audio stream: 2 format: ac3 (5.1) language: en aid: 130.
audio stream: 3 format: ac3 (stereo) language: en aid: 131.
number of audio channels on disk: 4.
subtitle ( sid ): 0 language: ru
subtitle ( sid ): 1 language: ru
subtitle ( sid ): 2 language: en
subtitle ( sid ): 3 language: en
subtitle ( sid ): 4 language: en
number of subtitles on disk: 5
...
dvd://<track> с какой части начинать воспроизведение
-alang [[ en | ru ] | -aid ID ] выбор звуковой дорожки
-slang [[ en | ru ] | -vobsubid [ 1 | 2 | n ]] выбор субтитров по двухбуквенному коду или id (в mkv трехбуквенные вроде)
-cache N устанавливает объем кэша в байтах, удобно при проигрывании DVD9 по сети
-af <filter> доступные фильтры по mplayer -af help
-channels [ 2 | 4 | 6 ] 2 stereo, 4 surround, 6 full 5.1
-ac <codec> выбирается автоматически, доступные кодеки по mplayer -ac help
-af volume=20.1:0 увеличить звук на 20дБ
Часто используемые опции добавить в ~/.mplayer/config.

ffmpeg screencast

Запись видео в запущенных иксах. Для изменения битрейта видео используется -b <bps> или -sameq:
$ ffmpeg -f x11grab -b 3200 -s 1280x800 -r 30 -i :0.0 /tmp/screencast.mpg

Mini http server via nc on 8080 port

Слушать на 8080 порту и открывать доступ к файлам каталога, из которого запущен скрипт. Как вариант, можно использовать & при вызове скрипта или screen:

#!/bin/bash

:;while [ $? -eq 0 ];do
    nc -vlp 8080 -c'(r=read;e=echo;$r a b c;z=$r;while [ ${#z} -gt 2 ];
    do $r z;done;
    f=`$e $b|sed 's/[^a-z0-9_.-]//gi'`;
    h="HTTP/1.0";o="$h 200 OK\r\n";c="Content";
    if [ -z $f ];then
       ($e $o;ls|(while $r n;do if [ -f "$n" ]; then
       $e "<a href=\"/$n\">`ls -gh $n`";fi;done););
       elif [ -f $f ];then
       $e "$o$c-Type: `file -ib $f`\n$c-Length: `stat -c%s $f`";$e;cat $f;
       else $e -e "$h 404 Not Found\n\n404 Not Found\n";
    fi)';
done

lspci -n check

Проверка наличия драйверов в ядре для PCI-устройств по коду вендора:
curl --silent -d "check=Check&lspci=$(lspci -n)" http://kmuto.jp/debian/hcl/index.cgi | sed -n '/<table>/,/<\/table>/ p' | lynx -stdin

rtorrent-0.8.6+libtorrent-0.12.6+apache2+php5+ruTorrent-2.8 on GNU/Linux Debian Lenny

Для начала нужно грохнуть из системы установленный ранее rtorrent, библиотеки libxmlrpc-c3, libtorrent11 и стянуть необходимые для сборки libcurl3-dev, libsigc++-2.0-0c2a, libsigc++-2.0-dev (про make, gcc, g++, autoconf, libncurses5-dev и др. я молчу — и так понятно, что без них никуда).
Подготовка к сборке заключается в получении свежего xmlrpc из SVN по адресу http://xmlrpc-c.svn.sourceforge.net/viewvc/xmlrpc-c/advanced/ (внизу страницы есть линк "Download GNU Tarball"), а также исходников rtorrent и libtorrent с сайта http://libtorrent.rakshasa.no/downloads/.

Опции ./configure для xmlrpc и libtorrent стандартные, могут возникнуть некоторые проблемы:
1) xmlrpc сфейлит при make install.
Fix: chmod +x install-sh (непонятно, почему его сразу исполняемым не сделали).

2) При компиляции libtorrent <0.12.6 может вылетать с ошибкой "file_list_iterator.h:64: error: 'abs' is not a member of 'std'".
Fix: patch -p1 http://libtorrent.rakshasa.no/attachment/ticket/1266/libtorrent-gcc43-v2.patch, внизу страницы линк на Original Format.

3) Собственно сам rtorrent нужно собирать с опцией --with-xmlrpc-c. При компиляции rtorrent <0.8.6 может вылетать с ошибкой "text_element_value.cc:117: error: ‘gmtime’ is not a member of ‘std’".
Fix: patch -p1 http://libtorrent.rakshasa.no/attachment/ticket/1267/rtorrent-gcc43.patch, внизу страницы линк на Original Format.

4) echo "include /usr/local/lib" >> /etc/ld.so.conf, иначе будет ругаться на отсутствие библиотек.

.rtorrent.rc:
min_peers = 1
max_peers = 200
download_rate = 200
upload_rate = 200
directory = /mnt/torrent/download
session = /mnt/torrent/session
port_range = 40893-40893
port_random = no
check_hash = no
encoding_list = cp1251
use_udp_trackers = no
session_save = yes
scgi_port=127.0.0.1:5000
encoding_list = UTF-8;CP1251;KOI8-R
Apache2:
Необходимые пакеты: apache2, libapache2-mod-php5, php5, php-cli, libapache2-mod-scgi. В sites-available создается файл rtorrent.domainname.ru:
<VirtualHost xx.xx.xx.xx:80>
    ServerAdmin webadmin@domainname.ru
    ServerName rtorrent.domainname.ru
    ServerAlias rtorrent.domainname.ru
    DocumentRoot /var/www/vhosts/rtorrent.domainname.ru/

    Options FollowSymLinks
    AllowOverride None

    ErrorLog /var/log/apache2/rtorrent.domainname.ru-error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/rtorrent.domainname.ru-access.log common
    ServerSignature On
</VirtualHost>

В /etc/apache2/apache2.conf в конец конфига добавить:
<Location "/RPC2">
    SetHandler scgi-handler
    SCGIServer 127.0.0.1:5000
    SCGIHandler On
    Options -Multiviews
    AuthName "RPC2 Restricted Area"
    AuthType Basic
    AuthBasicProvider file
    AuthUserFile /root/htpasswd/.rutorrent
    Require valid-user
</Location>


SCGIMount /RPC2 127.0.0.1:5000
В конфиге указано кого попало не пускать к веб-морде, AuthType Basic для меня вполне достаточно, апач доступен только из внутренних серых подсетей:

# htpasswd -c ~/htpasswd/.rutorrent admin
# chown www-data:www-data ~/htpasswd -R
# a2enmod scgi
# a2ensite /etc/apache2/sites-available/rtorrent.domainname.ru
# /etc/init.d/apache2 restart
# tail -f /var/log/apache2/error.log
 [Sun Mar 14 06:25:03 2010] [notice] Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny6 with Suhosin-Patch mod_scgi/1.12 configured -- resuming normal operations

rutorrent-2.8:
Проект обновляется достаточно часто и старые версии быстро перестают поддерживаться девелоперами, но не думаю, что установка будет в корне отличаться:

# cd ~ && wget http://rutorrent.googlecode.com/files/rutorrent-2.8.tar.gz
# extract rutorrent-2.8.tar.gz; mv ~/rtorrent/* /var/www/vhosts/rtorrent.domainname.ru/; chown www-data:www-data /var/www/ -R; rm -rf ~/rtorrent; mv ~/rutorrent-2.8.tar.gz /mnt/nas/dist/soft/

Squid 2.7STABLE on FreeBSD 8_STABLE

Squid compile options:
# squid -v
Squid Cache: Version 2.7.STABLE7
configure options: '--bindir=/usr/local/sbin' '--sbindir=/usr/local/sbin' '--datadir=/usr/local/etc/squid' '--libexecdir=/usr/local/libexec/squid' '--localstatedir=/usr/local/squid' '--sysconfdir=/usr/local/etc/squid' '--enable-removal-policies=lru heap' '--disable-linux-netfilter' '--disable-linux-tproxy' '--disable-epoll' '--enable-auth=basic digest negotiate ntlm' '--enable-basic-auth-helpers=DB NCSA PAM MSNT SMB YP' '--enable-digest-auth-helpers=password' '--enable-external-acl-helpers=ip_user session unix_group wbinfo_group' '--enable-ntlm-auth-helpers=SMB' '--with-pthreads' '--enable-storeio=ufs diskd null aufs' '--enable-delay-pools' '--enable-snmp' '--disable-internal-dns' '--enable-referer-log' '--enable-useragent-log' '--enable-pf-transparent' '--disable-kqueue' '--with-large-files' '--enable-large-cache-files' '--enable-err-languages=Armenian Azerbaijani Bulgarian Catalan Czech Danish Dutch English Estonian Finnish French German Greek Hebrew Hungarian Italian Japanese Korean Lithuanian Polish Portuguese Romanian Russian-1251 Russian-koi8-r Serbian Simplify_Chinese Slovak Spanish Swedish Traditional_Chinese Turkish Ukrainian-1251 Ukrainian-koi8-u Ukrainian-utf8' '--enable-default-err-language=English' '--prefix=/usr/local' '--mandir=/usr/local/man' '--infodir=/usr/local/info/' '--build=i386-portbld-freebsd8.0' 'build_alias=i386-portbld-freebsd8.0' 'CC=cc' 'CFLAGS=-O2 -fno-strict-aliasing -pipe -march=pentium4 -mtune=pentium4 -march=pentium4 ' 'LDFLAGS=' 'CPPFLAGS='

squid.conf:
http_port 3128 transparent
snmp_port 3401
snmp_incoming_address 0.0.0.0
snmp_outgoing_address 255.255.255.255
visible_hostname proxy.domainname.ru

acl all src 0.0.0.0/0.0.0.0
acl localhost src 127.0.0.0/255.255.255.255
acl localhost src 127.0.0.1
acl ssl_ports port 443 563 873
acl safe_ports port 80 21 70 210 1025-65535 280

acl manager proto cache_object
acl purge method PURGE
acl CONNECT method CONNECT

acl nobanners url_regex "/usr/local/etc/squid/acl/inet_nobanners.acl"
acl banners url_regex "/usr/local/etc/squid/acl/inet_banners.acl"

http_access allow localhost
http_access allow all localhost
http_access allow manager localhost
http_access allow purge localhost

acl servers src 10.0.1.0/24
acl users   src 10.20.5.0/24

http_access allow servers
http_access allow users !banners
http_access allow nobanners
http_access deny !servers
http_access deny !users

acl hostname src 10.0.1.3/255.255.255.255
acl snmpacl snmp_community define_snmpcommunity
snmp_access allow snmpacl localhost
snmp_access allow snmpacl hostname
snmp_access deny all
high_memory_warning 128 MB

cache_mem 32 MB
memory_pools off
memory_pools_limit 16 MB

cache_swap_low 90
cache_swap_high 99
maximum_object_size 16364 KB
minimum_object_size 0 KB
maximum_object_size_in_memory 128 KB

ipcache_size 4096
ipcache_low 94
ipcache_high 99
fqdncache_size 8192
icp_port 0

cache_dir ufs /usr/local/squid/cache 5000 16 128
access_log /usr/local/squid/logs/access.log squid
cache_log /usr/local/squid/logs/cache.log
cache_store_log none
#emulate_httpd_log off

quick_abort_min 0 KB
quick_abort_max 0 KB
negative_ttl 1 minutes
dns_children 6
positive_dns_ttl 6 hours
negative_dns_ttl 1 minutes
range_offset_limit 0
request_header_max_size 250 KB
request_body_max_size 0 KB
request_entities on
collapsed_forwarding on

#cache_replacement_policy heap GDSF
#memory_replacement_policy heap GDSF

refresh_pattern ^ftp: 129600 100% 129600
refresh_pattern ^gopher: 129600 100% 129600
refresh_pattern . 0 20% 4320
refresh_pattern .*.deb$ 129600 100% 129600 reload-into-ims
refresh_pattern -i \Packages.*$ 1 100 129600 reload-into-ims
refresh_pattern .*.tar.bz2$ 129600 100% 129600 reload-into-ims
refresh_pattern -i \.gif$ 129600 100% 129600 reload-into-ims
refresh_pattern -i \.png$ 129600 100% 129600 reload-into-ims
refresh_pattern -i \.jpg$ 129600 100% 129600 reload-into-ims
refresh_pattern -i \.jpeg$ 129600 100% 129600 reload-into-ims
refresh_pattern -i \.swf$ 129600 100% 129600 reload-into-ims
refresh_pattern -i \.bmp$ 129600 100% 129600 reload-into-ims

#connect_timeout 60 seconds
#siteselect_timeout 8 seconds
read_timeout 2 minutes

#request_timeout 60 seconds
#client_lifetime 12 hours
#half_closed_clients off
#pconn_timeout 120 seconds
#ident_timeout 0 seconds
shutdown_lifetime 1 seconds

#high_response_time_warning 50
#high_page_fault_warning 2
forwarded_for off

cache_mgr manager@domainname.ru
coredump_dir /usr/local/squid
http_reply_access allow all

icp_access deny all
http_access deny all
http_access deny manager
http_access deny !safe_ports
http_access deny CONNECT !ssl_ports

rdesktop alias in .bashrc

$ echo "alias rdesktop='rdesktop -g 1280x1024 -u user -p- -k en-us -z -K'" >> ~/.bashrc
-g    desktop geometry (WxH)
-u    username for authentication on the server
-p-   the password to authenticate with, use -p - to make rdesktop request a password at startup (from standard input)

-k    keyboard layout to emulate
-z    enable compression of the RDP datastream
-K    do not override window manager key bindings.

Use proxy, Luke

Для ситуации, когда нет прозрачного squid:
# cd /etc/apt/; touch apt.conf; echo Acquire::http::Proxy '"http://user:password@proxy:3128"' > /etc/apt/apt.conf; cp apt.conf proxy
При необходимости также можно экспортировать информацию о доступных proxy в переменные окружения:
# echo "export http_proxy='http://user:password@proxy:3128'" >> ~/.bashrc
# echo "export ftp_proxy='http://user:password@proxy:3128'" >> ~/.bashrc

Extract archives

#!/bin/bash

if [ -f $1 ] ; then
   case $1 in
      *.tar.bz2) tar xvjf $1 ;;
      *.tar.gz) tar xvzf $1 ;;
      *.bz2) bunzip2 $1 ;;
      *.rar) unrar x $1 ;;
      *.gz) gunzip $1 ;;
      *.tar) tar xvf $1 ;;
      *.tbz2) tar xvjf $1 ;;
      *.tgz) tar xvzf $1 ;;
      *.zip) unzip $1 ;;
      *.Z) uncompress $1 ;;
      *.7z) 7z x $1 ;;
      *) echo "'$1' cannot be extracted via script" ;;
   esac
else
   echo "'$1' is not a valid file"
fi

find . -mtime

find . -mtime -1          # find files modified within the past 24 hours
find . -mtime 1           # find files modified between 24 and 48 hours ago
find . -mtime +1          # find files modified more than 48 hours ago
find . -mmin +5 -mmin -10 # find files modifed between 5 and 10 minutes ago

Debian bash completion

Полезная вещь в Debian – после добавления этой строки, опции deb-специфичных программ
(apt-get, dpkg-reconfigure) научатся автодополнению при нажатии tab:
echo '. /etc/bash_completion' >> ~/.bashrc

Configure ntpd on FreeBSD

Security Issues
Начнем с того, что некоторое время назад при сборке версии 4.2.4p7 из портов с поддержкой OpenSSL, а также использовании опции crypto pw в ntp.conf, демон будет подвержен уязвимости при вызове sprintf() в функции crypto_recv(), которая позволит атакующему выполнить произвольный код с привилегиями ntp демона, а также вызвать Denial of Service. До обновления пакета ntpd в коллекции портов проблему можно решить редактированием Makefile порта перед компиляцией (USE_OPENSSL=no) и исключением из конфига вышеуказанной строки crypto pw. Для дефолтного ntpd, поставляемого с системой, проблема была так же актуальна и решалась с помощью патчей с http://security.freebsd.org/advisories/FreeBSD-SA-09:11.ntpd.asc.

Configure /etc/rc.conf
ntpd_enable="YES"
ntpd_program="/usr/local/bin/ntpd"
ntpd_flags="-c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift"


Configure pf.conf
table <dmz_net> { 10.0.1.0/24 }
table <usr_net> { 10.20.5.0/24 }

block in log all
pass out on $ext_if all keep state
pass out on $dmz_if all keep state
pass out on $usr_if all keep state

# Macro
#
int_if = "{" $dmz_if $usr_if "}"
networks = "{" "<dmz_net>, <usr_net>" "}"

pass in on $int_if proto udp from $networks to any port ntp keep state


Configure /etc/ntp.conf
server 77.236.33.77 prefer iburst
server 212.118.54.2 iburst
server 193.41.86.177 iburst
server 193.125.143.140 iburst

driftfile /etc/ntp/drift
logfile /var/log/ntpd.log

restrict default ignore
restrict 127.0.0.1
restrict 10.0.1.0 mask 255.255.255.0 nomodify notrap
restrict 10.20.5.0 mask 255.255.255.0 nomodify notrap

restrict 193.125.143.140 noquery notrap
restrict 212.118.54.2 noquery notrap
restrict 193.41.86.177 noquery notrap
restrict 77.236.33.77 noquery notrap
Рестарт ntpd, в логах должен гавкнуть, что все хорошо, на всякий случай можно проверить сокеты:
# sockstat | grep -v udp6 | grep ntpd
root ntpd 1037 3 dgram -> /var/run/logpriv
root ntpd 1037 20 udp4 *:123 *:*
root ntpd 1037 22 udp4 192.168.1.2:123 *:*
root ntpd 1037 23 udp4 10.0.1.1:123 *:*
root ntpd 1037 24 udp4 10.20.5.1:123 *:*
root ntpd 1037 27 udp4 127.0.0.1:123 *:*
root ntpd 1037 29 udp4 xx.xx.xx.xx:123 *:*

Used docs
После перезапуска синхронизация не начнется сразу же. Придется подождать некоторое время, ntpd демон не слишком торопливый — мне пришлось сидеть около двух часов. Для того, чтобы отследить состояние соединения с другими серверами, есть утилита ntpq. За дополнительной информацией можно обратиться к man ntpd, man ntp.conf, а также почитать более подробную документацию.

GNU/Linux Debian Lenny amd64+Xen+soft RAID1+LVM

Давно уже дело было, но примерная последовательность действий такая. Необходимые пакеты:
apt-get install xen-hypervisor-3.2-1-amd64 xen-linux-system-2.6.26-1-xen-amd64 xen-utils-3.2-1 xenstore-utils xenwatch xen-shell xen-tools mdadm lvm2
В ходе экспериментов для софтового RAID-массива использовались два винта по 250Gb с партициями sdb и sdc, а также логическими томами под бэкапы и повседневные нужды:
xen:~# fdisk -l /dev/sdb
Disk /dev/sdb: 250.0 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xb00bb847
Device Boot Start End Blocks Id System

/dev/sdb1 * 1 30401 244196001 83 Linux

xen:~# fdisk -l /dev/sdc
Disk /dev/sdc: 250.0 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00086b49
Device Boot Start End Blocks Id System

/dev/sdc1 1 30401 244196001 fd Linux raid autodetect
Создание физических устройств и групп lvm:
xen:~# pvcreate /dev/sdb1
xen:~# pvcreate /dev/sdc1
xen:~# vgcreate vgsdb /dev/sdb1
xen:~# vgcreate vgsdc /dev/sdc1
Cоздание логических томов для виртуальной машины, которые затем будут синхронизированы в массив:
xen:~# lgcreate -L 20048 -n domU vgsdb
xen:~# lgcreate -L 20048 -n domU vgsdс
Создание RAID-массива:
xen:~# mdadm -C /dev/md0 --level=1 --raid-disks=2 /dev/vgsdb/domU /dev/vgsdc/domU
xen:~# pvcreate /dev/md0
Создание вложенной группы внутри логического тома:
xen:~# vgcreate vg-domU /dev/md0
Cоздание виртуальной машины:
xen:/dev# cat /etc/xen-tools/partitions.d/domU
[root]
size=1G
type=ext3
mountpoint=/
options=sync,errors=remount-ro[swap]
size=512M
type=swap[home]
size=512M
type=ext3
mountpoint=/home
options=nodev,nosuid

[tmp]
size=512M
type=ext3
mountpoint=/tmp
options=nodev,nosuid

[var]
size=10G
type=ext3
mountpoint=/var
options=nodev,nosuid

xen:/dev# xen-create-image --force --hostname=domU --partitions=/etc/xen-tools/partitions.d/domU --ip=1.1.1.1 --memory=128Mb --arch=amd64 --role=udev
Если нужно увеличить размер партиции:
xen:/dev# lvresize /dev/vgetch/etch-var -L +900M
Extending logical volume etch-var to 10,98 GB
Logical volume etch-var successfully resized

xen:/dev# resize2fs /dev/vgetch/etch-var

xen:~# df -h
Файловая система Разм Исп Дост Исп% смонтирована на
/dev/sda2 12G 1,1G 11G 9% /
tmpfs 406M 0 406M 0% /lib/init/rw
udev 10M 732K 9,3M 8% /dev
tmpfs 406M 0 406M 0% /dev/shm
/dev/sda1 133M 37M 89M 29% /boot
/dev/sda6 60G 181M 57G 1% /home
/dev/sdd5 459G 308G 128G 71% /mnt/media
/dev/mapper/vgetch-etch--var
11G 203M 11G 2% /mnt/etch

xen:/dev# mke2fs -n /dev/vgetch/etch-var
mke2fs 1.41.3 (12-Oct-2008)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
719488 inodes, 2877440 blocks
143872 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=2948595712
88 block groups
32768 blocks per group, 32768 fragments per group
8176 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208

xen:~# e2fsck -b 32768 /dev/vgetch/etch-var
e2fsck 1.41.3 (12-Oct-2008)
/dev/vgetch/etch-var: recovering journal
e2fsck: unable to set superblock flags on /dev/vgetch/etch-var
В последней строке ругнулось, но работало без каких-либо проблем.

Add rules to pf via ssh from cell phone

На случай экстренного открытия доступа к ssh с мобильного телефона через midpSSH:
[root@gw /usr/local/etc]# touch pf_temp_ssh && chown mobileuser:mobileuser pf_temp_ssh
[root@gw /usr/local/etc]# cat pf.conf | grep temp
table <pf_temp_ssh> persist file "/usr/local/etc/pf_temp_ssh"
pass in on $ext_if proto tcp from <pf_temp_ssh> to <ext_ip> port ssh keep state
[root@gw /usr/local/etc]# cat sudoers | grep mobileuser
mobileuser ALL=/sbin/pfctl
#!/bin/bash

# copyright (c) 2010 vprokofyev.blogspot.com <v.prokofyev@gmail.com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program (see the file COPYING); if not, write to the
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301 USA.

# usage: pfadd <ip-address or network>

ip_regexp=^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$

if [[ $1 =~ $ip_regexp ]]; then
    echo "$1" >> /usr/local/etc/temp_ssh
    sudo pfctl -f /usr/local/etc/pf.conf
    echo "pf.conf loaded"
elif [[ $1 != $ip_regexp ]]; then
    echo "Specify valid IP address"
fi

Weather on console

Для начала определяем местонахождение http://www.bbc.co.uk/cgi-perl/weather/search/new_search.pl и копипастим линк rss-feed на ближайшие три дня, получается нечто подобное:

#!/bin/bash

wget -q -O - http://newsrss.bbc.co.uk/weather/forecast/3000/Next3DaysRSS.xml | grep title | sed -e "s/<[^>]*>//g" -e "s///g" | egrep "^[A-Z]"


Была проблема в том, что вместо знаков ° отображалось "&#xB0", но это легко фиксится добавлением дополнительных конвейеров с sed -r 's/expr/ /'

Search keyword in directory via find and grep

Поиск заданной строки в файлах текущей директории:
find . -exec grep -Hn "phrase" {} \;

rsnapshot

Для начала на бэкап-сервере создается отдельный пользователь с --home=/path/to/backups, от его имени с помощью ssh-keygen генерируется private- и public-ключи. Первый остается на сервере, публичный копируется в /root/.ssh и на удаленную машину:
cat /mnt/backup/.ssh/id_dsa.pub | ssh backup@domainname.ru "cat >> ~/.ssh/authorized_keys2"
Не забыть выставить chmod 700 .ssh && chmod 400 .ssh/authorized_keys2 на клиенте. По дефолту у обычного пользователя нет прав копировать /etc/ и прочее, поэтому пользователю backup нужно дать доступ к rsync, с помощью которого rsnapshot синхронизирует снимки. В /etc/sudoers добавляется:
backup ALL=NOPASSWD: /usr/bin/rsync
backup ALL=NOPASSWD: /usr/bin/rsync_original
Обертка необходима потому, что при указании в rsnapshot.conf опции rsync_long_args --rsync-path="/usr/bin/sudo /usr/bin/rsync" она вообще не может понять чего от нее хотят — отсюда и велосипед с враппером /usr/bin/sudo /usr/bin/rsync_original $@
Примерный rsnapshot.conf (не забывать про таб между опцией и значением):
srv:~# grep -v -e "^#" /etc/rsnapshot.conf | sed '/^$/d'
config_version 1.2
snapshot_root /mnt/nas/backup/

cmd_rm /bin/rm
cmd_rsync /usr/bin/rsync
cmd_ssh /usr/bin/ssh
cmd_logger /usr/bin/logger

interval hourly 6
interval daily 7
interval weekly 4
interval monthly 3

verbose 2
loglevel 3
logfile /var/log/rsnapshot

lockfile /var/run/rsnapshot.pid

exclude /dev
exclude /proc
exclude /sys
exclude /mnt
exclude /var/cache/apt
exclude /usr/src
exclude /home/ftp

exclude /usr/ports
exclude /usr/local/squid
exclude /usr/obj

exclude /home/user/.cache/google-chrome
exclude /home/user/.config/google-chrome
exclude /home/user/.opera
exclude /home/user/.mozilla
exclude /home/user/.macromedia
exclude /home/user/.wine

# srv0
backup / srv0.domainname.ru/
backup /boot/ srv0.domainname.ru/
backup /var/ srv0.domainname.ru/
backup /home/ srv0.domainname.ru/

# srv1
backup backup@srv1.domainname.ru:/ srv1.domainname.ru/
backup backup@srv1.domainname.ru:/usr/ srv1.domainname.ru/
backup backup@srv1.domainname.ru:/var/ srv1.domainname.ru/
backup backup@srv1.domainname.ru:/home/ srv1.domainname.ru/

# user1
backup backup@user.domainname.ru:/ srv3.domainname.ru/
backup backup@user.domainname.ru:/boot/ srv3.domainname.ru/
backup backup@user.domainname.ru:/home/ srv3.domainname.ru/
Сказать крону когда запускать rsnapshot (интервалы должны соответствовать тому, чтобы перед выполнением следующей задачи успевала отрабатывать предыдущая):
srv:~# cat /etc/crontab | grep rsnap
0 */4 * * * root /usr/bin/rsnapshot hourly
40 23 * * * root /usr/bin/rsnapshot daily
20 23 * * 0 root /usr/bin/rsnapshot weekly
00 23 1 * * root /usr/bin/rsnapshot monthly