martes, diciembre 07, 2010

FreeBSD + PHP5

Requerimientos:

FreeBSD instalado
Apache instalado

Instalando

# whereis php5
php5: /usr/ports/lang/php5
# cd /usr/ports/lang/php5
# make config
Activar la opcion
[X] APACHE Build Apache module
[ OK ]
# make install clean

Configurando

# edit /usr/local/www/apache22/data/test.php

<?php
phpinfo();
?>

# cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini

# edit /usr/local/etc/apache22/httpd.conf

Desactivo las siguientes lineas:

#<IfModule dir_module>
#DirectoryIndex index.html
#</IfModule>

Agregamos las nuevas:

# Lineas agregadas para PHP inicio
<IfModule mod_php5.c>
DirectoryIndex default.php index.html index.php login.php
</IfModule>

<IfModule mod_php5.c>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
</IfModule>
# Lineas agregadas para PHP fin

# /usr/local/etc/rc.d/apache22 restart

http://serverip/test.php

FreeBSD + Apache

Requerimientos:

FreeBSD instalado

Instalando

# whereis apache22
apache22: /usr/ports/www/apache22
# cd /usr/ports/www/apache22
# make config
# make install clean

Configurando
# edit /usr/local/etc/apache22/httpd.conf

Verificar una configuracion en httpd.conf
# /usr/local/etc/rc.d/apache22 configtest

Hacer que Apache se inicie con el sistema
# echo 'apache22_enable="YES"' >> /etc/rc.conf

Iniciar apache
# /usr/local/etc/rc.d/apache22 start

Aplicando los cambios luego de modificar algo en httpd.conf
# apachectl graceful

sábado, octubre 23, 2010

FreeBSD Updating and Upgrading

FreeBSD Updating and Upgrading
Requerimientos:

FreeBSD instalado
Conexion a Internet

Ahora vamos sincronizar y/o actualizar las fuentes de FreeBSD (Kernel + World) con csup

Chapter 24 Updating and Upgrading FreeBSD
http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/updating-upgrading.html

---------------------------------------

24.4.3 Updating the Documentation Sources
# csup -h cvsup15.us.FreeBSD.org -g -L 2 /usr/share/examples/cvsup/doc-supfile

---------------------------------------

24.6 Synchronizing Your Source
A.6 Using CVSup
Note: The csup utility is a rewrite of the CVSup...
...if you are using FreeBSD 6.2 or later, you can use it out-of-the-box, since it is included in the base system.
# csup -h cvsup15.us.FreeBSD.org -g -L 2 /usr/share/examples/cvsup/standard-supfile <-(VIEW THE TIP)
---
TIP :
# cp /usr/share/examples/cvsup/standard-supfile /root
# edit /root/standard-supfile
Change the lines
*default host=CHANGE_THIS.FreeBSD.org
*default release=cvs tag=RELENG_7_1
for
*default host=cvsup15.us.FreeBSD.org
*default release=cvs tag=RELENG_8_1

Exit from editor and save changes (en edit, con "Esc" main menu, "a" leave editor, "a" save changes)

Note :
for FreeBSD 8.1 RELEASE use tag=RELENG_8_1, for FreeBSD 8.2 use tag=RELENG_8_2
http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/cvs-tags.html
http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/cvsup.html#CVSUP-MIRRORS

# csup -g -L 2 /root/standard-supfile
---

---------------------------------------

24.7 Rebuilding “world”

These concerns have led to the following recommended sequence. Note that the detailed sequence for particular updates may require additional steps, but this core process should remain unchanged for some time:

# cd /usr/src (hay que estar dentro de este directorio para el siguiente comando)

1. make buildworld
This first compiles the new compiler and a few related tools, then uses the new compiler to compile the rest of the new world. The result ends up in /usr/obj.

2. make buildkernel <-(VIEW THE TIP)
Unlike the older approach, using config(8) and make(1), this uses the new compiler residing in /usr/obj. This protects you against compiler-kernel mismatches.

3. make installkernel <-(VIEW THE TIP)
Place the new kernel and kernel modules onto the disk, making it possible to boot with the newly updated kernel.
---
TIP: Storing your kernel configuration file directly under /usr/src can be a bad idea. If you are experiencing problems it can be tempting to just delete /usr/src and start again. After doing this, it usually only takes a few seconds for you to realize that you have deleted your custom kernel configuration file. Also, do not edit GENERIC directly, as it may get overwritten the next time you update your source tree, and your kernel modifications will be lost.

You might want to keep your kernel configuration file elsewhere, and then create a symbolic link to the file in the i386 directory.

For example:
# cd /usr/src/sys/i386/conf
# mkdir /root/kernels
# cp GENERIC /root/kernels/MYKERNEL
# ln -s /root/kernels/MYKERNEL

8.6 The Configuration File
Now, edit MYKERNEL with your favorite text editor.
# edit MYKERNEL
Change the line:
ident GENERIC
for
ident MYKERNEL

Save an exit for editor (en edit, con "Esc" se abre el menu, "a" salir del editor, "a" guardar cambios)
8.5 Building and Installing a Custom Kernel
Building a Kernel
1. Change to the /usr/src directory:
# cd /usr/src
2. Compile the kernel:
# make buildkernel KERNCONF=MYKERNEL
3. Install the new kernel:
# make installkernel KERNCONF=MYKERNEL
---

4. Reboot into single user mode <-(VIEW THE TIP)
Single user mode minimizes problems from updating software that's already running. It also minimizes any problems from running the old world on a new kernel.
---

TIP:
24.7.5 Drop to Single User Mode

As the superuser, you can execute:

# shutdown now

from a running system, which will drop it to single user mode.

Alternatively, reboot the system, and at the boot prompt, select the “single user” option. The system will then boot single user. At the shell prompt you should then run:

# fsck -p
# mount -u /
# mount -a -t ufs
# swapon -a
---

5. mergemaster -p <-(VIEW THE NOTE)
This does some initial configuration file updates in preparation for the new world. For instance it may add new user groups to the system, or new user names to the password database. This is often necessary when new groups or special system-user accounts have been added since the last update, so that the installworld step will be able to use the newly installed system user or system group names without problems.
---
NOTE:
http://www.understudy.net/makeworld.html#mergemaster1

*** The directory specified for the temporary root environment,
/var/tmp/temproot, exists. This can be a security risk if untrusted users have access to the system.

Use 'd' to delete the old /var/tmp/temproot and continue
Use 't' to select a new temporary root directory
Use 'e' to exit mergemaster

Default is to use /var/tmp/temproot as is

How should I deal with this? [Use the existing /var/tmp/temproot]

Press Enter ( which means use /var/tmp/temproot ) and you should be good to go. This will keep the temporary root environment in /var/tmp/temproot. It will now start to compare a large number of files. And show you the differences between them.

Now it is going to start going through your /etc/ directory and /dev/MAKEDEV file .This is the beginning of the hellish part of Make World. Some notes on what you will see here. Mergemaster brings up the current file on the hard drive and the new version.If they are the same it smiles and moves on. If they are different it will point out the differences. It brings up what is different between the files and shows you just the things that are different in the file. It may not need to bring up everything in the file. The symbols used in Mergemaster:

--- 3 minus symbols in a row usually pertaining to the date of the file installation. I have only seen them at the top of a file that is to be changed. It means the line next to them really has to be removed.

+++ 3 plus symbols in a row usually pertaining to the date of the file installation. I have only seen them at the top of a file that is to be changed. It means the line next to them really has to be added (replace the existing line).

@@ means the line numbers that will be affected by the change. @@ -1,5 +1,24 @@ means line 1 and the next 4 lines will become line 1 and the next 24 lines. Look at the next symbols to understand.
+ means the line that will be added.

- means the line that will be replaced/ removed

. The mergemaster then brings up this dialogue.

