Разные заметки

четверг, 4 ноября 2010 г.

Linux date

Наберите команду date, чтобы посмотреть текущие дату и время. Если необходимо изменить их, воспользуйтесь следующим форматом команды:
date MMDDhhmmCCYY.ss
MM — месяц, DD — день месяца, hh — часы, mm — минуты, CCYY — 4 цифры года, ss — секунды
Например:
date 100615352006.30
Эта команда установит текущие дату и время на 06 октября 2006 года, 15:35:30.
Обратите внимание: дату и время может изменять только root-пользователь.


Установка NTP сервера для Linux и Windows клиентов:
http://www.k-max.name/linux/ntp-server-na-linux/

среда, 6 октября 2010 г.

Gentoo руссификация консоли

nano /etc/locale.gen
  • en_US.UTF-8 UTF-8
    ru_RU.UTF-8 UTF-8 
locale-gen
nano /etc/conf.d/consolefont
  • consolefont="UniCyr_8x16" 
nano /etc/conf.d/keymaps
  • keymap="ruwin_ct_sh-UTF-8"
    windowkeys="YES"
    
nano /etc/env.d/02locale
  • LANG="ru_RU.utf-8"
    LC_ALL="" 
    ##Чтобы системные сообщения выводились на английском. 
    
    LC_MESSAGES="en_US.utf-8" 
env-update && source /etc/profile /etc/init.d/consolefont restart && /etc/init.d/keymaps restart


И еще один вариант.

Формат файла crontab

В Wikipedia можно вкратце посмотреть о формате с примерами.

