LinuxForum.Fans
Тема

Sysadmins tips and tricks

Автор: zenon 6 сообщений 10204 просмотров 📌 закреплена
22.01.2012 13:02 #223645

Тема для всевозможных админ - хитростей и трюков, флуда и обсуждений тут не потерплю.
Для обсуждений - http://linuxforum.ru/viewtopic.php?id=19704
....
Начну:
....
Бэкап MySQL с удаленного сервера таблицы с именем dbname:

text
ssh user@host 'mysqldump -u'root' -p'pass' dbname | gzip' > /path/to/backups/db-backup-`date +%Y-%m-%d`.sql.gz

Тоже только полностью всё:

text
ssh user@host 'mysqldump -u'root' -p'pass' | gzip' > /path/to/backups/db-backup-`date +%Y-%m-%d`.sql.gz

Бэкап всех MySQL баз, для каждой таблицы отдельный файл:

text
while read; do mysqldump -u'root' -p'pass' $REPLY | gzip > "/path/to/backup/$REPLY.sql.gz"; done \
            < <( mysql -u'root' -p'pass' -e 'show databases' -s --skip-column-names )

Меняем pass на свой root пароль MySQL и путь /path/to/backup на свой.

22.01.2012 17:21 · отредактировано #223674

Ищем пробелы в названиях файлов (в текущем каталоге) и заменяем их на "_" (знак подчеркивания).

text
find . -maxdepth 1 -name "* *" -type f | while read src; do mv "$src" `echo $src | tr " " "_"`; done 

maxdepth 1 - указывает на то чтобы переименование было только в текущем каталоге, если надо рекурсивно по каталогам, начиная от текущего:

text
find . -name "* *" -type f | while read src; do mv "$src" `echo $src | tr " " "_"`; done

+++
Заменяем символы в верхнем регистре на нижний + заменяем пробелы на "_".

text