Use 'd' to delete the temporary .name of file
Use 'i' to install the temporary .name of file
Use 'm' to merge the temporary and installed versions or parts of them.
Use 'v' to view the diff results again

Default is to leave the temporary file to deal with by hand

How should I deal with this? [Leave it for later]

'd' will remove any new lines for the file leaving it the way it was. No changes.
'i' will install all of the new lines and remove all of the old lines.
'm' will place both old and /or new lines in the file.
'v' lets you look at it again.

Use 'i' if you want to upgrade. Use 'd' if you don't. Use 'm' if you want to screw with things. And do it without the quotes.

Okay important notes here. If you have custom files in the /etc/ directory And you just click through this without checking. I can assure you they will be gone when your trip to Make World is done. and you will not have had a good time on the rides.You did remember to backup didn't you?
So how do I know what to upgrade and what to not upgrade? And what to merge?

My rules of thumb on this is:

The 'd' is for files that I have customized. Files I don't want changes in. Files like ppp.conf.
---

*** Comparison complete
Do you wish to delete what is left of /var/tmp/temproot? [no] (dar enter)


# cd /usr/src (hay que estar dentro de este directorio para el siguiente comando)

6. make installworld
Copies the world from /usr/obj. You now have a new kernel and new world on disk.

7. mergemaster
Now you can update the remaining configuration files, since you have a new world on disk.
---
Default is to use /var/tmp/temproot as is

How should I deal with this? [Use the existing /var/tmp/temproot] (dar enter)

The presence of stale files in this directory can cause the
dreaded unpredictable results, and therefore it is highly
recommended that you delete them.

*** Delete them now? [n] yes (poner 'yes' y dar enter)

Default is to leave the temporary file to deal with by hand

How should I deal with this? [Leave it for later] ( si es un archivo que hemos modificado como ppp.conf doy 'd', pero si me sirve el nuevo poner 'i' y dar enter)

Do you wish to delete what is left of /var/tmp/temproot? [no] yes (poner yes y dar enter)
---

8. reboot
A full machine reboot is needed now to load the new kernel and new world with new configuration files.

---------------------------------------

Para verificar que version de kernel tenemos, usamos el comando:
# uname -a
FreeBSD pruebas.alpha.telemedellin.tv 8.1-RELEASE-p1 FreeBSD 8.1-RELEASE-p1 #0: Thu Oct 21 07:44:33 COT 2010 angel@pruebas.alpha.telemedellin.tv:/usr/obj/usr/src/sys/MYKERNEL i386

Si hemos actualizado la version de FreeBSD modificando el RELENG_X_Y puede que tengamos que recompilar e instalar todos los ports que tengamos actualmente instalados, para hacer esto ejecutamos
# portupgrade -af

Si quisieramos desistalar todos los ports que tengamos en un solo comando, puedemos ejecutar
# cd /var/db/pkg
# pkg_delete *

---------------------------------------

Si algo sale mal y el nuevo kernel no funciona bien, puedo regresar al anterior
Al iniciar el equipo nos muestra el listado de opciones de inicio de FreeBSD

6. Escape to loader prompt
Type '?' for a list of commands, 'help' for more detailed help.
OK

(escribimos)
unload kernel (enter)
(escribimos)
boot /boot/kernel.old/kernel (enter)

Luego podemos renombrar el kernel problematico y renombrar el kernel anterior que funciona (kernel.old)
# mv /boot/kernel /boot/kernel.bad
# mv /boot/kernel.old /boot/kernel

---------------------------------------

Ahora vamos a actualizar el arbol de ports

# csup -h cvsup15.us.FreeBSD.org -g -L 2 /usr/share/examples/cvsup/ports-supfile <-(VIEW THE TIP)
---
TIP :
# cp /usr/share/examples/cvsup/ports-supfile /root
# edit /root/ ports-supfile
Change the lines
*default host=CHANGE_THIS.FreeBSD.org
for
*default host=cvsup15.us.FreeBSD.org

Exit from editor and save changes (en edit, con "Esc" main menu, "a" leave editor, "a" save changes)

# csup -h cvsup15.us.FreeBSD.org -g -L 2 /root/ports-supfile

Note :
http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/cvsup.html#CVSUP-MIRRORS
---

---------------------------------------

Ejemplo de como se usan los ports, aqui instalaremos portupgrade, es una utilidad para mantener actualizados los ports que se instalen luego y hasta portupgrade mismo.

Instalar nuestro primer port, portupgrade:
# whereis portupgrade
portupgrade: /usr/ports/ports-mgmt/portupgrade
# cd /usr/ports/ports-mgmt/portupgrade
# make install clean
Options for portupgrade 2.4.6_4,2
[X] BDB4 Use Berkeley DB >=2 as backend
[ OK ]

Suele pasar que luego de instalar algun port, al ejecutar el comando, nos muestre
Command not found.

Hay dos formas de hacer que permita usar el port:

Ejecutar el comando
# rehash

Tambien podemos simplemente salir de la sesion (exit), iniciar de nuevo sesion y ejecutar el comando de nuevo

Comandos basicos de portupgrade:
# pkg_version -v <- Imprime como estan las versiones
# portupgrade -a <- Actualiza los ports instalados
# portsclean -DD <- Limpia los ports viejos guardados en /usr/ports/distfiles

martes, julio 27, 2010

FreeBSD 8 + Migracion usuarios

Manuales:

http://forums.freebsd.org/showthread.php?t=5446
http://forums.freebsd.org/showthread.php?t=3292
http://www.afterschool.dk/documents/freebsd/freebsd-migrate-users/

Para migrar los usuarios de un equipo con FreeBSD a otro equipo con FreeBSD, se debe hacer backup a los siguientes archivos:

BACKUPS (en el servidor viejito)

Usuarios de FreeBSD
/etc/passwd
/etc/master.passwd
/etc/group

Documentos de los usuarios de FreeBSD
/usr/home
/var/mail

Usuarios de SAMBA de FreeBSD
/usr/local/etc/samba34/passdb.tdb
/usr/local/etc/samba34/secrets.tdb

Archivo con los parametros para compartir en SAMBA
/usr/local/etc/smb.conf

RESTAURACION (en el servidor nuevo)

Se instala FreeBSD
Se crea el usuario root y si lo deseamos para ssh creamos algun otro usuario.
Se instala SAMBA
Hacemos que SAMBA arranque con el sistema agregando en /etc/rc.conf las lineas:

# Activamos Samba
nmbd_enable="YES"
smbd_enable="YES"

Se reemplazan los archivos existentes con los del backups, que son los que tienen los datos importantes (usuarios, passwords y grupos)
Con "pwd_mkdb" se regeneran los passwords, con el siguiente comando:
# pwd_mkdb -p /etc/master.passwd

Si nuestro FreeBSD actua como file server, el contenido de
/usr/home
es donde ellos tienen su informacion importante y que debemos restaurar del backup

El directorio
/var/mail
guarda los e-mails de los usuarios del equipo, si nuestro FreeBSD actua como file server, no es importante restaurar esto.

Aqui les dejo un script para automatizar el proceso, pero cuidado que lo deben ajustar a su equipo y lo mas importante, deben activar o no el backup de /usr/home y /var/mail segun se desee (por defecto los dejo activo!)

Contenido del script INICIO

#! /bin/sh

# Manual
# http://forums.freebsd.org/showthread.php?t=5446
# http://forums.freebsd.org/showthread.php?t=3292

# http://www.afterschool.dk/documents/freebsd/freebsd-migrate-users/
#
# Move user entries from the following old files:
# /etc/passwd
# /etc/group
# /etc/master.passwd
#
# Then run the following command to rebuild the password database:
# pwd_mkdb -p /etc/master.passwd

# Macros
path="/root/backups"

# USUARIOS y PASSWORDS de FreeBSD
#