Строка может быть трёх типов: комментарий (начинается с #), задание переменной среды (SHELL,MAILTO,PATH,LOGNAME,HOME) или команда для cron. Строки не могут смешиваться, то есть нельзя писать комментарий в строке с командой.
С первым типом всё понятно - комментарий он и есть комментарий.
Второй тип - задание переменной выглядит как "имя_переменной = величина". За подробностями о переменных обращайтесь в справку.
Ну и третий тип, самый интересный для нас, выглядит как шесть полей разделённых пробельными символами (пробелы и/или знаки табуляции). Первые пять полей задают время для команды, шестой - имя программы:
(минуты:0-59) (часы:0-23) (дни месяца:0-31) (месяц:0-12) (день недели:0-6, 0-воскресенье) (программа_с_параметрами)
Каждое из первых пяти полей может быть задано следующим образом:
  • Звёздочка (*) - обозначает весь диапазон (от первого до последнего)
  • Диапазон чисел, от и до. Например "5-7" будет означать 5,6 и 7
  • Списки. Это числа (или диапазоны) разделенные запятыми. Например: "1,5,10,11" или "1-11,19-23".
  • Звёздочка или диапазон с шагом. Используется для пропусков в диапазонах. Шаг указывается после косой черты. Например "2-10/2" будет значить "2,4,6,8,10", а выражение "*/2" в поле "часы" будет означать "каждые два часа.
Последнее поле (шестое) определяет команду для запуска.
Примеры (взяты из Wikipedia):

# как обычно, с символа '#' начинаются комментарии
# в качестве командного интерпрететора использовать /bin/sh
SHELL=/bin/sh
# результаты работы отправлять по этому адресу
MAILTO=paul@example.org
# добавить в PATH
PATH=$PATH:$HOME/bin

#### Здесь начинаются задания
# выполнять каждый день в 0 часов 5 минут, результат складывать в log/daily
5 0 * * * $HOME/bin/daily.job >> $HOME/log/daily 2>&1
# выполнять 1 числа каждого месяца
15 14 1 * * $HOME/bin/monthly
# каждый рабочий день в 22:00
0 22 * * 1-5 echo «Пора домой» | mail -s «Уже 22:00» john

23 0-23/2 * * * echo «Выполняется в 0:23, 2:23, 4:23 и т. д.»
5 4 * * sun echo «Выполняется в 4:05 в воскресенье»
0 0 1 1 * echo «С новым годом!»
15 10,13 * * 1,4 echo «Каждый понедельник и четверг в 10:15 и 13:15»

Как добавить задачу в crontab?

Формат команды:

crontab { -l | -r | -e }

где:
-l - выводит текущих crontab файл на стандартный вывод.
-r - удаляет текущий crontab файл.
-e - используется для редактирования текущего crontab используя редактор, заданный переменной окружения VISUAL или EDITOR. Таким образом, вводим crontab -e, добавляем нужную строку с командой и нажимаем "Ctrl-D".

Настройки окружения

Надоело все время с нуля настраивать оболочку под себя.
Вот здесь выкладываю свои настройки.

.bashrc
Для root'а:

# ~/.bashrc: executed by bash(1) for non-login shells.

# Note: PS1 and umask are already set in /etc/profile. You should not
# need this unless you want different defaults for root.
#PS1='${debian_chroot:+($debian_chroot)}\h:\w\$ '
# umask 022

#PS1="\[\033[1;31m\]\h:\[\033[1;33m\](\w)\[\033[0m\]\[\033[0m\]"

lightblue='\e[1;34m'
lightgreen='\e[1;32m'
lightred='\e[1;31m'

###PS1='\[\033[01;32m\]\u\[\033[01;34m\]-\[\033[01;31m\]\h\[\033[00;34m\]{\[\033[01;34m\]\w\[\033[00;34m\]}\[\033[01;32m\]:\[\033[00m\]'
PS1="\[\033[1;30m\]\t-\[\033[1;31m\]\h:\[\033[1;33m\](\w)\[\033[0m\]\[\033[0m\]"

clear
###echo -e "${lightred}";figlet -c "DEBIAN";
echo -e "${lightgreen}Ядро: \t${lightgreen}" `uname -smr`
echo -e "${lightgreen}ОС: \t ${lightgreen}Debian  GNU/Linux ${NC}" `cat /etc/debian_version`

export LESS_TERMCAP_mb=$'\033[01;31m'
export LESS_TERMCAP_md=$'\033[01;31m'
export LESS_TERMCAP_me=$'\033[0m'
export LESS_TERMCAP_se=$'\033[0m'
export LESS_TERMCAP_so=$'\033[01;44;33m'
export LESS_TERMCAP_ue=$'\033[0m'
export LESS_TERMCAP_us=$'\033[01;32m'

# You may uncomment the following lines if you want `ls' to be colorized:
export LS_OPTIONS='--color=auto --group-directories-first'
eval "`dircolors`"
alias ls='ls $LS_OPTIONS'
alias ll='ls $LS_OPTIONS -l'
alias l='ls $LS_OPTIONS -lA'
alias la='ls $LS_OPTIONS -lah'
alias l='ls $LS_OPTIONS -CF'

#
# Some more alias to avoid making mistakes:
# alias rm='rm -i'
# alias cp='cp -i'
# alias mv='mv -i'


alias dir='dir --color=auto'
alias vdir='vdir --color=auto'

alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'

if [ -f /usr/bin/grc ]; then
  alias cvs="grc --colour=auto cvs"
  alias diff="grc --colour=auto diff"
  alias esperanto="grc --colour=auto esperanto"
  alias gcc="grc --colour=auto gcc"


#
# Some more alias to avoid making mistakes:
# alias rm='rm -i'
# alias cp='cp -i'
# alias mv='mv -i'


alias dir='dir --color=auto'
alias vdir='vdir --color=auto'

alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'

if [ -f /usr/bin/grc ]; then
  alias cvs="grc --colour=auto cvs"
  alias diff="grc --colour=auto diff"
  alias esperanto="grc --colour=auto esperanto"
  alias gcc="grc --colour=auto gcc"
  alias irclog="grc --colour=auto irclog"
  alias ldap="grc --colour=auto ldap"
  alias log="grc --colour=auto log"
  alias netstat="grc --colour=auto netstat"
  alias ping="grc --colour=auto ping"
  alias proftpd="grc --colour=auto proftpd"
  alias traceroute="grc --colour=auto traceroute"
  alias wdiff="grc --colour=auto wdiff"
fi

if [ -f /etc/bash_completion ]; then
 . /etc/bash_completion
fi

extract () {
  if [ -f $1 ] ; then
    case $1 in
      *.tar.bz2)   tar xvjf $1    ;;
      *.tar.gz)    tar xvzf $1    ;;
      *.tar.xz)    tar xvJf $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        ;;
      *.xz)        unxz $1        ;;
      *.exe)       cabextract $1  ;;
      *)           echo "\`$1': неизвестный метод сжатия файла" ;;
    esac
  else
    echo "\`$1' нет такого файла"
  fi
}



