jueves, 29 de abril de 2010

Open Chorizo - Un automatizador de tareas para servidores

Quiza el programita más chorra...
Cuando nos encontram
os con tareas repetitivas que hay que hacer en por ejemplo 200 servidores como añadir un nuevo disco de red, hacerlo manualmente es duro duro. Para ello mi siguiente script.

Para que sea automatico del todo hay que tener la clave pública ssh en los servidores de destino.



Mediante una lista de servidores como esta
:

servidor1
servidor2
servidor3
...
servidorN

y una lista de tareas como
ls -l
echo Hola
...
Va ejecutar cada comando en cada servidor, por ssh, mostrando por pantalla los resultados de cada comando.

Asi de simple.











/usr/bin/python
#
# 28/04/2010 by Ferran Serafini
import os
import sys
import getopt


list_servers=[]
list_tasks=[]

#-------------------------------------------------------------------------------
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
#-------------------------------------------------------------------------------
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
#-------------------------------------------------------------------------------
def req_servers():
print "Lo que voy a ejecutar"
print
print bcolors.OKGREEN + "--------------------------" + bcolors.ENDC
print bcolors.OKGREEN + "Lista servidores" + bcolors.ENDC
print bcolors.OKGREEN + "--------------------------" + bcolors.ENDC
#-------------------------------------------------------------------------------
def req_commands():
print bcolors.OKGREEN + "--------------------------" + bcolors.ENDC
print
print bcolors.OKBLUE + "--------------------------" + bcolors.ENDC
print bcolors.OKBLUE + "Lista Comandos" + bcolors.ENDC
print bcolors.OKBLUE + "--------------------------" + bcolors.ENDC
#-------------------------------------------------------------------------------
def hello():
print "Open Chorizo. 0.1 stable"
print "---------------------------------------------------"
print "Executa una llista de tasques en els equips remots que hi hagin en una llista"
print "[EXEMPLE] chorizo -s llista_servers.txt -t llista_tasques.txt"
#-------------------------------------------------------------------------------
def usage():
print "Usage: " + sys.argv[0] + " [ -h | --help ] [ -s | --servers ] [ -t | --tasques ] "
#-------------------------------------------------------------------------------
def check_file(f):
return os.path.isfile(f)
#-------------------------------------------------------------------------------
def file_read(f):
llista=[]
if check_file(f) == True:
f_read=open(f,"r")
for line in f_read:
line_r=str.split(line,"\n")
llista.append(line_r)
f_read.close
return llista
else:
print "Chorizo no trova el fitxer!: "+ f
#-------------------------------------------------------------------------------
def execute_chorix():
for server in list_servers:
counter=1
print bcolors.OKGREEN + "--------------------------" + bcolors.ENDC
print ">>: Executant en: "+ bcolors.OKGREEN + server[0] + bcolors.ENDC
print bcolors.OKGREEN + "--------------------------" + bcolors.ENDC
for command in list_tasks:
print "(" + str(counter) + "/" + str(len(list_tasks)) + ") " + bcolors.OKGREEN + "#" + server[0] + bcolors.OKBLUE + " >>>> " + command[0] + bcolors.ENDC
c="ssh root@" + server[0] + " -C '" + command[0] + "'"
com=os.popen(c).read()
counter=counter+1
print com
#print bcolors.OKBLUE + "--------------------------" + bcolors.ENDC
return com
#-------------------------------------------------------------------------------
try:
optlist, args = getopt.getopt(sys.argv[1:], 't:s:h' , ["tasques","servers","help"])
except getopt.GetoptError, err:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)

for k,v in optlist:
if k in ('-h','--help'):
hello()
sys.exit(0)
elif k in ('-s','--servers'):
list_servers=file_read(str(v)) #print list_servers
elif k in ('-t','--tasques'):
list_tasks=file_read(str(v)) #print list_tasks
req_servers()
for server in list_servers:
print ">> | " + server[0]
req_commands()
for command in list_tasks:
print "<< | " + command[0] print bcolors.OKBLUE + "--------------------------" + bcolors.ENDC print print bcolors.WARNING + "Tot Ok? [s/n]" + bcolors.ENDC go=raw_input("> ")
if go=="s":
output = execute_chorix()
else:
print "no s'ha executat res"


Despotify - Spotify para GNU/Linux

Si tienes una subscripción "premium" a spotify tienes a tu disposición este cliente ncurses para escuchar música sin necesidad de wine para el cliente oficial de spotify.



apt-get install subversion
svn co https://despotify.svn.sourceforge.net/svnroot/despotify despotify

cd despotify/src
apt-get install libncurses-dev libssl-dev zlib1g-dev libvorbis-dev libexpat1-dev libpulse-dev libgstreamer-plugins-base0.10-0 libgstreamer0.10-dev make libncursesw5-dbg libncursesw5-dev libao-dev libao-dbg libao2