# 1 Backup /etc/passwd
tar -czf $path/passwd-`date +%Y-%m-%d-%H-%M`.tar.gz /etc/passwd

# 2 Backup /etc/master.passwd
tar -czf $path/master.passwd-`date +%Y-%m-%d-%H-%M`.tar.gz /etc/master.passwd

# 3 Backup /etc/group
tar -czf $path/group-`date +%Y-%m-%d-%H-%M`.tar.gz /etc/group

# 4 Backup /usr/home
tar -czf $path/home-`date +%Y-%m-%d-%H-%M`.tar.gz /usr/home

# 5 Backup /var/mail
tar -czf $path/mail-`date +%Y-%m-%d-%H-%M`.tar.gz /var/mail

# USUARIOS y PASSWORDS de SAMBA en FreeBSD
#
# Parte 1. Backup a: /usr/local/etc/samba o /usr/local/etc/samba34, activar el que corresponda a la version de samba
#
# =<> samba34 (samba34-3.4.9) /usr/local/etc/samba34/ por defecto utiliza 'passdb.tdb' + 'secrets.tdb' para sus usuarios
#tar -czf /usr/home/hd1/backups/FreeBSD/Usuarios-Samba34-`date +%Y-%m-%d-%H-%M`.tar.gz /usr/local/etc/samba34
#
# Backend to store user information in. New installations should
# use either tdbsam or ldapsam. smbpasswd is available for backwards
# compatibility. tdbsam requires no further configuration.
# ; passdb backend = tdbsam
#
# Entonces podemos emplear tdbsam o smbpasswd segun se desee, la linea para el archivo 'smbpasswd' seria.
# passdb backend = smbpasswd
#
# Convertir 'smbpasswd' a 'passdb.tdb' con el comando (como root):
# pdbedit -i smbpasswd:/path/smbpasswd -e tdbsam:/path/passdb.tdb
#
# Convertir 'passdb.tdb' a 'smbpasswd'con el comando (como root):
# pdbedit -i tdbsam:/path/passdb.tdb -e smbpasswd:/path/smbpasswd
#
# Podemos preguntarle a SAMBA cual usa actualmente con el comando:
# smbd -b | less
# ...
# SMB_PASSWD_FILE: /usr/local/etc/samba/smbpasswd
# ...
#
# Parte 2. Backup a: /usr/local/etc/smb.conf
tar -czf $path/samba.conf-`date +%Y-%m-%d-%H-%M`.tar.gz /usr/local/etc/smb.conf
#
# Parte 3. Backup a: /root/.nsmbrc <- Aqui se ingresan los host, usuarios y claves para montajes remotos con SAMBA
tar -czf $path/dotnsmbrc-`date +%Y-%m-%d-%H-%M`.tar.gz /root/.nsmbrc

Contenido del script FIN

Los comandos usados son basicamente:

Descomprimir los .tar.gz
# tar -xvzf archivo.tar.gz

Copiar un archivo
# cp archivo /ruta/

Copiar un directorio recursivamente, osea con los archivos y sub-directorios
# cp -r /ruta/directorio /ruta/

Borrar un directorio que tenga archivos y sub-directorios
# rm -rf directorioaborrar

martes, junio 01, 2010

FreeBSD + APCUPSD

Requerimientos:

FreeBSD instalado
UPS APC con tarjeta AP9619 conectada al servidor

Manuales:
/usr/local/share/doc/apcupsd/apcupsd.pdf
http://www.apcupsd.com/manual/manual.pdf
http://www.apcupsd.com/
http://www.freebsddiary.org/apcupsd.php
http://www.packetwatch.net/documents/guides/2010031301.php

Instrucciones:

1) Instalar el port apcupsd-3.14.8
# whereis apcupsd
apcupsd: /usr/ports/sysutils/apcupsd
# cd /usr/ports/sysutils/apcupsd
# make config
[X] APCSMART_DRV Compile APC SmartUPS serial driver
[X] APCDUMB_DRV Compile dumb UPS driver
[ ] CLIENT_ONLY Only NIS client (no network server or drivers)
[X] CGI Compile with CGI programs to show status
[X] PCNET_DRV Compile PowerChute Network Shutdown driver
[X] USB Compile with USB Support driver
[X] SNMP_DRV Compile with SNMP driver
[ ] SNMP_DRV_OLD Compile with old SNMP driver
[X] TCP_WRAPPERS Compile with TCP_WRAPPERS support
[ ] TEST_DRV Compile TEST driver
[ ] GAPCMON Build GTK GUI front-end

[ OK ]

# make install clean
---
**********************************************************************
Read the manual

/usr/local/share/doc/apcupsd/apcupsd.pdf

to do site specific configuration assigenments! Especially have a
detailed look into the chapter describing the shutdown procedure.

Sample files are installed in /usr/local/etc/apcupsd. These files
must be copied and/or configured for a proper working apcupsd.
You need to modify /usr/local/etc/apcupsd/apcupsd.conf as follows:

For serial cable: DEVICE /dev/cuadX (or /dev/cuaaX for [45.]x)
For USB cable: DEVICE (yes, leave it blank after DEVICE)

NOTE that for USB cable you must comment out the line

device uhid # "Human Interface Devices"

in your kernel configuration file and recompile the kernel.
Your keyboard and mouse will still work.

WARNING USB support on FreeBSD is still considered BETA!

Add apcupsd_enable=YES to your /etc/rc.conf[.local] to have apcupsd
starting up at boot time.

**********************************************************************
---

2) Configurar APCUPSD
# cd /usr/local/etc/apcupsd
# ls
apccontrol apcupsd.conf.sample apcupsd.css.sample changeme commok
hosts.conf.sample multimon.conf.sample onbattery apcupsd.conf
apcupsd.css cgi commfailure hosts.conf multimon.conf offbattery
# cp apcupsd.conf apcupsd.conf.sample
# cp apccontrol apccontrol.sample
# edit apcupsd.conf

# egrep -v '#|^ *$' apcupsd.conf
---
UPSNAME SURT10000XLT-1TF10K
UPSCABLE ether
UPSTYPE snmp
DEVICE 192.168.1.187:161:APC:private
POLLTIME 60
LOCKFILE /var/spool/lock
SCRIPTDIR /usr/local/etc/apcupsd
PWRFAILDIR /var/run
NOLOGINDIR /var/run
ONBATTERYDELAY 6
BATTERYLEVEL 5
MINUTES 3
TIMEOUT 0
ANNOY 300
ANNOYDELAY 60
NOLOGON disable
KILLDELAY 0
NETSERVER on
NISIP 0.0.0.0
NISPORT 3551
EVENTSFILE /var/log/apcupsd.events
EVENTSFILEMAX 10
UPSCLASS standalone
UPSMODE disable
STATTIME 0
STATFILE /var/log/apcupsd.status
LOGSTATS off
DATATIME 0
---

# touch /var/log/apcupsd.events
# touch /var/log/apcupsd.status

# edit hosts.conf
# egrep -v '#|^ *$' hosts.conf
---
MONITOR 127.0.0.1 "SURT10000XLT-1TF10K"
---

# edit multimon.conf
# egrep -v '#|^ *$' multimon.conf
---
TEMPC
FIELD SYSTEM "System" ""
FIELD MODEL "Model" ""
FIELD STATUS "Status" ""
FIELD battpct "Battery Chg" "%"
FIELD utility "Utility" "VAC"
FIELD loadpct "UPS Load" "%"
FIELD UPSTEMP "UPS Temp" ""
FIELD runtime "Batt. Run Time" "min."
FIELD DATA "Data" "All data"
---

3) Verificar que en el firewall se pueda acceder al puerto TCP 3551 del servidor desde la LAN

4) Editar el archivo /etc/rc.conf para agregar las lineas de APCUPSD para que inicie con el equipo

