понедельник, 20 декабря 2010 г.

share OpenVpn server LAN

### VPN share server LAN
cat /proc/sys/net/ipv4/ip_forward
iptables  -t nat -A POSTROUTING -s 10.50.0.0/24 -o vmbr0 -j MASQUERADE

пятница, 17 декабря 2010 г.

linux RAM

Список процессов отсортированый по потребляемой памяти

ps -eo pid,ppid,rss,vsize,pcpu,pmem,cmd -ww --sort=rss
 
VSIZE (Virtual memory SIZE) - The amount of memory the process is
    currently using. This includes the amount in RAM and the amount in
    swap.

    RSS (Resident Set Size) - The portion of a process that exists in
    physical memory (RAM). The rest of the program exists in swap. If
    the computer has not used swap, this number will be equal to
    VSIZE.
 
Очистить кэшированую память
# sync; echo 3 > /proc/sys/vm/drop_caches

четверг, 16 декабря 2010 г.

autologon in linux

Вариант 1
Закомментировать в /etc/inittab строчку
   1:2345:respawn:/sbin/getty 38400 tty1
т.е.
#  1:2345:respawn:/sbin/getty 38400 tty1
ниже  ее добавить
   1:2345:respawn:/bin/login -f YOUR_USER_NAME tty1 /dev/tty1 2>&1

в /home/YOUR_USER_NAME в .bashrc или .bash_profile добавить строку для авто запуска иксов

if [ -z "$DISPLAY" ] && [ $(tty) == /dev/tty1 ]; then
    startx
fi

Вариант 2 
1) в /etc/inittab комментируем туже строку но добавляем:
   1:2345:respawn:/sbin/getty -n -l /usr/local/sbin/autologin 38400 tty1
2)
su -
mkdir -p /usr/local/sbin/
touch /usr/local/sbin/autologin
chmod u+x /usr/local/sbin/autologin


3) nano /usr/local/sbin/autologin добавляем
#!/usr/bin/python
import os
os.execlp('login', 'login', '-f', 'my_user_name', '0')
 



4) ~/.bashrc добавить
if [ -z "$DISPLAY" ] && [ $(tty) == /dev/tty1 ]; then
   startx
fi

воскресенье, 12 декабря 2010 г.

upgrade minor version of OpenERP

For each minor version like this one, the procedure is simple because there is no change that requires a real migration.

1. Make a fresh backup of all existing databases, as well as a backup of the files of your OpenERP installation (server, web and addons), just in case.
2. Stop the OpenERP server as well as Web Server (if present).
3. Update the source files to the latest release, or simply install the new releases over the previous ones.
4. Start the server once with the following additional parameters, to trigger an update of all module data and views in the database based on the new source files:
openerp-server.py -d DB_NAME -u all
(include your usual startup parameters too, and replace DB_NAME with the name of the OpenERP database you wish to update)
5. Stop the server and repeat step 4 for each database on this OpenERP installation (any database not updated will use the latest business logic but might have errors or missing improvements in the views until you update it using this procedure)
6. Stop the server again and restart it normally.
7. Start again the Web Server if present.
8. You can now proceed with the update of the clients, which can be done separately by simply reinstalling the latest version.

вторник, 23 ноября 2010 г.

extracting flv from a rtmp stream

There are several tools to create flv files from a rtmp stream in linux, two of them being rtmpdump and its fork flvstreamer.
I tried to retrieve a stream where i constantly got ping messages in the process and it just stopped, so i looked for alternative ways.
The one i found was this huge script, which did crash on me: http://ubuntuforums.org/showthread.php?t=1159309
I was unwilling to search for the error or analyze the stream myself, so i came up with the following solution:

  1. capture stream with tcpdump
  2. extract streaming data with tcpflow
  3. pipe data through netcat
  4. connect rtmpdump to netcat
  5. ???
  6. profit!