make

make install

Para más info: http://www.emezeta.com/articulos/despotify-cliente-spotify-nativo-para-linux

jueves, 22 de abril de 2010

NAGIOS - Monitor EPO

Desde la consola del EPO se puede configurar un report diario de las actualizaciones de las firmas en formato csv. El siguiente script en Python (mi primer script en este lenguaje) interpeta la cantidad de servidores actualizados y desactualizados para monitorizarse en Nagios. 


#!/usr/bin/python
#
# 26/04/2010
import os
import sys
import getopt

STATE=0
STATE_WARNING=1
STATE_OK=0
ARRAY_VERSIONS=[]
ARRAY_NOMS=[]
OLD_MACHINE=[]
OLD_MACHINE_noms=[]
FITXER_CSV="/home/ferran/av_version.csv"
MAX_VERSION=0
i=0

def hello():
print "Script per comprovar l'estat de les EPO de Mcafee."
print "---------------------------------------------------"
print "Principalment analitza el fitxer definit en FITXER_CSV com a punt de montatge cifs (veure fstab). Aquest fitxer es un csv generat de forma automatica on conte diferents dades relatives a la versio de Mcafee (signatures, versio del s.o, etc). Aqui es comprova la versio maxima trobada i la compara amb cada versio de cada client. Si en troba un desactualitzat el sys tornara Warning"

#Verifiquem que el FITXER csv EXISTEIX
#-------------------------------------------------------------------------------
def check_csv_file():
return os.path.isfile(FITXER_CSV)
#-------------------------------------------------------------------------------
def usage():
print "Usage: " + sys.argv[0] + " [ -h | --help ] "
#-------------------------------------------------------------------------------
#Llegim linia a linia el fitxer i afegim la versio de cada linia a ARRAY_VERSIONS.append(versio) i cada nom del server a ARRAY_NOMS.append(nom)
def llegir_linia(FITXER, i,STATE):
for linia in FITXER: #Busquem en les maquines UOC-
if "UOC-" in linia:
UOCSERVER=str.split(linia,",")
versio=UOCSERVER[14]
nom=UOCSERVER[0]
ARRAY_VERSIONS.append(versio)
ARRAY_NOMS.append(nom) # print ARRAY_VERSIONS
while i < len(ARRAY_VERSIONS):
if ARRAY_VERSIONS[i] < max(ARRAY_VERSIONS): #Warning: hi ha equips desactualitzats,busquem quins a partir de la version mes alta numericament"
OLD_MACHINE.append(ARRAY_VERSIONS[i]) # print OLD_MACHINE
OLD_MACHINE_noms.append(ARRAY_NOMS[i]) # print OLD_MACHINE_noms
STATE=STATE_WARNING=1 # print STATE
i=i+1
else:
i=i+1
FITXER.close
return STATE
#-------------------------------------------------------------------------------
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h' , ["help"])
except getopt.GetoptError, err:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)

for k,v in optlist:
if k in ('-h','--help'):
hello()
sys.exit(0)

if check_csv_file() == True:
STATE=llegir_linia(open(FITXER_CSV,"r"),i,STATE)
if STATE == 1:
# print "Warning: hi ha equips "+ str(len(OLD_MACHINE_noms))+ " desactualitzats," + str(OLD_MACHINE_noms) + str(OLD_MACHINE)
print "WARNING: "+ str(len(OLD_MACHINE_noms))+ " equips desactualitzats, " + " | " .join(str(item)for item in OLD_MACHINE_noms) +" | " + " - " .join(str(item)for item in OLD_MACHINE)
sys.exit(STATE_WARNING)
else:
print "OK: tots els equips actualitzats"
sys.exit(STATE_OK)
else:
print "WARNING: No es pot llegir el FITXER: " + FITXER_CSV
sys.exit(1)



MySQL: Lost connection to MySQL server at 'reading initial communication packet'

En FreeBSD /etc/hosts.allow
mysqld: ALL: allow 

En non-FreeBSD Unix /etc/hosts.allow
mysqld: ALL

Vigilar también que no esté en /etc/hosts.deny

http://www.bramschoenmakers.nl/en/node/595

miércoles, 21 de abril de 2010

SOLARIS - ps -aux equivalente de GNU/Linux

El equivalente del ps -aux de GNU/Linux en Solaris seria:

ps -elf

O tambien

/usr/ucb/ps -aux

lunes, 19 de abril de 2010

Oracle RAC O2CB Cluster Service

Oracle RAC O2CB Cluster Service