# edit /etc/rc.conf
---
# Activamos apcupsd (Si tengo una UPS marca APC)
apcupsd_enable="YES"
---

5) Crear el sitio en APACHE para monitorear la UPS remotamente por WWW ([X] CGI) agregando unas lineas
# edit /usr/local/etc/apache22/httpd.conf
---
# Modificacion para APCUPSD inicio
<Directory /usr/local/etc/apcupsd>
AllowOverride Options FileInfo
Order deny,allow
Allow from all
</Directory>
<Directory /usr/local/etc/apcupsd/cgi>
Options ExecCGI
</Directory>
ScriptAlias /apcupsd/cgi/ /usr/local/etc/apcupsd/cgi/
Alias /apcupsd /usr/local/etc/apcupsd/
# Modificacion para APCUPSD fin
---

Re-iniciar APACHE
# /usr/local/etc/rc.d/apache22 restart

6) Ajustar los parametros de la UPS
PARAMETROS DE LA UPS
IP Address: 192.168.1.187
Mask: 255.255.255.0
Gateway: 192.168.1.1

Tarjeta AP9619 S/N:
MAC Address 00:C0:B7:80:CA:D1

Enviarle la IP a la tarjeta desde FreeBSD
# arp -s 192.168.1.187 00:C0:B7:80:CA:D1
# ping 192.168.1.187 -s 113

Entrar por telnet a la ip de la tarjeta
# telnet 192.168.1.187

Login: apc
Passwd: apc

7) Iniciar el servicio
# /usr/local/etc/rc.d/apcupsd start

8) Monitorear la UPS via WWW, entrar a:
http://ipdemiserver/apcupsd/cgi/multimon.cgi

9) apcaccess Test
# apcaccess status
---
APC : 001,048,1167
DATE : 2010-09-01 07:36:10 -0500
HOSTNAME : alpha.company.com
VERSION : 3.14.8 (16 January 2010) freebsd
UPSNAME : UPS_IDEN
CABLE : Ethernet Link
MODEL : SNMP UPS Driver
UPSMODE : Stand Alone
STARTTIME: 2010-08-31 06:34:22 -0500
STATUS : ONLINE
LINEV : 205.0 Volts
LOADPCT : 38.0 Percent Load Capacity
BCHARGE : 100.0 Percent
TIMELEFT : 19.0 Minutes
MBATTCHG : 5 Percent
MINTIMEL : 3 Minutes
MAXTIME : 0 Seconds
MAXLINEV : 205.0 Volts
MINLINEV : 204.0 Volts
OUTPUTV : 207.0 Volts
SENSE : Unknown
DWAKE : 000 Seconds
DSHUTD : 020 Seconds
DLOWBATT : 02 Minutes
LOTRANS : 146.0 Volts
HITRANS : 229.0 Volts
RETPCT : 000.0 Percent
ITEMP : 34.0 C Internal
ALARMDEL : 5 seconds
BATTV : 214.0 Volts
LINEFREQ : 59.0 Hz
LASTXFER : Unacceptable line voltage changes
NUMXFERS : 0
TONBATT : 0 seconds
CUMONBATT: 0 seconds
XOFFBATT : N/A
SELFTEST : OK
STESTI : 336
STATFLAG : 0x07000008 Status Flag
MANDATE : 07/19/06
SERIALNO : NS0630013487
BATTDATE : 07/19/06
NOMOUTV : 208 Volts
NOMBATTV : 4294967295.0 Volts
EXTBATTS : 1
BADBATTS : -1
FIRMWARE : 476.17.W
APCMODEL : Smart-UPS RT 10000
END APC : 2010-09-01 07:37:10 -0500
---

10) APCUPSD SLAVE:
Se instala y configura en modo slave, estos son equipos que aunque reciben
energia de la UPS no estan conectados directamente a ella.

Nota:
La ip del servidor que corre APCUPSD en modo MASTER es 192.168.1.1

Parametros para los SLAVE en apcupsd.conf
UPSCABLE ether
UPSTYPE net
DEVICE 192.168.1.1:3551

WINDOWS
Cliente http://sourceforge.net/projects/apcupsd/files/win-binaries%20-%20Stable/
C:\apcupsd\etc\apcupsd\apcupsd.conf
Log
C:\apcupsd\etc\apcupsd\apcupsd.events

GNU/LINUX UBUNTU
$ sudo su
[sudo] password for angel:
# gedit /etc/apcupsd/apcupsd.conf
# gedit /etc/default/apcupsd
cambiar
ISCONFIGURED=no
por
ISCONFIGURED=yes

GNU/LINUX SUSE
YaST / Software / Software Management
apcupsd
# gedit /etc/apcupsd/apcupsd.conf
YaST / System / System Services (Runlevel)
apcupsd
Enable

MAC OS X
Configurar
sudo vi /private/etc/apcupsd/apcupsd.conf

Desinstalar
sudo /sbin/apcupsd-uninstall

FreeBSD
Configurar
# edit /usr/local/etc/apcupsd/apcupsd.conf
# edit /etc/rc.conf
apcupsd_enable="YES"
# /usr/local/etc/rc.d/apcupsd start
# exit

viernes, mayo 28, 2010

FreeBSD + MySQL

Requerimientos:

FreeBSD Instalado


Instrucciones:
1) Instalar MySQL desde los ports
# cd /usr/ports/databases/mysql50-server
# make install clean

2) Hacer que el MySQL se inicie con el sistema poniendo una linea en /etc/rc.conf como esta

# Activamos MySQL
mysql_enable="YES"

3) Iniciar MySQL para no tener que re-iniciar el servidor
# /usr/local/etc/rc.d/mysql-server start

4) Creamos el usuario administrador del gestor
# mysqladmin -u root password 'PASSWORDROOT'

Nota:
PASSWORDROOT se debe cambiar por una clave valida para el usuario root en MySQL
MyDB se debe cambiar por el nombre de la base de datos que requiero crear
usuario1 se debe cambiar por el nombre de usuario con el que se ingresara a DB
passusuario1 se debe cambiar por la clave que queremos para usuario1

5) Creamos la DB con su usuario correspondiente

# mysql -u root -p
Enter password: <- PASSWORDROOT
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15 Server version: 5.0.90 FreeBSD port: mysql-server-5.0.90 Type 'help;' or '\h' for help.
Type '\c' to clear the current input statement. mysql>

6) Crear la DB junto con el usuario y clave (todo de una)

CREAMOS DB utf8, permiso solo desde red clase "C", usuario y password, recargamos permisos
# mysql -u root -p
Enter password: <- PASSWORDROOT
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 5.0.90 FreeBSD port: mysql-server-5.0.90

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE DATABASE MyDB CHARACTER SET utf8 COLLATE utf8_general_ci;
Query OK, 1 row affected (0.01 sec)

mysql> GRANT ALL PRIVILEGES ON MyDB.* TO usuario1@'192.168.1.%' IDENTIFIED BY 'passusuario1';

Query OK, 0 rows affected (0.05 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
mysql> \q


Nota:

Esta permite conectar desde cualquier ip de la lan clase "C"
mysql> GRANT ALL PRIVILEGES ON MyDB.* TO usuario1@'192.168.1.%' IDENTIFIED BY 'passusuario1';

Con esta linea solo se permite conectar desde la ip 192.168.1.244
mysql> GRANT ALL PRIVILEGES ON MyDB.* TO usuario1@192.168.1.244 IDENTIFIED BY 'passusuario1';

7) Creamos la estructura (no se puede hacer si en el shell estoy como root)
$ mysql --user=root --password=PASSWORDROOT* MyDB < /tmp/dbiniciar.sql

8) Importamos los datos a la DB (no se puede hacer si en el shell estoy como root)
$ mysql --user=root --password=PASSWORDROOT* MyDB < /tmp/datos.sql