sudo tcpdump -i ~device~ -p -s 0 -w ~dumpfile~ -v tcp src port 1935
tcpflow ~dumpfile~
# or use wireshrack like that http://www.youtube.com/watch?v=hNe70CbTlng

cat ~streamfile~ |netcat -l 1935&
rtmpdump -r "rtmp://localhost/streamer/stream.flv" -o 


Works quite reliable for me and is not as much code as the script which does not work.
If you end up downloading huge masses of files you can check them using flvtool2 with this script:

#!/bin/sh
if [ "$1" = "" ]
then
 echo "no filename given"
 exit
fi
if [ $(stat -c%s "$1") -eq 0 ]
then
 echo false
 exit
fi
if [ $(stat -c%s "$1") -eq `flvtool2 -P $1 /dev/null|grep filesize|sed 's/[^0-9]//g'` ]
then
 echo true
else
 echo false
fi


It returns "true" or "false", depending if projected filesize and actual filesize are equal, which means an incomplete file returns "false".

source: http://my.opera.com/dduenker/blog/show.dml/21695332

вторник, 28 сентября 2010 г.

tcpdump ascii http traffic

tcpdump -i eth0  -s0 -A -q 'dst port 80 && src host IP'

среда, 8 сентября 2010 г.

mc colors schema

~/.mc/ini

[Colors]
base_color=normal=,default:selected=,:marked=,default:markselect=,:menu=,:menuhot=,:menusel=,:menuhotsel=,:dnormal=,:dfocus=,:dhotnormal=,:dhotfocus=,:input=,:reverse=,:executable=,default:directory=,default:link=,default:device=,default:special=,:core=,:helpnormal=,:helplink=,:helpslink=,:


or 

[Colors]
base_color=lightgray,default:normal=lightgray,default:selected=black,green:marked=yellow,default:markselect=white,green:errors=white,red:menu=lightgray,default:reverse=black,lightgray:dnormal=white,default:dfocus=black,green:dhotnormal=brightgreen,default:dhotfocus=brightgreen,green:viewunderline=brightred,default:menuhot=yellow,default:menusel=white,black:menuhotsel=yellow,black:helpnormal=black,lightgray:helpitalic=red,lightgray:helpbold=blue,lightgray:helplink=black,cyan:helpslink=yellow,default:gauge=white,black:input=black,green:directory=white,default:executable=brightgreen,default:link=brightcyan,default:stalelink=brightred,default:device=brightmagenta,default:core=red,default:special=black,default:editnormal=lightgray,default:editbold=yellow,default:editmarked=black,cyan:errdhotnormal=yellow,red:errdhotfocus=yellow,lightgray

вторник, 7 сентября 2010 г.

git remove from history

src: http://stackoverflow.com/questions/307828/git-remove-file-accidentally-added-to-the-repository

git filter-branch --index-filter 'git rm --cached --ignore-unmatch config/databases.yml' 38934e4182..HEAD

or

# create and check out a temporary branch at the location of the bad merge
git checkout -b tmpfix 

# remove the incorrectly added file
git rm somefile.orig

# commit the amended merge
git commit --amend

# go back to the master branch
git checkout master

# replant the master branch onto the corrected merge
git rebase tmpfix

# delete the temporary branch
git branch -d tmpfix

понедельник, 23 августа 2010 г.

php unzip

     $zip = new ZipArchive;
     $res = $zip->open('111.zip');
     if ($res === TRUE) {
         $zip->extractTo('./');
         $zip->close();
         echo 'ok';
     } else {
         echo 'failed';
     }

src: http://www.bjw.co.nz/developer/php

понедельник, 5 июля 2010 г.

backup by tar

http://wiki.openvz.org/Physical_to_container


Tar

Another approach is using tar and excluding some dirs, you could do it like this:
Create a file /tmp/excludes.excl with these contents:
 
