terça-feira, 31 de julho de 2012

Atenção com SORT em LINUX

Por default, algumas compilações/distribuições LINUX (como o CentOS), tem o seu ambiente definido de modo com que o aplicativo SORT considere em seu processo de ordenação apenas os caracteres válidos em dicionário - ou seja, caracteres alfanuméricos (a/A-z/N e 0-9), sem pontuações (! ? , . <espaço>, etc). Caso você necessite que tais caracteres sejam considerados na ordenação deve-se, independente dos parâmetros do próprio SORT (como -d -g e outros) alterar a variável de ambiente LC_ALL para C, e na sequência executar o SORT. Veja como:

export LC_ALL=C; sort <parâmetros>

Esta observação faz parte inclusive da documentação do GNU-SORT, conforme texto abaixo:

*** WARNING *** The locale specified by the environment affects sort order.  Set LC_ALL=C  to  get  the  traditional sort order that uses native byte values.


segunda-feira, 30 de julho de 2012

Executando programas/jobs em Background

Para executar e controlar programas/scripts como jobs em background em ambiente Linux, utiliza-se os comandos bg, fg e jobs.

Para colocar um programa em background, pode-se fazer de duas maneiras:

1) Usando o & ao final do comando:
exemplo:

$ vi teste.txt &
[2] 6865


2) Após o início da execução do programa, usar o conjunto de teclas <CTRL-Z>

$ man fg


[1]+  Stopped                 man fg


Para verificar os jobs sendo executados utiliza-se o comando jobs
exemplo:
jobs

[1]-  Stopped                 man fg
[2]+  Stopped                 vi teste.txt


jobs -l
[1]-  6836 Stopped                 man fg
[2]+  6865 Stopped (tty output)    vi teste.txt



3) Para colocar o programa para ser executado em background utiliza-se o comando bg <job>
exemplo:

$ jobs
[1]-  Stopped                 man fg
[3]+  Stopped                 gedit teste.txt



$ bg 3
[3]+ gedit teste.txt &

$ jobs -l
[1]+  6918 Stopped                 man fg
[3]-  6942 Running                 gedit teste.txt &



4) Para trazer um programa que está sendo executado em background para foreground (pra frente) utiliza-se o comando fg <job>.
exemplo;
fg 1

quinta-feira, 26 de julho de 2012

Executar um comando periodicamente

Para executar um comando a cada tempo, pode-se usar o comando watch do linux:

Sintaxe

watch -n <segundos> '<comando>'

onde:
<segundos> intervalo de tempo (em segundos) - Default 2 segundos
<comando> comando a ser executado

Exemplo

watch 'ls -lhtr' -> Lista o diretório a cada 2 segundos


Compactar arquivos usando Multi Thread

Para compactar (e descompactar) arquivos em máquinas com mais de um núcleo a sugestão é utilizar o utilitário pigz (http://zlib.net/pigz/) que possui os mesmos paramêtros do gzip e trabalha com diversas threads !

terça-feira, 24 de julho de 2012

Como mover os "n" primeiros arquivos de um diretório para outro

O problema é simples:  você tem um diretório com MUITOS (mas muitos mesmo!) arquivos e, por simplicidade, você quer separá-los em "n" diretórios.

a solução?

mv `ls | head -100` ./subdir1/

a linha acima move os 100 primeiros arquivos listados no ls para o diretório subdir1.  Se você executar novamente, vai pegar os próximos 100 e assim sucessivamente...


quarta-feira, 18 de julho de 2012

Contando e calculando percentuais em MySQL

Queremos contar o número de chamadas no banco que tenham determinado comprimento ("len" do campo) e calcular seu percentual em relação ao total.  Como fazer?


select length(ass_a),count(*) as cont, count(*)*t.factor as pct from tabela_1
join (select 100/count(*) as factor from tabela_1) as t
group by 1;

O resultado:
Length(ass_a)    |    cont    |  pct
2                        |     683    | 0.2049
11                      | 284592  | 85.3776
(...)

terça-feira, 17 de julho de 2012

OpenVPN no Linux

Algumas dicas para uso do OpenVPN no Linux:

1) lembre-se de que no linux o ambiente é case-sensitive, por isso se no seu arquivo de configuração você apontar para Arquivo.crt ele deverá existir com este nome e não como arquivo.crt, por exemplo;