#!/bin/bash
IFS="$(printf '\n\t')"   
for file in ./* ; do        
  if [ -f "$file" ] ; then  
     f=$(echo $file | tr A-Z a-z | tr ' ' _)
     if [ ! "$file" == "$f" ] ; then mv "$file" "$f"; fi
  fi
done
unset IFS

В соответствии с http://www.dwheeler.com/essays/filenames-in-shell.html
+++
Только удалить пробелы из названий файлов, в текущем каталоге:

text

#!/bin/bash
IFS="$(printf '\n\t')"   
for file in ./* ; do        
  if [ -f "$file" ] ; then  
     f=$(echo $file | tr -d ' ')
     if [ ! "$file" == "$f" ] ; then mv "$file" "$f"; fi
  fi
done

Для тестирования - перед командой mv добавить echo, переименовывать не будет, только отобразит как это будет происходить, например:

text

#!/bin/bash
IFS="$(printf '\n\t')"   
for file in ./* ; do        
  if [ -f "$file" ] ; then  
     f=$(echo $file | tr -d ' ')
     if [ ! "$file" == "$f" ] ; then echo mv "$file" "$f"; fi
  fi
done

+++
+++
Чтобы посмотреть как это работает:

text
echo " test test test " | tr -d ' '

результат:

text
testtesttest

Тоже самое используя sed:

text
echo " test test test " | sed 's/ //g'

результат:

text
testtesttest
text
echo " test test test " | sed 's/ /_/g'

результат:

text
_test_test_test_

+++
+++
Еще один вариант:

text
#!/bin/bash
IFS=$'\n'
for f in `find .`; do
    file=$(echo $f | tr [:blank:] '_')
    [ -e $f ] && [ ! -e $file ] && mv "$f" $file
done
unset IFS

Однострок:

text

IFS=$'\n';for f in `find .`; do file=$(echo $f | tr [:blank:] '_'); [ -e $f ] && [ ! -e $file ] && mv "$f" $file;done;unset IFS

+++
И интересный способ с find - верхний регистр в нижний, текущий каталог.

text
find . -type f -name '*[A-Z]*' -execdir bash -c 'mv "$0" "$(echo "$0" | tr "[:upper:]" "[:lower:]")"' {} \;
22.01.2012 21:56 #223779

Резервная копия прав на файлы/каталоги:

text
getfacl -R /var/www > permissions.acl

Сохранит установленные права на каталоги/файлы, включая подкаталоги, начиная с /var/www в файл permissions.acl
Восстановление:

text
setfacl --restore=permissions.acl

Путь указывать не надо, потому как getfactl сохраняет полный путь.

23.01.2012 12:58 #223879

Упрощаем авторизацию ssh.
Рут не нужен.
Можно прописать альясы в .bashrc или .zshrc, но у ssh есть собственные инструменты для этого.

text
mkdir /home/username/.ssh && chmod 700 /home/username/.ssh
text
vim /home/username/.ssh/config
text
Host ex1
   HostName example1.com
   Port 62333
   User username

Host ex2 HostName example2.com Port 22000 IdentityFile ~/.ssh/id_rsa User username ServerAliveInterval 30 ServerAliveCountMax 120 LocalForward 63333 localhost:3306 # Тунель для MySQL; 63333 - локальный порт; localhost:3306 - хост и порт на удаленной машине

Host ex3 HostName 10.10.0.1 Port 22 IdentityFile ~/.ssh/id_rsa User username Compression yes CompressionLevel 9

Думаю все понятно.
Теперь заходить можно просто:

text
ssh ex1
ssh ex2
ssh ex3

Копировать можно так:

text
scp filename.zip ex2

Читаем: man ssh_config
http://linux.die.net/man/5/ssh_config

14.03.2012 18:55 #237628

Мой ~/.zshrc

text
# разукрашиваем ls и автодополнение
export LS_COLORS='no=00;37:fi=00;37:di=01;36:ln=04;36:pi=33:so=01;35:do=01;35:bd=33;01:cd=33;01:or=31;01:su=37:sg=30:tw=30:ow=34:st=37:ex=01;31:*.cmd=01;31:*.exe=01;31:*.com=01;31:*.btm=01;31:*.sh=01;31:*.run=01;31:*.tar=33:*.tgz=33:*.arj=33:*.taz=33:*.lzh=33:*.zip=33:*.z=33:*.Z=33:*.gz=33:*.bz2=33:*.deb=33:*.rpm=33:*.jar=33:*.rar=33:*.jpg=32:*.jpeg=32:*.gif=32:*.bmp=32:*.pbm=32:*.pgm=32:*.ppm=32:*.tga=32:*.xbm=32:*.xpm=32:*.tif=32:*.tiff=32:*.png=32:*.mov=34:*.mpg=34:*.mpeg=34:*.avi=34:*.fli=34:*.flv=34:*.3gp=34:*.mp4=34:*.divx=34:*.gl=32:*.dl=32:*.xcf=32:*.xwd=32:*.flac=35:*.mp3=35:*.mpc=35:*.ogg=35:*.wav=35:*.m3u=35:';
export GREP_COLOR="1;33"
[[ -x $(whence -p most) ]]; export PAGER=$(whence -p most)
export EDITOR="/usr/bin/vim"
export DIRSTACKSIZE=20
export PAGER="/usr/bin/most"
# export PAGER='less -X -M'
export PATH="$PATH":/usr/local/sbin
export LANG="ru_RU.UTF-8"
export LC_ALL="ru_RU.UTF-8"
export LC="ru_RU.UTF-8"
export LESSCHARSET="UTF-8"

HISTFILE=~/.zsh_history SAVEHIST=1000 HISTSIZE=1000

zstyle ':completion:*' menu yes select zstyle ':completion:*' menu select=2 zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*' verbose yes zstyle ':completion:*:descriptions' format '%U%B%d%b%u' zstyle ':completion:*:messages' format '%d' zstyle ':completion:*:warnings' format 'No matches for: %d' zstyle ':completion:*' group-name '' zstyle ':completion:*' squeeze-slashes true # Remove trailing slashes zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s zstyle ':completion:*' use-cache on zstyle ':completion:*' cache-path ~/.zsh_cache zstyle ':completion:*:(all-|)files' ignored-patterns '(|*/)CVS' zstyle ':completion:*:cd:*' ignored-patterns '(*/)#CVS' zstyle ':completion:*' completer _complete _match _approximate zstyle ':completion:*:match:*' original only # zstyle ':completion:*:approximate:*' max-errors 1 numeric zstyle -e ':completion:*:approximate:*' max-errors 'reply=($((($#PREFIX+$#SUFFIX)/3))numeric)' zstyle ':completion:*:functions' ignored-patterns '_*' zmodload zsh/complist zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*:rm:*' ignore-line yes zstyle ':completion:*:mv:*' ignore-line yes zstyle ':completion:*:cp:*' ignore-line yes zstyle ':completion:*:sudo:*' command-path /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin /usr/X11R6/bin zstyle ':completion:*:*:kill:*:processes' list-colors "=(#b) #([0-9]#)*=36=31" zstyle ':completion:*:*:kill:*' menu yes select zstyle ':completion:*:kill:*' force-list always zstyle ':completion:*:*:killall:*' menu yes select zstyle ':completion:*:killall:*' force-list always zstyle ':completion:*:processes' command "ps -au$USER" zstyle ':completion:*:cd:*' ignore-parents parent pwd