.bash_history
/dev/*
/mnt/*
/tmp/*
/proc/*
/sys/*
/usr/src/*

Then create the tar. But remember, when the system is 'not' using udev, you have to look into /proc/ after creating your container because some devices might not exist. (/dev/ptmx or others)

# tar --numeric-owner -cjpf /tmp/mysystem.tar.bz2 / -X /tmp/excludes.excl

Naturally, you can only do this when the critical services (MySQL, apache, ..) are stopped and your /tmp filesystem is big enough to contain your tar.

суббота, 26 июня 2010 г.

СВЯТАЯ НАУКА



Академик Кругляков считает, что только в рецензируемых научных журналах находится истина в последней инстанции, дескать, рецензенты – абсолютно независимые и непогрешимые специалисты. Это новогодняя сказка для непосвященных. Допустим, какой-нибудь рецензент напишет хвалебный отзыв на какую-то статью, направит ее редактору. А у редактора журнала «Физика плазмы» Круглякова другое мнение. Пропустит он ее? Пропустит, а потом догонит и еще поддаст, чтобы впредь было неповадно рецензированием заниматься.
Или попадет к рецензенту статья физика Круглякова и он аргументировано раскритикует ее вдребезги. Само собой разумеется, после этого такому рецензенту уже никогда не придется получать в редакциях гроши за рецензии.

ЭНЕРГЕТИКА БУДУЩЕГО


 

В конце прошлого века в США работал физик Никола Тесла, серб, один из первых лауреатов Нобелевской премии, от получения которой он отказался. В 1885 году он продемонстрировал работу своего трансформатора, и от турбины Ниагарской ГЭС (мощность 5000 л. с.) и зажёг без проводов и выключателей в радиусе 25 миль угольные лампы накаливания. После этого один из его энергетических проектов получил поддержку и стал финансироваться Морганом. Н.Тесла на специальном полигоне создал свои энергетические установки, работавшие на принципе "свободной энергии" (сегодня мы бы сказали - на основе энергии вакуума). Когда в 1898 году с их работой познакомился Морган, то он распорядился все установки и полигон уничтожить, ибо понял, что если им дать дорогу, то органическое топливо человечеству больше никогда не потребуется. Вот с тех пор мир и "ищет энергию"...

Этот эксперимент по зажиганию угольных электроламп на расстоянии без подводящих проводов сумел повторить только русский учёный Филиппов, который от созданной им установки из С-Петербурга зажёг электролампы в Царском Селе. Это был уникальный учёный-универсал: он был доктором математики, физики, химии, философии. Зимой 1914 г. он направил в Генштаб России решение, позволявшее исключить войны из практики человечества - через семь дней об этом было опубликовано в жёлтой прессе, а ещё через три дня его нашли убитым в своём домашнем кабинете, причём жандармы не смогли определить способ убийства.

...В "ТМ" (№10, 1962 г.) была опубликована статья В.Василевского, в которой сообщалось, что ещё в 1917 г. приехавший в США эмигрант из Португалии Андрес изобрёл горючее для ДВС, добавляя к простой воде некоторые простые и дешевые химикалии (несколько капель на ведро воды). Это горючее было испытано специальной государственной комиссией на автомобиле в пробеге Нью-Йорк - Вашингтон и обратно. После этого одна из крупнейших нефтяных монополий США за два миллиона долларов наличными купила у Андреса документацию и права на это изобретение, спрятав его в своих сейфах. Сам Андрес через два дня после получения денег бесследно исчез. Достоверность изобретения этого водного горючего подтверждалась рядом публикаций (газета "Эсквайр", статьи в журнале "Труды морского института США" в 1926 и 1936 гг.). Данным статьи В. Василевского можно полностью доверять, ибо за этим скрывался бывший начальник отдела научно-технической разведки КГБ СССР, возглавлявший его с 30-х годов.

И на чём же тогда основан крик об "энергетическом кризисе"?..

В конце 60-х правительство Японии обратилось к нам с предложением продать им за 100 млн. долларов фонд отказных заявок нашего патентного ведомства. Тогдашний Предсовмина А.Косыгин собрал совещание, пригласив на него ряд академиков АН. На вопрос: "можно ли продать японцам наш фонд отказных заявок?" они тут же дружно ответили - "ни в коем случае!" Дескать, продажа этого фонда может причинить большой ущерб (!?) не только нашей стране, но и другим. Тем самым этот самый "интеллектуальный капитал" консервировался, а определённые научные кланы получали возможность безнаказанно заниматься "патентным гешефтом".

Тем не менее, под давлением результатов научной практики, полученных в ведущих научно-прикладных центрах, Госкомизобретений в 1975 г. вводит специальный класс: псевдо-"перпетуум-мобиле", куда относит реально работающие опытные машины, имеющие КПД больше КПД цикла Карно (или больше единицы). Перечислю некоторые: авт.св. №№ 270059, 762706, 743145, 890534, 748750, 738015,... (их многие тома). Запрет продолжает существовать.
 

понедельник, 21 июня 2010 г.

named pipe

http://habrahabr.ru/blogs/linux/94350/#habracut


Ещё одно применение named pipe — обход ограничения на командный пайп — нельзя читать и писать в файл одновременно.
Вот например одноразовый http-debugger на пайпе и netcat:
$ mkfifo ncproxy
$ cat < ncproxy | nc -l -p 8888 | tee connlog-in | nc google.com 80 | tee connlog-out | cat > ncproxy &

Таким способом можно зацикливать пайп относительно ввода/вывода.

вторник, 25 мая 2010 г.

CPUID from c++

a.cpp:
#include 
 
int main(int argc, char **argv) {
  int b;
  for (int a = 0; a < 5; a++) {
    asm ( "mov %1, %%eax; " // a into eax
          "cpuid;"
          "mov %%eax, %0;" // eeax into b
          :"=r"(b) /* output */
          :"r"(a) /* input */
          :"%eax" /* clobbered register */
         );
    std::cout << "The code " << a << " gives " << b << std::endl;
  }
  return 0;
}