NOTA: Para borrar la DB que en este caso llamamos MyDB
# mysqladmin -u root drop MyDB -p
Enter password: <- PASSWORDROOT
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'MyDB' database [y/N]y

9) PRUEBAS CONEXION

REMOTA (desde un linux con mysql-client -> FreeBSD)

$ mysql -h 192.168.1.1 -u usuario1 MyDB -p
Enter password: <- passusuario1
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 522
Server version: 5.0.90 FreeBSD port: mysql-server-5.0.90

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> \q
Bye

LOCAL (desde FreeBSD)

# mysql -u root MyDB -p
Enter password: <- PASSWORDROOT
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.90 FreeBSD port: mysql-server-5.0.90

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> \q
Bye

BACKUP A LA DB ACTUAL (NO SE PUEDE HACER COMO ROOT)
$ mysqldump --user=root --password=PASSWORDROOT MyDB | gzip > /tmp/MyDB.sql.gz

IMPORTAR BACKUP

DESCOMPRIMIR EL BACKUP
# cd /tmp
# gunzip MyDB.sql.gz

IMPORTAR LA DB DEL BACKUP (NO SE PUEDE HACER COMO ROOT)
$ mysql --user=root --password=PASSWORDROOT MyDB < /tmp/MyDB.sql

martes, mayo 25, 2010

FreeBSD + Squid-cache + squidGuard

Este resumen no está disponible. Haz clic aquí para ver la publicación.

martes, mayo 11, 2010

FreeBSD 8

Requerimientos:

Disco de instalacion de FreeBSD
Conexion a internet

Instalando:

Iniciar el equipo desde el cd

232 United States
OK

Standard Begin a standard installation (recommended)
[Select]

...fdisk...
OK

Would you like to keep using the current geometry?
YES

A = Use Entire Disk
Q = Finish

Standard Install a standard MBR (no boot manager)
OK

Now you need to create BSD partitions...
OK

C = Create
4096M
OK
FS A file system
OK
Please specify a mount point for the partition
/
OK

C = Create
2048M
OK
Swap A swap partition
OK

C = Create
8192M
FS A file system
OK
/var
OK

C = Create
(the resto of hd free)
OK
FS A file system
OK
/usr
OK

Q = Finish

----------------------------------------------
Ejemplo de particionado para un disco de 36GB SCSI

Part Mount Size Newfs Part
da0s1a / 4096MB UFS2 Y
da0s1b swap 2048MB SWAP
da0s1d /var 8192MB UFS2+S Y
da0s1e /usr 22528MB UFS2+S Y
----------------------------------------------

[X] 5 Kern-Developer Full binaries and doc, kernel soruces only
OK

<<< X Exit Exit this menu (returning to previous)
OK

Would you like to install the FreeBSD ports collection?
YES
OK
1 CD/DVD Install fron a FreeBSD CD/DVD
OK

Last Chance!
YES

Congratulations! You now have FreeBSD installed on your system.

/usr/sbin/sysinstall

OK

Would you like to configure any Ethernet or SLIP/PPP network devices?
YES

(si tenemos dos tarjetas, debemos tomar nota de los nombres, por ejemplo: sis0 y rl0)

sis0 SiS 900/SiS 7016 PCI Ethernet card
OK

Do you want to try IPv6 configuration of the interface?
YES

Do you want to try DHCP configuration of the interface?
YES

Host: pruebas.company.com
Domain: company.com
IPv4 Gateway: 192.168.1.1
Name server: 192.168.1.1
IPv4 Address: 192.168.1.108
Netmask: 255.255.255.0
OK

Do you want this machine to funtion as a network gateway?
NO

Do you want to configure inetd and the network services that it provides?
NO

Would you like to enable SSH login?
YES

Do you want to have anonymous FTP access to this machine?
NO

Do you want to configure this machine as an NFS server?
NO

Do you want to configure this machine as an NFS client?
NO

Would you like to customize your system console settings?
NO

Would you like to set this machine's time zone now?
YES

Is this machine's CMOS clock set to UTC? If ...
NO

2 America -- North and South
OK

13 Colombia
OK

Does the abbreviation 'COT' look reasonable?
YES

Does this system have a PS/2, serial, or bus mouse?
NO

The FreeBSD package collection is a ...
NO

Would you like add any initial user accounts...?
YES

User Add a new user to the system
OK

Login: myname
UID: 1001
Group:
Password: ******
Confirm Password: *******
Full name: My Full Name
Member groups:
Home directory: /home/myname
Login shell: /bin/sh
OK

X Exit Exit this menu (returning to previous)
OK

Now you must set the system manager's password
OK
New Password: ******
Retype New Password: ******

Visit the general configuration menu...?
NO

X Exit Install

Are you sure you wish to exit? The system will reboot
YES

(expulsa el disco de instalacion)

Be sure to remove the media fron the drive
OK

(se reinicia el equipo)

(al terminar de cargar, nos pide login y password en el shell)

FreeBSD/i386 (pruebas.company.com) (ttyv0)
Login: root
Password: ******

pruebas#

Nota:
FreeBSD por defecto solo permite conectar por SSH con usuarios normales, tampoco permite a los usuarios hacer 'su' por seguridad, por esto para permitirle a un usuario hacer 'su' hay que editar el archivo /etc/group

# edit /etc/group
---
wheel:*:0:root,angel
---
En nuestro ejemplo hemos agregado el login angel como se puede ver, los logins van separados por (,).

martes, mayo 04, 2010

FreeBSD + Network UPS Tools

Requerimientos:
FreeBSD Instalado

Manuales:
http://www.networkupstools.org/
http://people.freebsd.org/~thierry/nut_FreeBSD_HowTo.txt
http://opensource.mgeups.com/howto.htm#test-cfg

Otros manuales:
http://taquiones.net/sysadmin/nut.html
http://www.lissyara.su/articles/freebsd/programms/network_ups_tools/
http://www.usebox.net/jjm/ups-obsd/

/usr/local/share/doc/nut

Datos de la tarjeta SNMP en la UPS
http://www.ingrasys.com/Product/usha/pd_usha_1.aspx

1) Instalar el port nut
#cd /usr/ports/sysutils/nut
# cd make config

Solo activo las opciones
[ ] SERIAL
[ ] USB
[X] SNMP
[X] NEON
[ ] HAL
[X] IPV6
[ ] DEVEL
[ ] CGI

Guardar y salir

# make install clean

2) Crear los archivos de configuracion

# cd /usr/local/etc/nut/

# cp ups.conf.sample ups.conf
---
[myups]
driver = snmp-ups
port = 192.168.1.252
#cable = 1234
desc = "UPS Pinnacle Plus 10000T"
---

# cp upsd.conf.sample upsd.conf
---
LISTEN 127.0.0.1 3493
---
# cp upsd.users.sample upsd.users
---
[admin]
password = mypass
actions = SET
instcmds = ALL

[upsmon]
password = pass
upsmon master
MONITOR myups@localhost 1 monuser pass master
---

# cp upsmon.conf.sample upsmon.conf
---
MONITOR myups@localhost 1 monuser mypass master
MINSUPPLIES 1
SHUTDOWNCMD "/sbin/shutdown -h +0"
POLLFREQ 5
POLLFREQALERT 5
HOSTSYNC 15
DEADTIME 15
POWERDOWNFLAG /etc/killpower
RBWARNTIME 43200
NOCOMMWARNTIME 300
FINALDELAY 5
---

Asegurando un poco los archivos de configuracion
# chown root:uucp /usr/local/etc/nut/upsd.conf
# chmod 0640 /usr/local/etc/nut/upsd.conf
# chown root:uucp /usr/local/etc/nut/upsd.users
# chmod 0640 /usr/local/etc/nut/upsd.users