autoload -Uz compinit; compinit autoload zkbd autoload colors; colors autoload -U edit-command-line autoload -U url-quote-magic autoload -U zcalc

bindkey -e bindkey "^[[A" history-search-backward bindkey "^[[B" history-search-forward bindkey "\e[1~" beginning-of-line # Home bindkey "\e[4~" end-of-line # End bindkey "\e[5~" beginning-of-history # PageUp bindkey "\e[6~" end-of-history # PageDown bindkey "\e[2~" quoted-insert # Ins bindkey "\e[3~" delete-char # Del bindkey "\e[5C" forward-word bindkey "\eOc" emacs-forward-word bindkey "\e[5D" backward-word bindkey "\eOd" emacs-backward-word bindkey "\e\e[C" forward-word bindkey "\e\e[D" backward-word bindkey "\e[Z" reverse-menu-complete # Shift+Tab bindkey "\e[7~" beginning-of-line # Home bindkey "\e[8~" end-of-line # End bindkey "\eOH" beginning-of-line bindkey "\eOF" end-of-line bindkey "\e[H" beginning-of-line bindkey "\e[F" end-of-line

# Options {{{ setopt auto_cd autocd setopt hist_ignore_all_dups setopt hist_ignore_space histignoredups setopt inc_append_history setopt APPEND_HISTORY setopt autopushd pushdminus pushdsilent pushdtohome setopt cdablevars setopt ignoreeof # Prevent from using Ctrl + d setopt interactivecomments # setopt nobanghist setopt noclobber setopt HIST_REDUCE_BLANKS setopt HIST_IGNORE_SPACE setopt SH_WORD_SPLIT setopt nohup setopt chase_links setopt hist_verify setopt extendedglob # Use regexp in commands (ex : cp ^*.(tar|bz2|gz)) setopt IGNORE_EOF setopt nullglob setopt notify globdots autolist # setopt correct correctall setopt recexact longlistjobs setopt autoresume rcquotes mailwarning unsetopt bgnice autoparamslash unsetopt beep unsetopt hist_beep unsetopt list_beep unsetopt BSD_ECHO unalias run-help autoload run-help set always_to_end # }}}

## Coloring man pages man() { env \ LESS_TERMCAP_mb=$(printf "\e[1;37m") \ LESS_TERMCAP_md=$(printf "\e[1;37m") \ LESS_TERMCAP_me=$(printf "\e[0m") \ LESS_TERMCAP_se=$(printf "\e[0m") \ LESS_TERMCAP_so=$(printf "\e[1;47;30m") \ LESS_TERMCAP_ue=$(printf "\e[0m") \ LESS_TERMCAP_us=$(printf "\e[0;36m") \ man "$@" }