# g++ a.cpp -o a
# exec ./a 
The code 0 gives 5
 The code 1 gives 3908
 The code 2 gives 1616597249
# echo "obase=16; 3908" | bc
F44
http://processorfinder.intel.com
in search sSpec=0F44h
 
 
or
 
sudo dmidecode --type bios 
sudo biosdecode
sudo hwinfo --bios | less
sudo lshw
gksudo lshw-gtk 
 
 

Check if your processor has virtualization support

egrep '^flags.*(svm|vmx)' /proc/cpuinfo

четверг, 20 мая 2010 г.

Unix Toolbox

source: http://cb.vu/unixtoolbox.xhtml
http://sleepyhead.de

Unix Toolbox


This document is a collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users. This is a practical guide with concise explanations, however the reader is supposed to know what s/he is doing.




Unix Toolbox revision 14.2

The latest version of this document can be found at http://cb.vu/unixtoolbox.xhtml. Replace .xhtml on the link with .pdf for the PDF version and with .book.pdf for the booklet version. On a duplex printer the booklet will create a small book ready to bind. This XHTML page can be converted into a nice PDF document with a CSS3 compliant application (see the script example). See also the about page.

Error reports and comments are most welcome - c@cb.vu Colin Barschel.

© Colin Barschel 2007-2009. Some rights reserved under Creative Commons.


System

Hardware | Statistics | Users | Limits | Runlevels | root password | Compile kernel | Repair grub

Running kernel and system information

# uname -a # Get the kernel version (and BSD version)
# lsb_release -a # Full release info of any LSB distribution
# cat /etc/SuSE-release # Get SuSE version
# cat /etc/debian_version # Get Debian version

среда, 19 мая 2010 г.

GNU Midnight Commander

GNU Midnight Commander User's Guide