Por defecto parece que requiere un directorio cuando esta corriendo,
en el configure.txt lo comenta en el numeral 5
# mkdir -p /var/state/ups
# chmod 0770 /var/state/ups
# chown uucp:wheel /var/state/ups

Tambien requiere otro directorio en /var/db/nut/upssched para el upssched.conf (upssched.pipe y upssched.lock)
# mkdir /var/db/nut/upssched
# chown uucp:uucp /var/db/nut/upssched

3) Hacer que inicie con el sistema agregando en /etc/rc.conf las lineas
---
# Activamos Network UPS Tools
nut_enable="YES"
nut_upslog_enable="YES"
nut_upsmon_enable="YES"
---

4) Iniciar el servicio [sart|stop]
# /usr/local/etc/rc.d/nut start
---
Network UPS Tools - UPS driver controller 2.4.1
Network UPS Tools - Generic SNMP UPS driver 0.44 (2.4.1)
Detected Model 10K on host 192.168.1.252 (mib: ietf 1.3)
[myups] unhandled ASN 0x5 recieved from 1.3.6.1.2.1.33.1.2.3.0
[myups] unhandled ASN 0x5 recieved from 1.3.6.1.2.1.33.1.2.6.0
[myups] unhandled ASN 0x5 recieved from 1.3.6.1.2.1.33.1.4.2.0
Starting nut.
Network UPS Tools upsd 2.4.1
/usr/local/etc/nut/upsd.conf is world readable
listening on 127.0.0.1 port 3493
Connected to UPS [myups]: snmp-ups-myups
/usr/local/etc/nut/upsd.users is world readable
---

Hay que iniciar los otros dos
# /usr/local/etc/rc.d/nut_upsmon start
# /usr/local/etc/rc.d/nut_upslog start


5) Solicitar informacion de la ups
# upsc myups@localhost
---
battery.charge: 100.00
battery.runtime.low: 0
battery.temperature: 32.00
battery.voltage: 256.80
driver.name: snmp-ups
driver.parameter.pollinterval: 2
driver.parameter.port: 192.168.1.252
driver.version: 2.4.1
driver.version.internal: 0.44
input.current: 0.00
input.frequency: 60.00
input.phases: 1.00
input.quality: 34.00
input.voltage: 2060.00
output.current: 0.00
output.phases: 1.00
output.realpower: 0.00
output.voltage: 2300.00
ups.firmware: Ver P7.0
ups.firmware.aux: AlphaLink Card v4.26 (SN 1117027624120)
ups.load: 64.00
ups.mfr: UPS
ups.model: Model 10K
ups.power: 0.00
ups.serial:
ups.status: OL
ups.test.result:
---

Para ver como va la cosa
# tail -f /var/log/messages

http://opensource.mgeups.com/howto.htm#test-cfg

Nota:
Se cambio la parte original ups_name@localhost por myups@localhost

To view the list of available settable variables, use the following command:
upsrw myups@localhost

To set the low battery level (which trigger shutdown), use the following command:
upsrw -s battery.charge.low=20 -u admin -p mypass myups@localhost

To view the list of available settable variables, use the following command:
upscmd -l myups@localhost

To execute a battery test, use the following command:
upscmd -u admin -p mypass myups@localhost battery.test

Actualizacion:
Active la opcion [X] cgi y re-instale el port

# edit /usr/local/etc/apache22/httpd.conf
agrego las siguientes lineas:
---
<Directory /usr/local/www/nut>
AllowOverride Options FileInfo
Order deny,allow
Allow from all
</Directory>

<Directory /usr/local/www/nut/cgi>
Options ExecCGI
</Directory>

ScriptAlias /nut/cgi/ /usr/local/www/nut/cgi/
Alias /nut /usr/local/www/nut/
---

Por defecto el port crea los directorios

# ls /usr/local/www/cgi-bin/nut/
upsimage.cgi upsset.cgi upsstats.cgi

# ls /usr/local/www/nut/
bottom.html header.html index.html nut-banner.png

Pero aun no se como hacer en el httpd.conf para que el sitio este en un lugar y que se pueda ejecutar los .cgi que estan en otro!

Para solucionarlo, copiare el contenido de /usr/local/www/cgi-bin/nut/ en una carpeta que creare dentro de /usr/local/www/nut/cgi

# mkdir /usr/local/www/nut/cgi
# cp /usr/local/cgi-bin/nut/*.cgi /usr/local/www/nut/cgi

El codigo del archivo /usr/local/www/nut/header.html apunta a los .cgi , pero los hago apuntar dentro de /usr/local/www/nut/cgi

# edit /usr/local/www/nut/header.html

Asi quedaron las lineas ya modificadas

<a href=/nut/cgi/upsstats.cgi target=mainFrame>Statistics</a>

<a href=/nut/cgi/upsset.cgi target=mainFrame>Settings</a>

adicionalmente con la activacion de [X] CGI se crearon otros archivos dentro de /usr/local/etc/nut/

Aqui pongo el contenido de todos luego del cambio:

# egrep -v '#|^ *$' hosts.conf
MONITOR myups@localhost "My UPS"

# egrep -v '#|^ *$' nut.conf
MODE = none

# egrep -v '#|^ *$' ups.conf
[myups]
driver = snmp-ups
port = 192.168.1.252
desc = "My UPS"

# egrep -v '#|^ *$' upsd.conf
LISTEN 127.0.0.1 3493
LISTEN 192.168.1.1 3493 (esta es la ip fija que da a la lan)

# egrep -v '#|^ *$' upsmon.conf
MONITOR myups@localhost 1 upsmon pass master
MINSUPPLIES 1
SHUTDOWNCMD "/sbin/shutdown -h +0"
POLLFREQ 5
POLLFREQALERT 5
HOSTSYNC 15
DEADTIME 15
POWERDOWNFLAG /etc/killpower
RBWARNTIME 43200
NOCOMMWARNTIME 300
FINALDELAY 5

# egrep -v '#|^ *$' upssched.conf
CMDSCRIPT /usr/local/bin/upssched-cmd

# egrep -v '#|^ *$' upsset.conf
este no tiene nada activado

# egrep -v '#|^ *$' upsd.users
[admin]
password = mypass
actions = SET
instcmds = ALL
[upsmon]
password = pass
upsmon master
MONITOR myups@localhost 1 monuser pass master

copio un par de archivos .html.sample

# cp upsstats-single.html.sample upsstats-single.html
# cp upsstats.html.sample upsstats.html

Re-inicio el servicio

# /usr/local/etc/rc.d/nut restart

Para ver si la cosa del html funciona, ingreso a
http://ipdemiservidor/nut

Nota2:
Ya encontre la razon de que me diera errores al tratar de compartir los cgi del nut, la razon era una linea en el /usr/local/etc/apache22/httpd.conf
la linea que daba problemas era:
ScriptAlias /cgi-bin/ "/usr/local/www/apache22/cgi-bin/"

Si la desactivo con un #, puedo crear toda la entrada asi:
# Modificacion para Network UPS Tools inicio

# Para el sitio
<Directory /usr/local/www/nut>
AllowOverride Options FileInfo
Order deny,allow
Allow from all
</Directory>

<Directory /usr/local/www/nut/cgi>
Options ExecCGI
</Directory>

#ScriptAlias /nut/cgi/ /usr/local/www/nut/cgi/
Alias /nut /usr/local/www/nut/

# Notas:
# * Los CGI los pone en el directorio /usr/local/www/cgi-bin/nut
# * Para poder ejecutar los cgi en el directorio de instalacion, desactivo (#) una linea
# de arriba que dice:
# ScriptAlias /cgi-bin/ "/usr/local/www/apache22/cgi-bin/"
# ya que parece que no se requiere actualmente para nadie
#
# Para los CGI
<Directory /usr/local/www/cgi-bin/nut>
AllowOverride Options FileInfo
Order deny,allow
Allow from all
</Directory>