Before we can do anything with OCFS2 like formatting or mounting the file system, we need to first have OCFS2's cluster stack, O2CB, running (which it will be as a result of the configuration process performed above). The stack includes the following services:

  • NM: Node Manager that keep track of all the nodes in the cluster.conf
  • HB: Heart beat service that issues up/down notifications when nodes join or leave the cluster
  • TCP: Handles communication between the nodes
  • DLM: Distributed lock manager that keeps track of all locks, its owners and status
  • CONFIGFS: User space driven configuration file system mounted at /config
  • DLMFS: User space interface to the kernel space DLM

All of the above cluster services have been packaged in the o2cb system service (/etc/init.d/o2cb). Here is a short listing of some of the more useful commands and options for the o2cb system service.

  • /etc/init.d/o2cb status
    Module "configfs": Not loaded
    Filesystem "configfs": Not mounted
    Module "ocfs2_nodemanager": Not loaded
    Module "ocfs2_dlm": Not loaded
    Module "ocfs2_dlmfs": Not loaded
    Filesystem "ocfs2_dlmfs": Not mounted
    Note that with this example, all of the services are not loaded. I did an "unload" right before executing the "status" option. If you were to check the status of the o2cb service immediately after configuring OCFS using ocfs2console utility, they would all be loaded

  • /etc/init.d/o2cb load
    Loading module "configfs": OK
    Mounting configfs filesystem at /config: OK
    Loading module "ocfs2_nodemanager": OK
    Loading module "ocfs2_dlm": OK
    Loading module "ocfs2_dlmfs": OK
    Mounting ocfs2_dlmfs filesystem at /dlm: OK
    Loads all OCFS modules.

  • /etc/init.d/o2cb online ocfs2
    Starting cluster ocfs2: OK
    The above command will online the cluster we created, ocfs2.

  • /etc/init.d/o2cb offline ocfs2
    Unmounting ocfs2_dlmfs filesystem: OK
    Unloading module "ocfs2_dlmfs": OK
    Unmounting configfs filesystem: OK
    Unloading module "configfs": OK
    The above command will offline the cluster we created, ocfs2.

  • /etc/init.d/o2cb unload
    Cleaning heartbeat on ocfs2: OK
    Stopping cluster ocfs2: OK
http://www.debian-administration.org/articles/578

miércoles, 14 de abril de 2010

Cluster o2cb - ERROR: Wrong stack

/usr/lib/ocf/resource.d/ocfs/o2cb monitor
ERROR: Wrong stack

Ojo el o2cb
init script esta ejecutandose.
Parar y borrar del inicio

lunes, 12 de abril de 2010

Instalación Oracle10g en Ubuntu

Añadir el siguiente repositorio:deb http://oss.oracle.com/debian unstable main non-free
Añadir su clave GPG

wget http://oss.oracle.com/el4/RPM-GPG-KEY-oracle -O- | sudo apt-key add -
apt-get updateapt-get install oracle-xe
/etc/init.d/oracle-xe configure


Añadirmos en el bashrc
ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
PATH=$PATH:$ORACLE_HOME/bin
export ORACLE_HOME
export ORACLE_SID=XE

sqlplus sys as sysdba


GNU/Linux - Añadir nuevo fichero swap

Por ejemplo de 64 MB
dd if=/dev/zero of=/swapfile bs=1024 count=65536
mkswap /swapfile
swapon /swapfile

en /etc/fstab
/swapfile swap swap defaults 0 0
cat /proc/swaps


viernes, 9 de abril de 2010

NAGIOS - Documentación Extra con serviceextinfo y hostextinfo

Una de las posibilidades que tiene nagios para documentar cada host, servicio, etc es enlazar cada check con una documentación detallada de cada host/servicio, un howto solucionar esa incidencia, etc. Para ello hay que poner en la definición extendida del servicio donde el campo notes_url tendra el valor la URL donde queremos que enlace este servicio, por ejemplo una entrada de un plone o cualquier otro CMS.


define service{
        use                             generic-service
        host_name                       serveis_wiki
        service_description             wiki
        is_volatile                     0
        check_period                    24x7
        max_check_attempts              3
        normal_check_interval           5
        retry_check_interval            1
        contact_groups                  admins
        notification_interval           120
        notification_period             24x7
        notification_options            w,u,c,r
        check_command                   check_http_url_"/webapps/wiki/check.action"!80!"OK"!web.dom.com
       }

define serviceextinfo{
        host_name               serveis_wiki
        service_description     wiki
        notes_url               http://mycms/docs/servicio1/
       }

jueves, 8 de abril de 2010

POSTFIX - Cola de correo muy llena

Una buena manera de acelerar el proceso es hacer un flush donde se entreguen primero los correos más pequeños.

postqueue -p | awk '{print $2}' | sort -n | xargs postsuper -r ; postsuper -f