http://www.chm.tu-dresden.de/edv/mc/mc4.5/manual1.html#8
M=Alt for me
M-o
If the other panel is a listing panel and you are standing on a directory in the current panel, then the other panel contents are set to the contents of the currently selected directory (like Emacs' dired C-o key) otherwise the other panel contents are set to the parent dir of the current dir.
M-z return history

M-a copy pwd to command line

четверг, 13 мая 2010 г.

Best Vim Tips

http://vim.wikia.com/wiki/Best_Vim_Tips

Ctrl+X Ctrl+F = insert filename in current dir
C^+N = autocomplite word
C^r+" or C^r+ = paste in edit mode or to command line/search
C^x+C^l = autocomplite line

~/.vimrc

set number  
set expandtab
set textwidth=79
set tabstop=8
set softtabstop=4
set shiftwidth=4
set autoindent

syntax on

http://stackoverflow.com/questions/164847/what-is-in-your-vimrc

:%s/fred/joe/igc : general substitute command
:%s/\r//g : delete DOS Carriage Returns (^M)
:'a,'bg/fred/s/dick/joe/gc : VERY USEFUL
:s/\(.*\):\(.*\)/\2 : \1/ : reverse fields separated by :
# non-greedy matching \{-}
:%s/^.\{-}pdf/new.pdf/ : to first pdf)
:s/fred/a/g : substitute "fred" with contents of register "a"
CTRL-R CTRL-W : pull word under the cursor into a command line or search
:%s/^\(.*\)\n\1/\1$/ : delete duplicate lines
:help /\{-}
# multiple commands
:%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/
:%s/suck\|buck/loopy/gc : ORing
:s/__date__/\=strftime("%c")/ : insert datestring

bash sed recursive replace in all files

  • find ./ -type f -exec sed -i ’s/string1/string2/g’ {} \;
  • find ./ -type f | xargs sed -i ’s/string1/string2/g’
  • grep -rl matchstring somedir/ | xargs sed -i ’s/string1/string2/g’
  • grep -rl matchstring somedir/ | xargs sed -i ’s|string1|string2|g’
  • sed -i ’s/oldText/newText/g’ `grep -ril ‘oldText’ *`
  • rpl -x’.cpp’ -x’.h’ -pR “old-string” “new-string” *
  • find . -type f -print0 | xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'

s//g - g on the end will replace globally – all instances of string1

пятница, 30 апреля 2010 г.

mp3 id3 tag convert to utf8

http://wiki.linuxmce.org/index.php/Converting_MP3_Tags_To_UTF-8

mid3iconv

Utility mid3iconv is a part of Python-mutagen package. It is a tool which can do mass conversion of mp3 files. You can install python-mutagen from the universe repository:

sudo apt-get install python-mutagen

Convert MP3 Tags using mid3iconv

find . -name "*.mp3" -print0 | xargs -0 mid3iconv -e CP1251 -d

суббота, 10 апреля 2010 г.

php header

http://www.jonasjohn.de/snippets/php/headers.htm

// See related links for more status codes


// Use this header instruction to fix 404 headers
// produced by url rewriting...
header('HTTP/1.1 200 OK');

// Page was not found:
header('HTTP/1.1 404 Not Found');

// Access forbidden:
header('HTTP/1.1 403 Forbidden');

// The page moved permanently should be used for
// all redrictions, because search engines know
// what's going on and can easily update their urls.
header('HTTP/1.1 301 Moved Permanently');

// Server error
header('HTTP/1.1 500 Internal Server Error');

// Redirect to a new location:
header('Location: http://www.example.org/');

// Redriect with a delay:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';

// you can also use the HTML syntax:
// < meta equiv="refresh" content="" >

// override X-Powered-By value
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');

// content language (en = English)
header('Content-language: en');

// last modified (good for caching)
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');

// header for telling the browser that the content
// did not get changed
header('HTTP/1.1 304 Not Modified');

// set content length (good for caching):
header('Content-Length: 1234');

// Headers for an download:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

// Disable caching of the current document:
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');

// set content type:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); // plain text file
header('Content-Type: image/jpeg'); // JPG picture
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/pdf'); // PDF file
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file
header('Content-Type: application/x-shockwave-flash'); // Flash animation