# распаковка архива extract () { if [ -f $1 ] ; then case $1 in *.tar.bz2) tar xjf $1 ;; *.tar.gz) tar xzf $1 ;; *.bz2) bunzip2 $1 ;; *.rar) unrar x $1 ;; *.gz) gunzip $1 ;; *.tar) tar xf $1 ;; *.tbz2) tar xjf $1 ;; *.tgz) tar xzf $1 ;; *.zip) unzip $1 ;; *.Z) uncompress $1 ;; *.7z) 7z x $1 ;; *) echo "я не в курсе как распаковать '$1'..." ;; esac else echo "'$1' is not a valid file" fi }

# упаковка в архив pack () { if [ $1 ] ; then case $1 in tbz) tar cjvf $2.tar.bz2 $2 ;; tgz) tar czvf $2.tar.gz $2 ;; tar) tar cpvf $2.tar $2 ;; bz2) bzip $2 ;; gz) gzip -c -9 -n $2 > $2.gz ;; zip) zip -r $2.zip $2 ;; 7z) 7z a $2.7z $2 ;; *) echo "'$1' cannot be packed via pk()" ;; esac else echo "'$1' is not a valid file" fi }

# перенаправляем READNULLCMD=${PAGER}

# цветной grep alias grep='grep --color=auto' alias df='df -h' alias du='du -h' alias ls='ls -F --color=auto' alias ll="ls -lah" alias man="LC_ALL="ru_RU.UTF-8" man"

# разукрашиваем некоторые команды с помощью grc [[ -f /usr/bin/grc ]] && { alias ping="grc --colour=auto ping" alias traceroute="grc --colour=auto traceroute" alias make="grc --colour=auto make" alias diff="grc --colour=auto diff" alias cvs="grc --colour=auto cvs" alias netstat="grc --colour=auto netstat" }

# разукрашиваем логи с помощью grc alias logc="grc cat" alias logt="grc tail" alias logh="grc head" alias -g HE='2>>( sed -ue "s/.*/$fg_bold[red]&$reset_color/" 1>&2 )' # Highlight Errors

# Установка PROMT # # левый # PROMPT="%{$fg_bold[yellow]%}G$%{$reset_color%}" # правый - когда всё гуд хороший смайлик, когда ошибка то грусный, ну и цветные ясен фиг # RPROMPT="%{$fg_bold[grey]%}%~/ %{$reset_color%}% %(?,%{$fg[green]%}:%)%{$reset_color%},%{$fg[red]%}:(%{$reset_color%}" # вопрос на автокоррекцию # SPROMPT='zsh: Заменить '\''%R'\'' на '\''%r'\'' ? [Yes/No/Abort/Edit] ' # # [[ ${TERM} =~ screen ]] && precmd() { print -Pn "\e]2;%2d\a" } || RPROMPT='%F{white}%~%f' PS1='%B%F{cyan}%#%f%b ' PS2=' ' PS3='%B%F{white}?# %b%f%F{red}%# %f' PS4='%B%F{white}%_ %b%f%F{magenta}%# %f%B%F{white}+%N:%i %b%f%F{magenta}%# %f'

02.06.2012 18:31 #256215

Скрипт блокировки IP адресов.

text
#!/bin/bash
# Simple iptables IP/subnet block script
# -------------------------------------------------------------------------
# Copyright (c) 2004 nixCraft project <http://www.cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
IPT=/sbin/iptables
SPAMLIST="spamlist"
SPAMDROPMSG="SPAM LIST DROP"
BADIPS=$(egrep -v -E "^#|^$" /root/iptables/blocked.ips)
 
# create a new iptables list
$IPT -N $SPAMLIST
 
for ipblock in $BADIPS
do
   $IPT -A $SPAMLIST -s $ipblock -j LOG --log-prefix "$SPAMDROPMSG"
   $IPT -A $SPAMLIST -s $ipblock -j DROP
done
 
$IPT -I INPUT -j $SPAMLIST
$IPT -I OUTPUT -j $SPAMLIST
$IPT -I FORWARD -j $SPAMLIST

Найдено тут - http://bash.cyberciti.biz/firewall/iptables-block-ip-address/
Там же еще много интересных скриптов.

Войдите или зарегистрируйтесь, чтобы ответить.