Для пользователя:
PS1="\[\033[1;30m\]\t-\[\033[1;32m\]\h:\[\033[1;33m\](\w)\[\033[0m\]\[\033[0m\]"
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias dir='dir --color=auto'
    alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# some more ls aliases
#alias ll='ls -l'
#alias la='ls -A'
#alias l='ls -CF'
alias ls='ls $LS_OPTIONS'export LS_OPTIONS='--color=auto --group-directories-first'

alias ll='ls $LS_OPTIONS -l'
alias l='ls $LS_OPTIONS -lA'
alias la='ls $LS_OPTIONS -lah'
alias l='ls $LS_OPTIONS -CF'

Screen (/etc/screenrc):
# -вместо "ctrl+a" назначена клавиша <`> (обычно она под esc и над tab),
# так что вместо двух клавиш надо жать одну. Если надо
# набрать <`>, что довольно редко требуется, то надо нажать её два раза подряд.
# -внизу терминала зеленым на чёрном статусная строка показывающая
# активные сессии и часы. Переключение между ними: `1, `2, `3 и т.п., или
# `n (next), `p (previous)
# - для CERN/Lxplus добавление в конец этого файла строк
#    # annoying RedHat/SLC backspace problem
#    bindkey ^? stuff ^H
#  решает проблему с
# - `d => detach session; screen -ls => list of detached session;
#  screen -r => reattach session.
#------------------------------------------------------------------------------
# .screenrc file based on http://www.dotfiles.com/files/3/463_screenrc.txt
#------------------------------------------------------------------------------
# SCREEN SETTINGS
#------------------------------------------------------------------------------
 escape ``                             # use ` instesd of Cntr-A
 vbell on                               # default: off
 vbell_msg "   -- Ring, Ring!! --   "   # default: "Wuff,Wuff!!"
 autodetach on                          # default: on
 startup_message off                    # default: on
 crlf off                               # default: off
 defscrollback 1024                     # default: 100
 silencewait 15                 # default: 30
 msgwait 15
 pow_detach_msg "Screen session of \$LOGNAME \$:cr:\$:nl:ended."
# change the hardstatus settings to give an window list at the bottom of the
 # screen, with the time and date and with the current window highlighted
 # caption always "%{=}%?%{b}%H %L=%{+b}%?%{y}%-Lw%47L>%?%{g}%n*%f %t %?%{y}%+Lw%?%{b}%-31=%c %l %Y-%m-%d"
hardstatus alwayslastline
#hardstatus string '%{= mK}%-Lw%{= KW}%50>%n%f* %t%{= mK}%+Lw%< %{= kG}%-=%D %d %M %Y %c:%s%{-}'
 hardstatus string '%{= kG} %{G}%H %{g}[%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}]%{D} %d/%m %c %{g}'