2) Script para usar o OpenVPN como serviço:

#!/bin/sh
#
# openvpn       This shell script takes care of starting and stopping
#               openvpn on RedHat or other chkconfig-based system.
#
# chkconfig: - 24 76
#
# processname: openvpn
# description: OpenVPN is a robust and highly flexible tunneling \
#              application that uses all of the encryption, \
#              authentication, and certification features of the OpenSSL \
#              library to securely tunnel IP networks over a single UDP \
#              port.
#

### BEGIN INIT INFO
# Provides: openvpn
# Required-Start: $network
# Required-Stop: $network
# Short-Description: start and stop openvpn
# Description: OpenVPN is a robust and highly flexible tunneling \
#              application that uses all of the encryption, \
#              authentication, and certification features of the OpenSSL \
#              library to securely tunnel IP networks over a single UDP \
#              port.
### END INIT INFO


# Contributed to the OpenVPN project by
# Douglas Keller <doug@voidstar.dyndns.org>
# 2002.05.15

# To install:
#   copy this file to /etc/rc.d/init.d/openvpn
#   shell> chkconfig --add openvpn
#   shell> mkdir /etc/openvpn
#   make .conf or .sh files in /etc/openvpn (see below)

# To uninstall:
#   run: chkconfig --del openvpn

# Author's Notes:
#
# I have created an /etc/init.d init script and enhanced openvpn.spec to
# automatically register the init script.  Once the RPM is installed you
# can start and stop OpenVPN with "service openvpn start" and "service
# openvpn stop".
#
# The init script does the following:
#
# - Starts an openvpn process for each .conf file it finds in
#   /etc/openvpn.
#
# - If /etc/openvpn/xxx.sh exists for a xxx.conf file then it executes
#   it before starting openvpn (useful for doing openvpn --mktun...).
#
# - In addition to start/stop you can do:
#
#   service openvpn reload - SIGHUP
#   service openvpn reopen - SIGUSR1
#   service openvpn status - SIGUSR2
#
# Modifications:
#
# 2003.05.02
#   * Changed == to = for sh compliance (Bishop Clark).
#   * If condrestart|reload|reopen|status, check that we were
#     actually started (James Yonan).
#   * Added lock, piddir, and work variables (James Yonan).
#   * If start is attempted twice, without an intervening stop, or
#     if start is attempted when previous start was not properly
#     shut down, then kill any previously started processes, before
#     commencing new start operation (James Yonan).
#   * Do a better job of flagging errors on start, and properly
#     returning success or failure status to caller (James Yonan).
#
# 2005.04.04
#   * Added openvpn-startup and openvpn-shutdown script calls
#     (James Yonan).
#

# Location of openvpn binary
openvpn=""
openvpn_locations="/usr/sbin/openvpn /usr/local/sbin/openvpn"
for location in $openvpn_locations
do
  if [ -f "$location" ]
  then
    openvpn=$location
  fi
done

# Lockfile
lock="/var/lock/subsys/openvpn"

# PID directory
piddir="/var/run/openvpn"

# Our working directory
work=/etc/openvpn

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
if [ ${NETWORKING} = "no" ]
then
  echo "Networking is down"
  exit 0
fi

# Check that binary exists
if ! [ -f  $openvpn ] 
then
  echo "openvpn binary not found"
  exit 0
fi