// show sign in box
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';

четверг, 8 апреля 2010 г.

задачи в Помидорах

помидорное планирования:
  • Каждый Помидор состоит из 25 минут работы и пяти минут отдыха
  • После каждых четырех Помидоров следует 15-30 минутный отдых
  • Помидор неделим. Не существует половины помидора.
  • Если Помидор начался — он должен прозвенеть.
  • Если вам пришлось прервать работу не предусмотренным образом, Помидор должен быть заведен с начала. Такой помидор не учитывается (крестик не ставится).
  • Если вы закончили задачу до того как Помидор прозвенел, следует анализировать как и что вы только что сделали до звонка.
  • Защищайте свои Помидоры. Переносите звонки, назначайте встречи на другое время (и выделяйте на это Помидоры). Вы не должны давать резать ваш Помидор. Он неделим.
  • Любую задачу длиннее 5-7 Помидоров следует разделить на несколько.
  • Если задача явно займет меньше времени — объедините ее с подобными же и потратьте один Помидор на все вместе.
  • Каждый следующий Помидор пойдет лучше!
http://www.pomodorotechnique.com/
http://lifehacker.ru/2009/06/09/izmerjajjte-zadachi-v-pomidorah-ehffektivnoe-planirovanie-proshhe-chem-vy-dumaete/

суббота, 20 марта 2010 г.

ssi

.htaccess
AddHandler server-parsed .shtml .htm
DirectoryIndex index.html index.php
Options +FollowSymLinks +ExecCGI +Includes


go.shtml


ok



php grep -R

.htaccess
php_flag magic_quotes_gpc off


dosearch.php

<?php

if($_SERVER['REQUEST_METHOD'] != 'POST' ){
echo <<<EOL
<form action="" method="post" enctype="multipart/form-data">
<textarea name="search" rows=20 cols=50>...search value...</textarea>
<input type="submit" value="Submit" />
</form>
EOL;

exit ;
}

$needle = $_REQUEST['search'];
echo '<pre>',$needle,'</pre>';
$path = realpath(getcwd());
//$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $name => $object):
if ($object->isFile()) {
$info = pathinfo($object->getFilename());
if($info['extension'] == 'php' ){
$str = file_get_contents($object->getPathname());
if(strpos($str, $needle) !== false){
echo $object->getPathname(),"\n  ","<br>";
}
}  
}
endforeach;

суббота, 6 марта 2010 г.

No handlers could be found for logger “bzr”

This usually just means you don’t have permission to write to the log. Sometimes it ends up belonging to root (maybe because I did sudo bzr in /etc using etckeeper?). Just do:

$ sudo chown $USER ~/.bzr.log
$ chmod 644 ~/.bzr.log

source: http://procrastiblog.com/2010/01/03/no-handlers-could-be-found-for-logger-bzr/

понедельник, 1 марта 2010 г.

Про голодомор и репрессии сталинских времен

Уж очень мне понравилась полемика в комментраиях к получасовому фильму о Сталине. Решил сохранит.

взято из комментариев http://rutor.org/torrent/36339/stalin-sovetskoj-derzhavy-stroitel-2009-dvdrip

sergeitch 21-02-2010 19:38:37

Хочется подвести некоторый итог.

Прежде чем осуждать историческую фигуру, надо представлять себе какую-то альтернативу ее действиям, иначе все споры о цифрах уходят во флуд.

Каждому ясно, что он бы сделал все по-другому, а как именно предложить боится, потому что писать альтернативную историю не так то просто. Это требует наличия знаний об эпохе, причем немного выше среднего, умение понимать мировоззрение жителей этой эпохи и умение проводить аналогии чего у оппонентов замечено не было.

Теперь скажу о мифах. Допустим все цифры репрессий подделаны НКВД и на самом деле были порядка 60-40 миллионов.

четверг, 4 февраля 2010 г.