<Directory /usr/local/www/cgi-bin/nut>
Options ExecCGI
</Directory>

ScriptAlias /cgi-bin/nut/ /usr/local/www/cgi-bin/nut/
Alias /cgi-bin/ /usr/local/www/cgi-bin/nut/

# Modificacion para Network UPS Tools fin

Logicamente, con esta solucion ya no es necesario la carpeta /usr/local/www/nut/cgi y tampoco hay que poner a apuntar los links en /usr/local/www/nut/header.html a otros lugares.

Nota3:
Tambien tengo una ups de la marca CyberPower System

y para el FreeBSD 8 en el archivo de la ups tengo esto:
# egrep -v '#|^ *$' ups.conf
[CPS425SL]
driver = genericups
port = /dev/cuau0
upstype = 7
desc = "CyberPower Systems 425SL 425VA / CPS425SL"

Hay que anotar que en FreeBSD 8 el nombre de los COM cambio:
http://www.freebsd.org/releases/8.0R/relnotes-detailed.html

COM1 /dev/cuau0
COM2 /dev/cuau1

Hasta este punto, cuando la UPS llega al nivel critico de las baterias, apaga el servidor.

Otra opcion interesante es poder programar un apagado en el servidor luego de que la UPS esta agotando las baterias, por ejemplo luego de 60 segundos...

Para esto hay que usar upssched y agregarle unas lineas, aqui dejo las modificaciones:

# egrep -v '#|^ *$' /usr/local/etc/nut/upsmon.conf
MONITOR myups@localhost 1 upsmon pass master
MINSUPPLIES 1
SHUTDOWNCMD "/sbin/shutdown -h +0"
NOTIFYCMD /usr/local/sbin/upssched
POLLFREQ 5
POLLFREQALERT 5
HOSTSYNC 15
DEADTIME 15
POWERDOWNFLAG /etc/killpower
NOTIFYMSG ONBATT "%s is on battery"
NOTIFYMSG ONLINE "%s is back online"
NOTIFYMSG LOWBATT "%s has a low battery!"
NOTIFYMSG SHUTDOWN "System is being shutdown!"
NOTIFYFLAG ONBATT SYSLOG+EXEC
NOTIFYFLAG ONLINE SYSLOG+EXEC
NOTIFYFLAG LOWBATT SYSLOG+EXEC
NOTIFYFLAG SHUTDOWN SYSLOG+EXEC
RBWARNTIME 43200
NOCOMMWARNTIME 300
FINALDELAY 5

# egrep -v '#|^ *$' /usr/local/etc/nut/upssched.conf
CMDSCRIPT /usr/local/bin/upssched-cmd
PIPEFN /var/db/nut/upssched/upssched.pipe
LOCKFN /var/db/nut/upssched/upssched.lock
AT ONBATT * START-TIMER ONBATT 60 <- los 60 seg
AT ONLINE * CANCEL-TIMER ONBATT
AT LOWBATT * EXECUTE LOWBATT
AT SHUTDOWN * EXECUTE SHUTDOWN

# egrep -v '#|^ *$' /usr/local/bin/upssched-cmd
case $1 in
ONBATT)
echo ONBATT TIMEOUT | mail -s "UPS Notify" reidrac
/usr/local/sbin/upsmon -c fsd
;;
LOWBATT)
echo LOWBATT | mail -s "UPS Notify" reidrac
;;
SHUTDOWN)
echo SHUTDOWN | mail -s "UPS Notify" reidrac
;;
*)
logger -t upssched-cmd "Unrecognized command: $1"
;;
esac

Re-inicio upsmon para que tome la nueva configuracion
# /usr/local/etc/rc.d/nut_upsmon restart

jueves, abril 29, 2010

FreeBSD + Squid-cache + SquidClamAV + ClamAV

Requerimientos:

FreeBSD instalado
Squid-cache instalado

1) Instalar ClamAV
# whereis clamav
clamav: /usr/ports/security/clamav
# cd /usr/ports/security/clamav
# make install clean

Crear el archivo de configuracion

# cp /usr/local/etc/clamd.conf.default /usr/local/etc/clamd.conf

Ejemplo del contenido ya listo

Note que la opcion
LocalSocket /var/run/clamav/clamd.sock
no puede funcionar si esta usando las opciones
TCPSocket 3310
TCPAddr 127.0.0.1

egrep -v '#|^ *$' /usr/local/etc/clamd.conf
---
LogFile /var/log/clamav/clamd.log
PidFile /var/run/clamav/clamd.pid
TemporaryDirectory /usr/home/hd1/infected
DatabaseDirectory /var/db/clamav
FixStaleSocket yes
TCPSocket 3310
TCPAddr 127.0.0.1
MaxConnectionQueueLength 30
User root
AllowSupplementaryGroups yes
ScanMail yes
---

Hacer que se inicie con el sistema

Poner las siguientes lineas en el /etc/rc.conf
---
# Activamos ClamAV (antivirus para Samba)
clamav_freshclam_enable="YES"
clamav_clamd_enable="YES"
---

Iniciar ClamAV
# /usr/local/etc/rc.d/clamav-clamd start

El log /var/log/clamav/clamd.log

Muestra algo como esto
---
+++ Started at Thu Apr 29 10:06:02 2010
clamd daemon 0.96 (OS: freebsd7.2, ARCH: amd64, CPU: amd64)
Running as user root (UID 0, GID 0)
Log file size limited to 1048576 bytes.
Reading databases from /var/db/clamav
Not loading PUA signatures.
Loaded 759499 signatures.
TCP: Bound to address 127.0.0.1 on port 3310
TCP: Setting connection queue length to 30
Limits: Global size limit set to 104857600 bytes.
Limits: File size limit set to 26214400 bytes.
Limits: Recursion level limit set to 16.
Limits: Files limit set to 10000.
Archive support enabled.
Algorithmic detection enabled.
Portable Executable support enabled.
ELF support enabled.
Mail files support enabled.
OLE2 support enabled.
PDF support enabled.
HTML support enabled.
Self checking every 600 seconds.
Set stacksize to 2162688
No stats for Database check - forcing reload
Reading databases from /var/db/clamav
Database correctly reloaded (759499 signatures)
---

Verificar que esta funcionando

# sockstat -4 | grep clamd
root clamd 26383 4 tcp4 127.0.0.1:3310 *:*

Hacer una prueba mediante telnet y ponerlo a escanear el directorio /root

# telnet localhost 3310
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
SCAN /root
/root: OK
Connection closed by foreign host.

2) Instalar SquidClamAV
# whereis squidclamav
squidclamav: /usr/ports/security/squidclamav
# cd /usr/ports/security/squidclamav
# make install clean

Crear el archivo de configuracion
# cp /usr/local/etc/squidclamav.conf.dist /usr/local/etc/squidclamav.conf

Ejemplo del contenido ya listo

egrep -v '#|^ *$' /usr/local/etc/squidclamav.conf

---
squid_ip 127.0.0.1
squid_port 3128
logfile /var/log/squidclamav.log
maxsize 5000000
redirect http://alpha/mensaje6.html
stat 0
maxredir 30
clamd_ip 127.0.0.1
clamd_port 3310
timeout 60
useragent Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100402)
trust_cache 0
logredir 0
abort ^.*\.(ico|gif|png|jpg)$
abortcontent ^image\/.*$
abort ^.*\.(css|xml|xsl|js|html|jsp)$
abortcontent ^text\/.*$
abortcontent ^application\/x-javascript$
abortcontent ^video\/x-flv$
abortcontent ^video\/mp4$
abort ^.*\.swf$
abortcontent ^application\/x-shockwave-flash$
abortcontent ^.*application\/x-mms-framed.*$
whitelist .*\.clamav.net
---

Crear el archivo de log /var/log/squidclamav.log