#------------------------------------------------------------------------------
# TERMINAL SETTINGS
#------------------------------------------------------------------------------
 #the vt100 description does not mention "dl". *sigh*
 termcapinfo  vt100 dl=5\E[M
 termcap  vt100* ms:AL=\E[%dL:DL=\E[%dM:UP=\E[%dA:DO=\E[%dB:LE=\E[%dD:RI=\E[%dC
 terminfo vt100* ms:AL=\E[%p1%dL:DL=\E[%p1%dM:UP=\E[%p1%dA:DO=\E[%p1%dB:LE=\E[%p1%dD:RI=\E[%p1%dC
 termcap  xterm hs@:cs=\E[%i%d;%dr:im=\E[4h:ei=\E[4l
 terminfo xterm hs@:cs=\E[%i%p1%d;%p2%dr:im=\E[4h:ei=\E[4l
 termcapinfo xterm Z0=\E[?3h:Z1=\E[?3l:is=\E[r\E[m\E[2J\E[H\E[?7h\E[?1;4;6l
 termcapinfo xterm* OL=100
 termcapinfo xterm 'VR=\E[?5h:VN=\E[?5l'
 termcapinfo xterm 'k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~'
 termcapinfo xterm 'kh=\EOH:kI=\E[2~:kD=\E[3~:kH=\EOF:kP=\E[5~:kN=\E[6~'
 termcapinfo xterm 'hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'
 termcapinfo xterm 'vi=\E[?25l:ve=\E[34h\E[?25h:vs=\E[34l'
 termcapinfo xterm 'XC=K%,%\E(B,[\304,\\\\\326,]\334,{\344,|\366,}\374,~\337'
 termcapinfo xterm* be
 termcapinfo linux C8
#------------------------------------------------------------------------------
# SCREEN KEYBINDINGS
#------------------------------------------------------------------------------
# Remove some stupid / dangerous key bindings
 bind k
 bind ^k
 bind .
 bind ^\
 bind \\
 bind ^h
 bind h
 bind 'K' kill
 bind 'I' login on
 bind 'O' login off
 bind '}' history
 register [ "\033:se noai\015a"
 register ] "\033:se ai\015a"
 bind ^] paste [.]
 bind = resize =
 bind + resize +3
 bind - resize -3
 bind  ) select 10
 bind  ! select 11
 bind  @ select 12
 bind \# select 13
 bind \$ select 14
 bind  % select 15
 bind \^ select 16
 bind  & select 17
 bind  * select 18
 bind  ( select 19
 logfile ~/logs/screen_%Y-%m-%d_%0c
 bindkey -k F1 prev
 bindkey -k F2 next

Nano - apхив с шаблонами,
мой /etc/nanorc:
## Sample initialization file for GNU nano.
##
## Please note that you must have configured nano with --enable-nanorc
## for this file to be read!  Also note that this file should not be in
## DOS or Mac format, and that characters specially interpreted by the
## shell should not be escaped here.
##
## To make sure a value is disabled, use "unset
##
## For the options that take parameters, the default value is given.
## Other options are unset by default.
##
## Quotes inside string parameters don't have to be escaped with
## backslashes.  The last double quote in the string will be treated as
## its end.  For example, for the "brackets" option, ""')>]}" will match
## ", ', ), >, ], and }.
## Use auto-indentation.
# set autoindent
## Backup files to filename~.
# set backup
## The directory to put unique backup files in.
# set backupdir ""
## Do backwards searches by default.
# set backwards
## Use bold text instead of reverse video text.
# set boldtext
## The characters treated as closing brackets when justifying
## paragraphs.  They cannot contain blank characters.  Only closing
## punctuation, optionally followed by closing brackets, can end
## sentences.
##
# set brackets ""')>]}"
## Do case sensitive searches by default.
# set casesensitive
## Constantly display the cursor position in the statusbar.  Note that
## this overrides "quickblank".
# set const
## Use cut to end of line by default.
# set cut
## Set the line length for wrapping text and justifying paragraphs.
## If fill is 0 or less, the line length will be the screen width less
## this number.
##
# set fill -8
## Enable ~/.nano_history for saving and reading search/replace strings.
# set historylog
## The opening and closing brackets that can be found by bracket
## searches.  They cannot contain blank characters.  The former set must
## come before the latter set, and both must be in the same order.
##
# set matchbrackets "(<[{)>]}"
## Use the blank line below the titlebar as extra editing space.
# set morespace
## Enable mouse support, if available for your system.  When enabled,
## mouse clicks can be used to place the cursor, set the mark (with a
## double click), and execute shortcuts.  The mouse will work in the X
## Window System, and on the console when gpm is running.
##
# set mouse

## Allow multiple file buffers (inserting a file will put it into a
## separate buffer).  You must have configured with --enable-multibuffer
## for this to work.
##
# set multibuffer
## Don't convert files from DOS/Mac format.
# set noconvert
## Don't follow symlinks when writing files.
# set nofollow
## Don't display the helpful shortcut lists at the bottom of the screen.
# set nohelp
## Don't add newlines to the ends of files.
# set nonewlines
## Don't wrap text at all.
# set nowrap
## Set operating directory.  nano will not read or write files outside
## this directory and its subdirectories.  Also, the current directory
## is changed to here, so any files are inserted from this dir.  A blank
## string means the operating directory feature is turned off.
##
# set operatingdir ""
## Preserve the XON and XOFF keys (^Q and ^S).
# set preserve
## The characters treated as closing punctuation when justifying
## paragraphs.  They cannot contain blank characters.  Only closing
## punctuation, optionally followed by closing brackets, can end
## sentences.
##
# set punct "!.?"
## Do quick statusbar blanking.  Statusbar messages will disappear after
## 1 keystroke instead of 26.  Note that "const" overrides this.
##
# set quickblank
## The email-quote string, used to justify email-quoted paragraphs.
## This is an extended regular expression if your system supports them,
## otherwise a literal string.  Default:
# set quotestr "^([     ]*[#:>\|}])+"
## if you have extended regular expression support, otherwise:
# set quotestr "> "
## Fix Backspace/Delete confusion problem.
# set rebinddelete
## Fix numeric keypad key confusion problem.
# set rebindkeypad
## Do extended regular expression searches by default.
# set regexp
## Make the Home key smarter.  When Home is pressed anywhere but at the
## very beginning of non-whitespace characters on a line, the cursor
## will jump to that beginning (either forwards or backwards).  If the
## cursor is already at that position, it will jump to the true
## beginning of the line.
# set smarthome
## Use smooth scrolling as the default.
# set smooth
## Use this spelling checker instead of the internal one.  This option
## does not properly have a default value.
##
# set speller "aspell -x -c"
## Allow nano to be suspended.
# set suspend
## Use this tab size instead of the default; it must be greater than 0.
# set tabsize 8
## Convert typed tabs to spaces.
# set tabstospaces
## Save automatically on exit, don't prompt.
# set tempfile
## Disallow file modification; why would you want this in an rcfile? ;)
# set view
## The two single-column characters used to display the first characters
## of tabs and spaces.  187 in ISO 8859-1 (0000BB in Unicode) and 183 in
## ISO-8859-1 (0000B7 in Unicode) seem to be good values for these.
# set whitespace "  "
## Detect word boundaries more accurately by treating punctuation
## characters as part of a word.
# set wordbounds


## Default - makes ## as comment
 include "/usr/share/nano/default.nanorc"
## Emacs
 include "/usr/share/nano/dotemacs.nanorc"
## C++
 include "/usr/share/nano/c.nanorc"
## C
 include "/usr/share/nano/c-file.nanorc"
## Pov-Ray
 include "/usr/share/nano/pov.nanorc"
## HTML
#there is better one in xml.nanorc
# include "/usr/share/nano/html.nanorc"
## TeX
 include "/usr/share/nano/tex.nanorc"
## Quoted emails (under e.g. mutt)
 include "/usr/share/nano/mutt.nanorc"
## Patch files
 include "/usr/share/nano/patch.nanorc"
## Manpages
 include "/usr/share/nano/man.nanorc"
## Groff
 include "/usr/share/nano/groff.nanorc"
## Perl
 include "/usr/share/nano/perl.nanorc"
## Python
 include "/usr/share/nano/python.nanorc"
## Ruby
 include "/usr/share/nano/ruby.nanorc"
## Java
 include "/usr/share/nano/java.nanorc"
## Assembler
 include "/usr/share/nano/asm.nanorc"
## Bourne shell scripts
 include "/usr/share/nano/sh.nanorc"
## Gentoo ebuilds and such
 include "/usr/share/nano/gentoo.nanorc"
## PHP something missing in there...
#include "/usr/share/nano/php.nanorc"
## PHP
include "/usr/share/nano/php2.nanorc"
## Xorg config
include "/usr/share/nano/xorg.nanorc"
## XML
include "/usr/share/nano/xml.nanorc"
## URLS
include "/usr/share/nano/urls.nanorc"
## CSS
include "/usr/share/nano/css.nanorc"
## Conky
include "/usr/share/nano/conky.nanorc"
## .cf
include "/usr/share/nano/maincf.nanorc"
## *rc - catches more files for now
#include "/usr/share/nano/rcfiles.nanorc"
## *rc
include "/usr/share/nano/rcfiles-new.nanorc"
## profile
include "/usr/share/nano/profile.nanorc"
## java script
include "/usr/share/nano/js.nanorc"
## configs
include "/usr/share/nano/configfiles.nanorc"
## Xstuff
include "/usr/share/nano/xdefaults.nanorc"
## configs
include "/usr/share/nano/config.nanorc"
## configs
include "/usr/share/nano/config2.nanorc"
## configs
include "/usr/share/nano/config3.nanorc"
## configs
include "/usr/share/nano/tab.nanorc"
## configs
include "/usr/share/nano/passwd.nanorc"
include "/usr/share/nano/desc.nanorc"
## Delphi
include "/usr/share/nano/delphi.nanorc"
# ChangeLog - colors everything in blue
#include "/usr/share/nano/changelog.nanorc"
## ChangeLog            (C)ryszardzonk
include "/usr/share/nano/changelogs.nanorc"
## video metadata info  (C)ryszardzonk
include "/usr/share/nano/info.nanorc"
## configs in /etc      (C)ryszardzonk
include "/usr/share/nano/etc-stuff.nanorc"
## logs in /var/log     (C)ryszardzonk
include "/usr/share/nano/log-stuff.nanorc"
## nanorc syntax
include "/usr/share/nano/nanorc.nanorc"
## *.po files           (C)ryszardzonk
include "/usr/share/nano/po.nanorc"
## Apache 2
include "/usr/share/nano/apache2.nanorc"
## Apache 2 Virtual Host
include "/usr/share/nano/vhost.nanorc"
## /etc/init.d/*        custom gentoo.nanorc
include "/usr/share/nano/initscript.nanorc"
## Named                (C)ryszardzonk
include "/usr/share/nano/named.nanorc"
## File Types           (C)ryszardzonk
include "/usr/share/nano/mimetype.nanorc"
## /etc/initng/         custom sh.nanorc
include "/usr/share/nano/initng.nanorc"
## /etc/xml         custom xml.nanorc
include "/usr/share/nano/etcxml.nanorc"
## sh.nanorc syntax for custom files
include "/usr/share/nano/shlike.nanorc"
## c.nanorc syntax for custom files
include "/usr/share/nano/clike.nanorc"
## EKG History view     (C)ryszardzonk
include "/usr/share/nano/ekghistory.nanorc"
## others               (C)ryszardzonk
include "/usr/share/nano/others.nanorc"
## others               (C)ryszardzonk + LinuxHelp Wiki
include "/usr/share/nano/makefile.nanorc"
## postegreSQL
## postegreSQL
include "/usr/share/nano/postgresql.nanorc"
## Debian Sources (off by default)
#include "/usr/share/nano/sources_list.nanorc"
## SoftCam.Key mgcamd
include "/usr/share/nano/softcam.nanorc"
## Paludis http://gentoo-wiki.com/TIP_Nano_Context_Highlighting
include "/usr/share/nano/paludis.nanorc"
## HAVP config          (C)ryszardzonk
include "/usr/share/nano/havp.nanorc"
## Privoxy              (C)ryszardzonk
include "/usr/share/nano/privoxy.nanorc"
## Asterisk syntax highlighting
include "/usr/share/nano/asterisk.nanorc"

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

Трафик компьютера в сети

tcpdump -i eth0 port www and host

LiveCD Debian на flash-диске

Устанавливаем программы:
apt-get install live-helper qemu


Выполняем команды:
lh_clean --binary
lh_config -b usb-hdd -p gnome
# lh_config --apt aptitude --binary-images --hostname live-machine --username sergey
lh_config --bootappend-live "locale=ru_RU.UTF-8"
lh_config --checksums disabled
lh_config --interactive shell
# lh_config --apt aptitude --binary-images --hostname live-machine --username sergey -b usb-hdd -p gnome --bootappend-live "locale=ru_RU.UTF-8" --checksums disabled  --interactive shell

lh_build



Ожидаем возврата в командную строку и устанавливаем в шелл нужные нам пакеты, например:
apt-get install mc gparted ssh dialog xdialog

Затем выходим:
logout

Проверяем образ с помощью виртуальной машины:
qemu -hda binary.img

Записываем на флешку:
dd if=binary.img of=/dev/sdb

Windows update через squid

acl windowsupdate dstdomain windowsupdate.microsoft.com .update.microsoft.com download.windowsupdate.com redir.metaservices.microsoft.com images.metaservices.microsoft.com c.microsoft.com www.download.windowsupdate.com wustat.windows.com crl.microsoft.com

acl CONNECT method CONNECT
acl wuCONNECT dstdomain www.update.microsoft.com

http_access allow CONNECT wuCONNECT
http_access allow windowsupdate


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

Работаем с tar bz2

ДЛЯ BZ2

Свернуть файлы:
tar -cvjf имяархива.tar.bz2 списокфайлов
или
tar -cvf - файлы | bzip2 -9 > имяархива.tar.bz2

Распаковать:
tar -xvf имяархива.tar.bz2
или
bzip2 -cd имяархива.tar.bz2 | tar -xvf -

ДЛЯ GZ

Распаковать:
tar xvfz *.tar.gz

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

Использование комманд diff и patch

$diff file1 /new/file2

77d76 - удалит строку 77 в файле file1 чтобы получить аналог file2

186c186
< { prn2f("\tDump ERROR!\n");}
---
> { prn2f("Dump ERROR!\n");}

замена 186 строки file1 (< { prn2f("\tDump ERROR!\n");})
на 186 строку file2 (> { prn2f("Dump ERROR!\n");})

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

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

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


Знак "<" означает, что патч должен удалить символы после этого знака, а знак ">" означает, что символы после этого знака надо добавить. Когда надо заменить строки ("c" между номерами строк), вы увидите оба знака: и "<", и ">". Когда надо добавить строку ("a" между номерами строк), вы увидите только знак ">", а когда надо удалить строку ("d" между номерами строк), вы увидите только знак "<". Строка "\ No newline at end of file" появилась из-за того, что я не не нажал enter после того как набрал слова. Считается хорошим тоном заканчивать текстовый файл пустой строкой. Некоторым программам она необходима для работы.


$ diff file1 /new/file2 > patch.now

И затем применить патч:
$ patch file1 -i patch.now -o file1.patching



Если все прошло хорошо, должен получиться файл, идентичный обновленному. Вы можете убедиться в этом, используя команду diff с опцией "-s":
 $ diff -s file1.patching /new/file2 
Файлы file1.patching и /new/file2 идентичны 

Оригинал http://www.ylsoftware.com/news/243

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

BASH замена символов в файле

Для замены "a" на "A" (только первые встречающиеся буквы в строке):
$ sed 's/a/A/' имя файла

и с сохранением результата
$ sed 's/a/A/' имя файла > имя файла2

Для замены "a" на "A" (весь текст):
$ sed 's/a/A/g' имя файла

и с сохранением результата
$ sed 's/a/A/g' имя файла > имя файла2

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

Perl перенаправление ввода-вывода

#!/usr/bin/perl
### ПЕРЕМЕННЫЕ
$log="log.log";
$out="out.dat";
$err="err.dat";
###
#system ("rm $out $log $err");
 

### Сохраняем стандартный вывод и вывод ошибок
open(SAVEOUT, ">&STDOUT");
open(SAVEERR, ">&STDERR");
 

### Открываем файл для записи
open (LOG,"> $log") or die "do not open $log!!!\n";
 
### Процедура вывода в файл
sub prn2f {
        $param =$_[0];
        select (LOG); $|=1;
        print $param;
}
 
### Процедура вывода в изначальный STDOUT
sub prn2std {
        $param =$_[0];
        select (SAVEOUT); $|=1;
        print $param;
        select (LOG); $|=1;
}
 
### Процедура вывода в изначальный STDERR
sub prn2err {
        $param =$_[0];
        select (STDERR); $|=1;
        print $param;
        select (LOG); $|=1;
}
### Перенаправляем STDOUT и STDERR в файлы
sub std2file {
        open (STDOUT, "> $out") or die "do not forward STDOUT to $out...\n";
        open (STDERR, "> $err") or die "do not forward STDERR to $err....\n";
        select(STDERR); $| = 1; # отключаем буферизацию
        select(STDOUT); $| = 1; # отключаем буферизацию


### Восстанавливаем вывод
sub std2std {
        open(STDOUT, ">&SAVEOUT");
        open(STDERR, ">&SAVEERR");
}


### НАЧАЛО   ПРИМЕРА
prn2std ("Вывод в стандартную консоль\n");
prn2f ("Вывод в файл\n");
prn2err("Вывод в поток ошибок\n");

std2file();
prn2std ("Вывод в стандартную консоль\n");
prn2f ("Вывод в файл\n");
prn2err("Вывод в поток ошибок\n");

std2std();

### КОНЕЦ
__END__

суббота, 15 мая 2010 г.

SSH доступ без пароля

Создаем открытый и закрытый ключ нашей локальной системы (с которой хотим подключаться к серверу):
$ ssh-keygen -t dsa –b 1024

Приватный ключ сохраняется в ~/.ssh/id_dsa или ~/.ssh/id_rsa, а публичный в ~/.ssh/id_dsa.pub или ~/.ssh/id_rsa.pub (для ключей DSA и RSA соответственно).

Для включения аутентификации по ключам публичный ключ должен быть помещен в файл ~/.ssh/authorized_keys на компьютер К КОТОРОМУ мы собираемся подключаться без пароля.

Копируем ключ на удаленный компьютер. Любыми безопасными методами.
Например:
$ scp ~/.ssh/id_rsa.pub user@(ip-адрес):~/.ssh/authorized_keys

Спросит пароль пользователя user.


Если используем ключи RSA то добавляем в файл authorized_keys:
$ cat id_rsa.pub >> authorized_keys

Если используем ключи DSA то добавляем в файл authorized_keys:
$ cat id_dsa.pub >> authorized_keys2



Настраиваем права доступа, хост зеркало:
$ chmod 700 ~/.ssh
$ chmod 600 authorized_keys 


Проверяем соединение без пароля:
ssh -i ~/.ssh/id_dsa -p22 user@(ip-адрес)

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

Chmod файлам и папкам

Требовалось назначить минимальные права на все содержимое каталога (каталогам 755, файлам 644 ).

find ./path -type f -exec chmod 644 {} \;
find ./path -type d -exec chmod 755 {} \;

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

Сервер терминалов Windows 2008, 1C и wtware

http://interface31.ru/tech_it/2009/09/windows-server-2008-novie-vozmozhnosti-sluzhb-terminalov.html

http://interface31.ru/tech_it/2009/10/1s-predpriyatie-77-osobennosti-raboty-v-windows-7-vista.html

а это так.... для другого дела http://interface31.ru/tech_it/2009/11/linux-nastrojka-routera-nat-dhcp-squid.html

Jabber server OPENFIRE

Скачиваем отсюда http://www.igniterealtime.org/downloads/index.jsp deb-пакет.
Ставим как обычно:
dpkg -i <имя>.deb

Если чего нехватает - будет ругаться на неудовлетворенные зависимости.
Тогда:
aptitude -f install

Заходим на адрес броузером: https://<айпи>:9091 и настравиваем сервер в режиме web-setup.

Запоминаем пароль. Входим на сервер и производим необходимые настройки сервиса.

Дополнительные сведения:
настройка http://www.tux.in.ua/articles/383
много http://forum.ru-board.com/topic.cgi?forum=8&topic=27991&start=2100

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

Полный бэкап Linux системы

Для начала заходим в консоль из под рута, затем идём в корень системы и соответственно тарим все данные:

sudo su
cd /
tar jcvpf sys_backup.tar.bz2 --exclude=/proc --exclude=/lost+found --exclude=/sys_backup.tar.bz2 --exclude=/mnt --exclude=/sys /


Если выполнять в screen то можно мониторить состояние в другом окне
watch -d -n2 "ls -sh | sort -r"

потом сливаем файл куда надо и спим спокойно.

среда, 21 апреля 2010 г.

Samba это не совсем танец

доп. инфа. http://www.osp.ru/lan/2000/03/130995/_p1.html
http://linux.yaroslavl.ru/docs/serv/samba/samba_conf.html
http://interface31.ru/tech_it/2010/03/sozdanie-fajlovogo-servera-na-ubuntu-910.html


#======================= Global Settings =====================================
[global]
;include = /usr/local/samba/lib/smb.conf.%m
workgroup = ALTEK
netbios name = baff01
server string = baff01


security = user
encrypt passwords = yes
;unix password sync = yes


hosts allow = 192.168.0. 127.0.0.1
interfaces = 127.0.0.1/255.255.255.0 192.168.0.1/255.255.255.0


log file = /var/log/samba/log.%m
max log size = 10
log level = 1


os level = 255
local master = yes
preferred master = yes
;domain master = no
;domain logons = yes


name resolve order = lmhosts host wins bcast


;logon script = %m.bat
;logon script = %U.bat
logon path = \\%L\Profiles\%U


;wins support = yes
dns proxy = no


socket options = TCP_NODELAY SO_KEEPALIVE SO_SNDBUF=16384 SO_RCVBUF=16384




;load printers = yes
;printcap name = /etc/printcap
;printcap name = lpstat
;printing = cups

#============================ Share Definitions ==============================
[homes]
comment = Only for YOU
browseable = no
writable = yes
hide dot files = yes
valid users = %S
create mask = 0644
directory mask = 0755


[1C-Bases]
comment = Allow all user
path = /home/shares/1C-Bases
writeable = yes
create mask = 0777
directory mask = 0777


[Documents]
comment = Allow all user
path = /home/shares/Documents
writeable = yes
create mask = 0777
directory mask = 0777