Instalar y configurar cliente y servidor de hora NTP en CentOS 5

Hoy en día resulta muy importante tener nuestros equipos con la hora adecuada, tanto para saber a que hora suceden eventos, así como para simplemente enviar y/o recibir correo de forma adecuada.

Si se trata de un entorno laboral/empresarial esta actividad pasa a ser una norma, pues de esta forma estaremos seguros de los registros generados en los sitemas y de esta forma realizaremos seguimiento de forma acertada utilizando los registros del sistema.

Puede hallar una definición formal del protocolo NTP en: wikipedia

Instalamos y configuramos la parte cliente de NTP

Para cambiar la zona horaria en sistemas operativos basados en CentOS 5.4 es necesario validar que se encuentra instalado el paquete que nos permitirá establecer la zona horaria en la que nos encontramos, con el comando:

# yum list tzadata.noarch

Y la salida debería ser:

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* addons: mirrors.tummy.com
* base: mirrors.igsobe.com
* extras: centos.corenetworks.net
* updates: mirror.raystedman.net
Installed Packages
tzdata.noarch        2009k-1.el5           installed
tzdata.noarch        2009u-1.el5           installed

En caso que no esté instalado, proceda a instalarlo con el comando:

# yum install tzdata.noarch

Y luego proceda a configurar la zona horaria con el comando:

tzselect

Responde al asistente escogiendo tu zona horaria por ejemplo: América y luego Caracas.

Ahora bien, para crear un servidor NTP como un cliente de otro servidor NTP para que la hora se actualice automáticamente de forma periódica el procedimiento es el siguiente:

* Instalar el programa ntpdate

# yum install ntp.i386

* Agregas una tarea programada para que actualice la hora cada 4 horas:

# crontab -e

* Dentro de la edición del crontab agregas la siguiente línea:

0 */4 * * * /usr/sbin/ntpdate -u 2.pool.ntp.org

Instalamos y configuramos la parte servidor de NTP

* Se debe instalar el paquete ntpdate como fue indicado anteriormente

* Modificar archivo de configuración /etc/ntp.conf con los siguientes valores:

# Permit time synchronization with our time source, but do not
# permit the source to query or modify the service on this system.
restrict default kod nomodify notrap nopeer noquery
#restrict -6 default kod nomodify notrap nopeer noquery

# Permit all access over the loopback interface.  This could
# be tightened as well, but to do so would effect some of
# the administrative functions.
restrict 127.0.0.1
#restrict -6 ::1

# Hosts on local network are less restricted.
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
server 0.centos.pool.ntp.org
server 1.centos.pool.ntp.org
server 2.centos.pool.ntp.org

#broadcast 192.168.1.255 key 42         # broadcast server
#broadcastclient                        # broadcast client
#broadcast 224.0.1.1 key 42             # multicast server
#multicastclient 224.0.1.1              # multicast client
#manycastserver 239.255.254.254         # manycast server
#manycastclient 239.255.254.254 key 42  # manycast client

# Undisciplined Local Clock. This is a fake driver intended for backup
# and when no outside source of synchronized time is available.
server  127.127.1.0     # local clock
fudge   127.127.1.0 stratum 10

# Drift file.  Put this in a directory which the daemon can write to.
# No symbolic links allowed, either, since the daemon updates the file
# by creating a temporary in the same directory and then rename()'ing
# it to the file.
driftfile /var/lib/ntp/drift

# Key file containing the keys and key identifiers used when operating
# with symmetric key cryptography.
keys /etc/ntp/keys

# Specify the key identifiers which are trusted.
#trustedkey 4 8 42

# Specify the key identifier to use with the ntpdc utility.
#requestkey 8

# Specify the key identifier to use with the ntpq utility.
#controlkey 8

# Permisos que se asignara para cada servidor de tiempo.
# En los ejemplos, no se permite a las fuente consultar, ni
# modificar el servicio en el sistema ni enviar mensaje de
# registro.
restrict 0.centos.pool.ntp.org mask 255.255.255.255 nomodify notrap noquery
restrict 1.centos.pool.ntp.org mask 255.255.255.255 nomodify notrap noquery
restrict 2.centos.pool.ntp.org mask 255.255.255.255 nomodify notrap noquery

# Se Activa la difusion hacia los clientes
broadcastclient

* Iniciar el servicio con:

# service ntpd start

* Agregar el servicio para que se inicie de forma automática con el sistema:

# chkconfig ntpd on