# See how we were called.
case "$1" in
  start)
 echo -n $"Starting openvpn: "

 /sbin/modprobe tun >/dev/null 2>&1

 # From a security perspective, I think it makes
 # sense to remove this, and have users who need
 # it explictly enable in their --up scripts or
 # firewall setups.

 #echo 1 > /proc/sys/net/ipv4/ip_forward

 # Run startup script, if defined
 if [ -f $work/openvpn-startup ]; then
     $work/openvpn-startup
 fi

 if [ ! -d  $piddir ]; then
     mkdir $piddir
 fi

 if [ -f $lock ]; then
     # we were not shut down correctly
     for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
       if [ -s $pidf ]; then
  kill `cat $pidf` >/dev/null 2>&1
       fi
       rm -f $pidf
     done
     rm -f $lock
     sleep 2
 fi

 rm -f $piddir/*.pid
 cd $work

 # Start every .conf in $work and run .sh if exists
 errors=0
 successes=0
 for c in `/bin/ls *.conf 2>/dev/null`; do
     bn=${c%%.conf}
     if [ -f "$bn.sh" ]; then
  . ./$bn.sh
     fi
     rm -f $piddir/$bn.pid
            # Handle backward compatibility, see Red Hat Bugzilla ID #458594
            script_security=''
            if [ -z "$( grep '^[[:space:]]*script-security[[:space:]]' $c )" ]; then
                script_security="--script-security 2"
            fi
     $openvpn --daemon --writepid $piddir/$bn.pid --config $c --cd $work $script_security
     if [ $? = 0 ]; then
  successes=1
     else
  errors=1
     fi
 done

 if [ $errors = 1 ]; then
     failure; echo
 else
     success; echo
 fi

 if [ $successes = 1 ]; then
     touch $lock
 fi
 ;;
  stop)
 echo -n $"Shutting down openvpn: "
 for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
   if [ -s $pidf ]; then
     kill `cat $pidf` >/dev/null 2>&1
   fi
   rm -f $pidf
 done

 # Run shutdown script, if defined
 if [ -f $work/openvpn-shutdown ]; then
     $work/openvpn-shutdown
 fi

 success; echo
 rm -f $lock
 ;;
  restart)
 $0 stop
 sleep 2
 $0 start
 ;;
  reload)
 if [ -f $lock ]; then
     for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
  if [ -s $pidf ]; then
      kill -HUP `cat $pidf` >/dev/null 2>&1
  fi
     done
 else
     echo "openvpn: service not started"
     exit 1
 fi
 ;;
  reopen)
 if [ -f $lock ]; then
     for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
  if [ -s $pidf ]; then
      kill -USR1 `cat $pidf` >/dev/null 2>&1
  fi
     done
 else
     echo "openvpn: service not started"
     exit 1
 fi
 ;;
  condrestart)
 if [ -f $lock ]; then
     $0 stop
     # avoid race
     sleep 2
     $0 start
 fi
 ;;
  status)
 if [ -f $lock ]; then
     for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
  if [ -s $pidf ]; then
      kill -USR2 `cat $pidf` >/dev/null 2>&1
  fi
     done
     echo "Status written to /var/log/messages"
 else
     echo "openvpn: service not started"
     exit 1
 fi
        ;;
  *)
 echo "Usage: openvpn {start|stop|restart|condrestart|reload|reopen|status}"
 exit 1
 ;;
esac
exit 0

Para instalar:
- Copiar este arquivo para /etc/init.d/openvpn
- Setar a configuração deste arquivo como executavel (chmod +x)
- Criar o serviço (chkconfig --add openvpn)
- Os arquivos de configuração devem estar em /etc/openvpn


terça-feira, 3 de julho de 2012

Habilitar SSH no Ubuntu

Para habilitar o acesso SSH ao Ubuntu (10.04 LTS) deve-se instalar o pacote OpenSSH

sudo apt-get install openssh-server

Após instalado o serviço, pode-se controlar o start / stop a partir do comando service ou ainda a partir do próprio script de do ssh

sudo service ssh start | stop | restart
sudo /etc/init.d/ssh start | stop |restart

O arquivo de configuração do SSH fica em:

/etc/ssh/sshd_config