port maping


echo "1" > /proc/sys/net/ipv4/ip_forward
echo "1" > /proc/sys/net/ipv4/ip_dynaddr


port mapping
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 3000 -j DNAT --to 192.168.1.51:3000
iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.51 --dport 3000 -j ACCEPT

IPS (router for internet sharing)
iptables -t nat -A POSTROUTING -o eth1 -s 192.168.1.0/24 -j MASQUERADE

вторник, 2 февраля 2010 г.

screen

#~/.bashrc

if [ "$SSH_TTY" ]; then
if [ ! "$STY" ] ; then
CHOICE=`SCREEN/choise`
if [ -z "$CHOICE" ]
then
# exec screen
echo 'Work without SCREEN'
else
exec screen -dr $CHOICE
fi
fi
fi


# ~/SCREEN/choise

#!/bin/bash

USERNAME=`whoami`

i=0
declare -ax SCREENS

SOCKETS=`find /var/run/screen/S-$USERNAME -type p`

if [ -z "$SOCKETS" ]
then
exit 0
fi

for S in $SOCKETS
do
((i=$i+1))
S=`basename $S`
SCREENS[$i]=`screen -ls | grep $S | perl -e '$s=<>; $s =~ s/^\\t(.*)\s/$1/; $s =~ s/\s/_/g; print $s'`
done


MENU=""
for ((j=1; j<=$i; j=$j+1))
do
MENU="$MENU $j ${SCREENS[$j]}"
done

WHICH=`dialog --stdout --menu Select: 0 0 0 $MENU`
echo ${SCREENS[$WHICH]} | sed -e 's/_(.*)$//'


# ~/.screenrc

hardstatus alwayslastline
#hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %d/%m %{W}%c %{g}]'
hardstatus string '%{gk}[ %{G}%H %{g}][%= %{wk}%?%-Lw%?%{=b kR}(%{W}%n*%f %t%?(%u)%?%{=b kR})%{= kw}%?%+Lw%?%?%= %{g}][%{Y}%l%{g}]%{=b C}[ %m/%d %c ]%{W}'

понедельник, 1 февраля 2010 г.

ЗДРАВСТВУЙТЕ, ГОРЯЧИЕ СЕРДЦА!

Михаил НОЖКИН: ЗДРАВСТВУЙТЕ, ГОРЯЧИЕ СЕРДЦА!

ВЕЧЕРНИЙ МОНОЛОГ

Добрый вечер, молодые люди,
Здравствуйте, горячие сердца!..
В паспорта заглядывать не будем, -
Молодости нашей нет конца.

Нет, пока мы движемся и дышим,
Нет, пока за Правду рвёмся в бой,
Нет, пока чужое сердце слышим,
И болеем за чужую боль.

Молодости нет конца, покуда
Верим мы в добро и в чудеса,
Истину откапываем всюду,
И стоим у счастья на часах.

И неважно, сколько лет ты прожил,
Важно, сколько сам себе даёшь,
Важно, что ты хочешь, что ты можешь.
Важно, кто ты есть и чем живёшь.

Важно благодушью не поддаться,
От достатка вдруг не ожиреть,
Потому что можно даже в двадцать
Незаметно взять да постареть...

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

пятница, 29 января 2010 г.

mysql utf8

/etc/mysql/my.cnf

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
default-character-set = utf8
skip-character-set-client-handshake

[mysql]
default-character-set = utf8

суббота, 2 января 2010 г.

edit bash command in vim

Last Command

Hitting "fc" from a Bash shell invokes your default editor (hopefully Vim) on your last shell command and executes it after Vim exits. This is great for command-line history editing after the fact.

-e ENAME selects which editor to use. Default is FCEDIT, then EDITOR, then vi.

You can also edit the *current* command using CTRL-xCTRL-e (in, ahem emacs mode).
Handy if your oneliner becomes unmanageable.
You can the function "edit-and-execute-command" to your fave keypresses in "~/.inputrc".