* Finalmente permitir al firewall recibir solicitudes de ntp de nuestros clientes agregando al archivo: /etc/sysconfig/iptables la siguiente línea:

-A RH-Firewall-1-INPUT -s 192.168.1.0/24 -m state --state NEW -p udp --dport 123 -j ACCEPT

Antes de la línea:

-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited

* Reiniciamos el firewall:

# service iptables restart

Y listoooooooooo ya tenemos nuestro propio cliente y servidor de hora NTP ¡¡¡¡¡
Si teneis alguna duda, comentarla¡¡¡

.bash_profile para Sysadmins con servidores Plesk

Aqui os dejo este .bash_profile útil para sysadmins que administren servidores con Plesk.

Si quereis comentar que alias teneis en vuestro bash_profile es de agredecer, un saludo¡¡¡

Para usarlo copiar y pegar dentro del archivo .bash_profile

alias bye=»exit»
alias ns=»netstat -lpn»
alias pmysql=»cd /var/lib/mysql»
alias phttpd=»cd /var/www/vhosts»
alias tailall=»tail -f /var/www/vhosts/*/statistics/logs/error_log /var/www/vhosts/*/statistics/logs/access_log»
alias tailallerror=»tail -f /var/www/vhosts/*/statistics/logs/error_log»
alias tailallaccess=»tail -f /var/www/vhosts/*/statistics/logs/access_log»
alias maillog=»tail -f /usr/local/psa/var/log/maillog»
alias myadmin=»mysql -u admin -p`cat /etc/psa/.psa.shadow`»
alias mchk=»/usr/local/psa/admin/sbin/mchk –with-spam»
alias webpsa=»/usr/local/psa/admin/sbin/websrvmng -av»
alias ppass=»cat /etc/psa/.psa.shadow;»
alias que=»/var/qmail/bin/qmail-qstat»

echo «############################################################»
echo » Shortcuts to your system »
echo «############################################################»
echo
echo «To see your Plesk password, type: ppass»
echo
echo «To rebuild your Apache/Web Server configuration, type: webpsa»
echo
echo «To rebuild your Qmail/Mail Server configuration, type: mchk»
echo
echo «To see your Qmail/Mail Server queue, type: que»
echo
echo «To connect to your MySQL server as admin, type: myadmin»
echo
echo «To exit from shell, type: exit»
echo
echo «To see netstat command, type: ns»
echo
echo «To see all error/access log, type: tailall»
echo
echo «To see all error log, type: tailallerror»
echo
echo «To see email log, type: maillog»
echo
echo «To see all access log, type: tailallaccess»
echo
echo «To get rid of these messages/aliases, edit your /root/.bash_profile»
echo

Error en Plesk: Espacio insuficiente en /migration del servidor fuente de la migración

Vaya tela…. este error persiste y persiste en las versiones de Plesk …

Síntomas
La migración de un dominio Parallels Plesk Panel finaliza sin ningún error. De todas formas, el dominio no presenta ningún archivo html.

Causa

La causa de este problema es una cantidad de espacio de disco insuficiente en el directorio /migration del servidor fuente.

El Administrador de Migraciones de Parallels Plesk Panel carga el Agente de Migración al servidor fuente. El Agente de Migración es un script perl que realiza el volcado de los datos, usando /migration en el servidor fuente como directorio temporal para la migración. Si el directorio /migration ya no dispone de más espacio o se encuentra en una partición de tamaño limitado, los datos no se volcan debido a esta insuficiencia de espacio de disco.

Puede comprobar el tamaño de la partición ejecutando el comando «df -h». Por ejemplo:

~# df -h

Filesystem Size Used Avail Use% Mounted on

/dev/sda1 950M 254M 649M 29% / <- la partición es demasiado pequeña

/dev/sda2 4.7G 1.6G 3.1G 35% /usr

/dev/sda3 100G 60G 41G 60% /var

/dev/sda4 4.7G 5.5M 4.7G 1% /home

~#

La partición “/” donde se encuentra el directorio /migration es demasiado pequeña. Tar no puede volcar los datos debido a la insuficiencia de espacio de disco.

Resolución

Le recomendamos liberar el directorio /migration en el servidor fuente. También puede transferir el directorio a una partición de mayor capacidad.

Por ejemplo, creemos el directorio de migración en otra partición que tenga espacio suficiente:

source~# mkdir /home/migration

Entonces creeamos un vínculo simbólico:

source~# rm -rf /migration

source~# ln -s /home/migration/ /migration

Y yasta amigos a migrar dominios a saco de servidor a servidor….

Script para optimizar las tablas fragmentadas en MySQL

Bueno otro buen script a la huchaca… esta escrito en bash aparte de ser utilisisimo porque chequea las tablas fragmentadas y tambien chequea todas las bbdds en busca de tablas MyISAM o INNODB y las optimiza.

#!/bin/bash

VERSION="0.7.2"
log="$PWD/mysql_error_log.txt"

echo "MySQL fragmentation finder (and fixer) v$VERSION, written by Phil Dufault ( http://www.dufault.info/ )"

showHelp() {
echo -e "\tThis script only repairs MyISAM and InnoDB tables"
echo -e "\t--help or -h\t\tthis menu"
echo -e "\t--user username\tspecify mysql username to use\n\t\t\tusing this flag means the script will ask for a password during runtime, unless you supply..."
echo -e "\t--password \"yourpassword\""
echo -e "\t--host hostname\tspecify mysql hostname to use, be it local (default) or remote"
}

#s parse arguments
while [[ $1 == -* ]]; do
case "$1" in
--help|-h) showHelp; exit 0;;
--user) mysqlUser="$2"; shift 2;;
--password) mysqlPass="$2"; shift 2;;
--host) mysqlHost="$2"; shift 2;;
--) shift; break;;
esac
done

# prevent overwriting the commandline args with the ones in .my.cnf, and check that .my.cnf exists
if [[ ! $mysqlUser && -f "$HOME/.my.cnf" ]]; then
if grep "user=" "$HOME/.my.cnf" >/dev/null 2>&1; then
if grep "pass=" "$HOME/.my.cnf" >/dev/null 2>&1; then
mysqlUser=$(grep user= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); mysqlPass=$(grep pass= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); if grep "host=" "$HOME/.my.cnf" >/dev/null 2>&1; then
mysqlHost=$(grep host= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); fi else echo "Found no pass line in your .my.cnf,, fix this or specify with --password" fi else echo "Found no user line in your .my.cnf, fix this or specify with --user" exit 1; fi fi # set localhost if no host is set anywhere else if [[ ! $mysqlHost ]]; then mysqlHost="127.0.0.1" fi # error out if [[ ! $mysqlUser ]]; then echo "Authentication information not found as arguments, nor in $HOME/.my.cnf" echo showHelp exit 1 fi if [[ ! $mysqlPass ]]; then echo -n "Enter your MySQL password: " read -s mysqlPass fi # Test connecting to the database: mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "show status" >/dev/null 2>&1
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information.";
exit 1;
fi

# Retrieve the listing of databases:
databases=( $(mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "show databases;" 2>"$log") );
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi

echo -e "Found ${#databases[@]} databases";
for i in ${databases[@]}; do
# get a list of all of the tables, grep for MyISAM or InnoDB, and then sort out the fragmented tables with awk
fragmented=( $(mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "SHOW TABLE STATUS FROM $i;" 2>"$log" | awk '{print $1,$2,$10}' | egrep "MyISAM|InnoDB" | awk '$3 > 0' | awk '{print $1}') );
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi
tput sc
echo -n "Checking $i ... ";
if [[ ${#fragmented[@]} -gt 0 ]]; then
if [[ ${#fragmented[@]} -gt 0 ]]; then
if [[ ${#fragmented[@]} -gt 1 ]]; then
echo "found ${#fragmented[@]} fragmented tables."
else
echo "found ${#fragmented[@]} fragmented table."
fi
fi
for table in ${fragmented[@]}; do
let fraggedTables=$fraggedTables+1;
echo -ne "\tOptimizing $table ... ";
mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" -D "$i" --skip-column-names --batch -e "optimize table $table" 2>"$log" >/dev/null
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi
echo done
done
else
tput rc
tput el
fi
unset fragmented
done

# footer message
if [[ ! $fraggedTables -gt 0 ]]; then
echo "No tables were fragmented, so no optimizing was done.";
else
if [[ $fraggedTables -gt 1 ]]; then
echo "$fraggedTables tables were fragmented, and were optimized.";
else
echo "$fraggedTables table was fragmented, and was optimized.";
fi
fi

if [[ ! -s $log ]]; then
rm -f "$log"
fi

unset fraggedTables

Link | http://www.dufault.info/blog/a-script-to-optimize-fragmented-tables-in-mysql/