# touch /var/log/squidclamav.log

Darle permiso para que lo use

chown squid:squid /var/log/squidclamav.log

Verificar que se aplico correctamente los permisos

# ls -l /var/log/squidclamav.log
-rw-r--r-- 1 squid squid 324645 Apr 29 12:19 /var/log/squidclamav.log

Iniciar el squidclamav manualmente para prueba
# squidclamav -c /usr/local/etc/squidclamav.conf

---
SquidClamav v5.3 running in interactive mode
Wed Apr 28 14:28:38 2010 LOG Anonymizing User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100402 Ubuntu/9.10 (karmic)
Wed Apr 28 14:28:38 2010 LOG SquidClamav v5.3 (PID 88666) started
---

Note que para pararlo, se hace con
Ctrl + C

3) Configuro unos parametros adicionales en el /usr/local/etc/squid/squid.conf
Le agrego las siguientes lineas

on ACL definition you should have declared:

acl localhost src 127.0.0.1/255.255.255.255
acl to_localhost dst 127.0.0.0/8
acl purge method PURGE

on http_acces definition you should declared the follwing :

http_access deny to_localhost
http_access allow localhost
http_access allow purge localhost
http_access deny purge
url_rewrite_access deny localhost

and on the redirect section the following:

url_rewrite_program /usr/local/bin/squidclamav -c /usr/local/etc/squidclamav.conf
url_rewrite_children 30

Verificar los logs para ver que todo esta bien

Para Squid-cache
# tail -f /usr/local/squid/logs/cache.log
---
2010/04/29 11:56:33| Starting Squid Cache version 3.0.STABLE25 for amd64-portbld-freebsd7.2...
2010/04/29 11:56:33| Process ID 39294
2010/04/29 11:56:33| With 11072 file descriptors available
2010/04/29 11:56:33| DNS Socket created at 0.0.0.0, port 51259, FD 7
2010/04/29 11:56:33| Adding domain company.com from /etc/resolv.conf
2010/04/29 11:56:33| Adding nameserver 127.0.0.1 from /etc/resolv.conf
2010/04/29 11:56:33| helperOpenServers: Starting 30/30 'squidclamav' processes
---

# tail -f /usr/local/squid/logs/access.log
---
---

Para SquidClamAV
# tail -f /var/log/squidclamav.log
---
Thu Apr 29 11:56:33 2010 [39306] LOG SquidClamav v5.3 (PID 39306) started
Thu Apr 29 11:56:33 2010 [39307] LOG Anonymizing User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100402 Ubuntu/9.10 (karmic)
Thu Apr 29 11:56:33 2010 [39308] LOG Anonymizing User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100402 Ubuntu/9.10 (karmic)
Thu Apr 29 11:56:33 2010 [39309] LOG Anonymizing User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100402 Ubuntu/9.10 (karmic)
---

miércoles, marzo 24, 2010

FreeBSD + Ajax-Chat

Requirements
============

Server-Side:

- PHP >= 4
- MySQL >= 4
- Ruby >= 1.8 (optional)


Client-Side:

- Enabled JavaScript
- Enabled Cookies
- Flash Plugin >= 9 (optional)

Installation
============

1) Descargar la ultima version de ajax chat
# cd /usr/local/www
# wget http://ufpr.dl.sourceforge.net/project/ajax-chat/ajax-chat/0.8.3/ajax_chat-0.8.3.zip
# gunzip ajax_chat-0.8.3.zip

2) Crear la DB chat en mysql
Creandola
$ mysqladmin -uroot create glpi

Garantizando acceso a la database
$ mysql -uroot -e"GRANT ALL ON chat.* TO admin@localhost IDENTIFIED BY 'MICLAVE'" chat

Nota:
MICLAVE se debe cambiar por la clave correcta

(choose your own values for USERNAME and PASSWORD)

3) Poner estas lineas en el /usr/local/etc/apache22/httpd.conf

# Modificacion para CHAT inicio
Alias /chat /usr/local/www/chat/

AllowOverride Options FileInfo
Order allow,deny
Allow from all

# Modificacion para CHAT fin

4) Configurar ajax chat

Configuration settings
----------------------

# cd /usr/local/www/chat/lib
# cp config.php.example config.php
# edit config.php

$config['dbConnection'] = array();
// Database hostname:
$config['dbConnection']['host'] = 'localhost';
// Database username:
$config['dbConnection']['user'] = 'admin';
// Database password:
$config['dbConnection']['pass'] = 'MICLAVE';
// Database name:
$config['dbConnection']['name'] = 'chat';
// Database type:
$config['dbConnection']['type'] = 'mysql';
// Database link:
$config['dbConnection']['link'] = null;


Channel settings:
-----------------

# cd /usr/local/www/chat/lib/data
# cp channels.php channels.php.original
# edit channels.php

User settings:
--------------

# cd /usr/local/www/chat/lib/data
# cp users.php users.php.original
# edit users.php

Upload to the server
--------------------

Upload the chat folder to your server somewhere under your document root:
e.g. http://alpha/chat/



Creation of database tables
---------------------------

Execute the provided installation script by visiting the following URL with your browser:
http://alpha/chat/install.php

Se ven estas lineas
---

Database tables created successfully - please delete this file (install.php).
---

Delete the installation script
------------------------------

Delete the file install.php from the chat directory on your server.


Ready! Just place a link to the chat directory on your website. :)

# cd /usr/local/www/chat
# mv install.php install.php.original

5) Configurando los usuarios admin y moderator

# cd /usr/local/www/chat/lib/data
# edit users.php

Se ve algo como esto
---


Se pueden cambiar las lineas respectivas para cambiar el password, ejemplo:

Para el usuario admin, que tiene role 1
$users[1]['password'] = 'PASSWORDADMIN';

Para el usuario moderator, que tiene role 2
$users[2]['password'] = 'PASSWORDMODERATOR';

Se guardan los cambios y listo!

Si luego quiero ver los logs, ingreso a:
http://alpha/chat/?view=logs

Username: admin
Password: PASSWORDADMIN

CREAR CHANNELS ADICIONALES
http://sourceforge.net/apps/mediawiki/ajax-chat/index.php?title=Custom_chat_channels

Limiting the list of forums used as chat channels
# edit /usr/local/www/chat/lib/config.php

$config['limitChannelList'] = array(123,456,789);

Adding additional chat channels
# edit /usr/local/www/chat/lib/data/channels.php

Cambiar
// Sample channel list:
$channels[0] = 'Public';
$channels[1] = 'Private';

Por
// Sample channel list:
$channels[0] = 'Public';
$channels[1] = 'Private';
$channels[2] = '123';
$channels[3] = '456';
$channels[4] = '789';

# edit /usr/local/www/chat/lib/class/CustomAJAXChat.php

Add
$this->_channels = array_merge($this->_channels, array('Extra_Public_Channel_1'=>123, 'Extra_Public_Channel_2'=>456, 'Extra_Public_Channel_3'=>789));

before

}
return $this->_channels;

Add
$this->_allChannels = array_merge($this->_allChannels, array('Extra_Public_Channel_1'=>123, 'Extra_Public_Channel_2'=>456, 'Extra_Public_Channel_3'=>789));

before

}
return $this->_allChannels;

ACTUALIZACION:
Ajax-Chat no funciona con PHP superior a 4, luego de un tiempo actualizo a esa version y Ajax-Chat ya no funciona por un parametro de fecha y no hay version nueva que use ese nuevo parametro, como solucion, cambio Ajax-Chat por http://www.phpfreechat.net , que es muy facil de instalar y parece funcionar bien!
Por defecto al montarlo todos inician con el usuario guest, para que pida que la persona escriba algun nombre, se desactiva con // en el archivo index.php del sitio
//linea desactivada $params["nick"] = "guest".rand(1,1000);