Páginas

martes, 13 de diciembre de 2011

PHP Vim

Función para la correcta visualización de acentos y caracteres especiales:

Vim se ha convertido en mi editor favorito, sin quitar mérito a otros editores como Emacs (el monstruo de los editores de Linux y el preferido por los programadores, altamente configurable, rápido y potente, IDE utilizando plugins, etc..), jedit, gedit, komodo, etc. Para editar archivos de texto cualquier editor vale, pero, ¿y si queremos un IDE para programar en ruby, php, html, etc con función de autocompletado, explorador de archivos y poder abrir una terminal desde vim ?.
Vi con algunos plugins será suficiente:
NERD_tree Navegador de archivos:
La página de descarga es: http://www.vim.org/scrits/script.php?script_id=1658

Descomprimir el archivo NERD_tree.zip dentro del directorio ~/.vim
Asegúrese de comprobar que el archivo NERD_tree.vim esta en ~/.vim/plugin y NERD_tree.txt
en ~/.vim/doc.

Gentoo utiliza /var/www/localhost/htdocs como directorio predeterminado. El archivo
de configuración de vim y agregar está linea:

# vi /etc/vim/vimrc.local
" Teclado rápido para abrir explorador de archivos NERTree
map ex :NERDTree /var/www/localhost/htdocs

Conque es un plugin para vi que permite abrir una terminal sin salir de vi.
La página de descarga es:
http://www.vim.org/scripts/script.php?script_id=2771

Después de descargar el plugin debe abrirse con vi, acto seguido teclear
:so %

En este momento puede abrir una terminal desde vi:
:ConqueTermSplit bash

Utilizar teclas rápidas desde vi pasa por agregar al archivo de configuración
/etc/vim/vimrc.local:

# vi /etc/vim/vimrc.local
" Crear alias para abrir terminal dentro de vi
" la primera linea abre un terminal
" la segunda abre un terminal vertical (V).
map ct :ConqueTermSplit bash
map cv :ConqueTermVSplit bash

" mapeo para editar el fichero a traves del
" interprete de php
autocmd FileType php noremap :w!:!/usr/bin/php %

" mapeo para pasear la sintaxis del fichero
" a traves del interprete de php en modo lint
autocmd FileType php noremap :!/usr/bin/php -l %

" Activar autocompletado php y html
" ctrl + x para autocomplete
" ctrl +o muestra opciones de autocomplete
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags

Luego al abrir un archivo .php, para activar el autocompletado:
Ctrl + z y Ctrl + o.

Es importante saber que para movernos por las diferentes por las diferentes ventanas
utilzaremos las teclas Ctrl + w seguido de la tecla de dirección hacia la ventana que
queremos movernos, (Der, Izq, Arriba o Abajo).

Por último el plugin Tag List. Un plugin para el navegador de código fuente de Vim
y proporciona una visión general de la estructura de archivos de código fuente para
los diferentes lenguajes de programación. El link de descarga:

http://www.vim.org/scripts/script.php?script_id=273

Descomprimir el archivo taglist_45.zip en el directorio ~/.vim
Compruebe el archivo principal y la documentación:

plugin/taglit.vim
doc/taglis.txt

$ cd ~/.vim/doc
$ ~/.vim/doc $ ls -l
total 168
-rw-r--r-- 1 carlos users 27142 Nov 30 07:55 conque_term.txt
-rw-r--r-- 1 carlos users 50021 Dec  1  2009 NERD_tree.txt
-rwxr-xr-x 1 carlos users 69366 May 24  2007 taglist.txt
-rw-r--r-- 1 carlos users 10673 Dec 13 14:18 tags

Iniciar vim y dentro de vim en modo comando (Esc):
:helptags .  <--- no olvidar el punto. Este comando procesa la ayuda del archivo tatglist.


Linux es genial!.

domingo, 13 de noviembre de 2011

Instalar ruby on rails

Instalar ruby rails en plataforma de desarrollo gentoo.
http://www.rubyonrails.org.es/
http://www.guateonrails.com Javier Alvarez.

Si están aprendiendo Ruby on Rails este es un sitio de visita obligada y visualicen los videos del sitio, excelentemente sencillos. Guateonrails.

Ruby es un lenguaje de programación interpretado que funciona con cualquier sistema operativo, aunque con los sistemas tipo Unix es que mejor se integra.


Instalar ruby:

# emerge -av ruby

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild  N     ] app-admin/eselect-ruby-20100603  2 kB
[ebuild  N     ] dev-lang/ruby-1.8.7_p352  USE="berkdb gdbm ipv6 ncurses readline ssl -debug -doc -examples -libedit -rubytests -socks5 -threads -tk -xemacs" 4,112 kB

Total: 2 packages (2 new), Size of downloads: 4,114 kB

Would you like to merge these packages? [Yes/No] y

Instalar rubygems:

# emerge -av rubygems

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild  N     ] dev-ruby/rubygems-1.3.7-r1  USE="-doc -server" RUBY_TARGETS="ruby18 -jruby -ree18" 285 kB

Total: 1 package (1 new), Size of downloads: 285 kB

Would you like to merge these packages? [Yes/No] y

Al finalzar la instalación un mensaje nos advierte:

 * To switch between available Ruby profiles, execute as root:
 * eselect ruby set ruby(18|19|...)

Procedemos:

# eselect ruby list
Available Ruby profiles:
  [1]   ruby18 (with Rubygems) *
# eselect ruby set ruby18
Successfully switched to profile:
  ruby18

Averiguar versión instalada:                
# gem -v
1.3.7

Instalar rails a través de Rubygem:

 # gem18 install rails --include-dependencies
INFO:  `gem install -y` is now default and will be removed
INFO:  use --ignore-dependencies to install only the gems you list
Building native extensions.  This could take a while...
Depending on your version of ruby, you may need to install ruby rdoc/ri data:

<= 1.8.6 : unsupported
 = 1.8.7 : gem install rdoc-data; rdoc-data --install
 = 1.9.1 : gem install rdoc-data; rdoc-data --install
>= 1.9.2 : nothing to do! Yay!
...

En un futuro para actualizar Rails solo tendremos que teclear:

# gem update rails --include-dependencies

# emerge -av sqlite3-ruby

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild  N     ] virtual/rubygems-1  RUBY_TARGETS="(ruby18)" 0 kB
[ebuild  N     ] dev-ruby/rake-0.8.7-r5  USE="-bash-completion -doc -test" RUBY_TARGETS="ruby18 -jruby -ree18" 101 kB
[ebuild  N     ] dev-ruby/hoe-2.8.0  USE="-doc -test" RUBY_TARGETS="ruby18 -jruby -ree18" 114 kB
[ebuild  N     ] dev-ruby/rake-compiler-0.7.5  USE="-test" RUBY_TARGETS="ruby18 -jruby -ree18" 26 kB
[ebuild  N     ] dev-ruby/sqlite3-ruby-1.3.2  USE="-doc -test" RUBY_TARGETS="ruby18 -ree18" 55 kB

Total: 5 packages (5 new), Size of downloads: 295 kB

Would you like to merge these packages? [Yes/No]

Instalar el paquete mysql de gems:

# gem install mysql
Building native extensions.  This could take a while...
Successfully installed mysql-2.8.1
1 gem installed
Installing ri documentation for mysql-2.8.1...
Installing RDoc documentation for mysql-2.8.1...

Verificar instalación y versión de rails:

# rails --version
Rails 3.1.1

Creando un esqueleto:
 $ rails new ~/code/ruby/weblog rails server
      create
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/images/rails.png
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  app/mailers/.gitkeep
      create  app/models/.gitkeep
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  lib/assets
      create  lib/assets/.gitkeep
      create  log
      create  log/.gitkeep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  script
      create  script/rails
      create  test/fixtures
      create  test/fixtures/.gitkeep
      create  test/functional
      create  test/functional/.gitkeep
      create  test/integration
      create  test/integration/.gitkeep
      create  test/unit
      create  test/unit/.gitkeep
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.gitkeep
      create  vendor/plugins
      create  vendor/plugins/.gitkeep
         run  bundle install
Enter your password to install the bundled RubyGems to your system:
Fetching source index for http://rubygems.org/
Using rake (0.9.2.2)
Using multi_json (1.0.3)
Using activesupport (3.1.1)
Using builder (3.0.0)
Using i18n (0.6.0)
Using activemodel (3.1.1)
Using erubis (2.7.0)
Using rack (1.3.5)
Using rack-cache (1.1)
Using rack-mount (0.8.3)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.0.3)
Using actionpack (3.1.1)
Using mime-types (1.17.2)
Using polyglot (0.3.3)
Using treetop (1.4.10)
Using mail (2.3.0)
Using actionmailer (3.1.1)
Using arel (2.2.1)
Using tzinfo (0.3.31)
Using activerecord (3.1.1)
Using activeresource (3.1.1)
Using bundler (1.0.21)
Installing coffee-script-source (1.1.3)
Installing execjs (1.2.9)
Installing coffee-script (2.2.0)
Using rack-ssl (1.3.2)
Using json (1.6.1)
Using rdoc (3.11)
Using thor (0.14.6)
Using railties (3.1.1)
Installing coffee-rails (3.1.1)
Installing jquery-rails (1.0.17)
Using rails (3.1.1)
Installing sass (3.1.10)
Installing sass-rails (3.1.4)
Installing sqlite3 (1.3.4) with native extensions
Installing uglifier (1.0.4)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

Comprobar dependencias:

$ bundle - Ruby
Using rake (0.9.2.2)
Using multi_json (1.0.3)
Using activesupport (3.1.1)
Using builder (3.0.0)
Using i18n (0.6.0)
Using activemodel (3.1.1)
Using erubis (2.7.0)
Using rack (1.3.5)
Using rack-cache (1.1)
Using rack-mount (0.8.3)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.0.3)
Using actionpack (3.1.1)
Using mime-types (1.17.2)
Using polyglot (0.3.3)
Using treetop (1.4.10)
Using mail (2.3.0)
Using actionmailer (3.1.1)
Using arel (2.2.1)
Using tzinfo (0.3.31)
Using activerecord (3.1.1)
Using activeresource (3.1.1)
Using bundler (1.0.21)
Using coffee-script-source (1.1.3)
Using execjs (1.2.9)
Using coffee-script (2.2.0)
Using rack-ssl (1.3.2)
Using json (1.6.1)
Using rdoc (3.11)
Using thor (0.14.6)
Using railties (3.1.1)
Using coffee-rails (3.1.1)
Using jquery-rails (1.0.17)
Using rails (3.1.1)
Using sass (3.1.10)
Using sass-rails (3.1.4)
Using sqlite3 (1.3.4)
Using uglifier (1.0.4)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

$ bundle show

Gems included by the bundle:
  * actionmailer (3.1.1)
  * actionpack (3.1.1)
  * activemodel (3.1.1)
  * activerecord (3.1.1)
  * activeresource (3.1.1)
  * activesupport (3.1.1)
  * arel (2.2.1)
  * builder (3.0.0)
  * bundler (1.0.21)
  * coffee-rails (3.1.1)
  * coffee-script (2.2.0)
  * coffee-script-source (1.1.3)
  * erubis (2.7.0)
  * execjs (1.2.9)
  * hike (1.2.1)
  * i18n (0.6.0)
  * jquery-rails (1.0.17)
  * json (1.6.1)
  * mail (2.3.0)
  * mime-types (1.17.2)
  * multi_json (1.0.3)
  * polyglot (0.3.3)
  * rack (1.3.5)
  * rack-cache (1.1)
  * rack-mount (0.8.3)
  * rack-ssl (1.3.2)
  * rack-test (0.6.1)
  * rails (3.1.1)
  * railties (3.1.1)
  * rake (0.9.2.2)
  * rdoc (3.11)
  * sass (3.1.10)
  * sass-rails (3.1.4)
  * sprockets (2.0.3)
  * sqlite3 (1.3.4)
  * thor (0.14.6)
  * tilt (1.3.3)
  * treetop (1.4.10)
  * tzinfo (0.3.31)
  * uglifier (1.0.4)

$ bundle check
The Gemfile's dependencies are satisfied


$ bundle update
Fetching source index for http://rubygems.org/
Enter your password to install the bundled RubyGems to your system:
Using rake (0.9.2.2)
Using multi_json (1.0.3)
Using activesupport (3.1.1)
Using builder (3.0.0)
Using i18n (0.6.0)
Using activemodel (3.1.1)
Using erubis (2.7.0)
Using rack (1.3.5)
Using rack-cache (1.1)
Using rack-mount (0.8.3)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.0.3)
Using actionpack (3.1.1)
Using mime-types (1.17.2)
Using polyglot (0.3.3)
Using treetop (1.4.10)
Using mail (2.3.0)
Using actionmailer (3.1.1)
Using arel (2.2.1)
Using tzinfo (0.3.31)
Using activerecord (3.1.1)
Using activeresource (3.1.1)
Using bundler (1.0.21)
Using coffee-script-source (1.1.3)
Using execjs (1.2.9)
Using coffee-script (2.2.0)
Using rack-ssl (1.3.2)
Using json (1.6.1)
Using rdoc (3.11)
Using thor (0.14.6)
Using railties (3.1.1)
Using coffee-rails (3.1.1)
Installing jquery-rails (1.0.18)
Using rails (3.1.1)
Using sass (3.1.10)
Installing sass-rails (3.1.5)
Using sqlite3 (1.3.4)
Installing uglifier (1.1.0)
Your bundle is updated! Use `bundle show [gemname]` to see where a bundled gem

Corregir error formato fecha:

# cd /usr/lib64/ruby/gems/1.8/specifications
# vim jquery-rails-1.0.17.gemspec

 cambiar:

 s.date = %q{2001-11-09 00.00.00 000000000Z}
por:
 s.date = %q{2011-11-13}

$ rails new ~/code/ruby/weblog
$ cd code/ruby/weblog/
$ bundle show

Corigiendo errores:

$ rails server
/usr/lib64/ruby/gems/1.8/gems/execjs-1.2.9/lib/execjs/runtimes.rb:47:in `autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)

$ sudo gem install 'execjs'
Password:

Successfully installed execjs-1.2.9
1 gem installed
Installing ri documentation for execjs-1.2.9...
Installing RDoc documentation for execjs-1.2.9...

$ sudo gem install 'therubyracer'
Fetching: libv8-3.3.10.2-x86_64-linux.gem (100%)
Fetching: therubyracer-0.9.9.gem (100%)
Building native extensions.  This could take a while...
Successfully installed libv8-3.3.10.2-x86_64-linux
Successfully installed therubyracer-0.9.9
2 gems installed
Installing ri documentation for libv8-3.3.10.2-x86_64-linux...
Installing ri documentation for therubyracer-0.9.9...
Installing RDoc documentation for libv8-3.3.10.2-x86_64-linux...
Installing RDoc documentation for therubyracer-0.9.9...

$ sudo gem install 'libv8'
Fetching: libv8-3.3.10.2-x86-linux.gem (100%)
Successfully installed libv8-3.3.10.2-x86-linux
1 gem installed
Installing ri documentation for libv8-3.3.10.2-x86-linux...
Installing RDoc documentation for libv8-3.3.10.2-x86-linux...


Añadir las siguientes líneas al archivo ~/code/ruby/weblog/config/boot.rb:

$ cd ~/code/ruby/weblog/config
$ vim boot.rb

 require 'rubygems'
 require 'execjs'
 require 'v8'

Iniciar el servidor:

$ cd ~/code/ruby/weblog
$ rails server
=> Booting WEBrick
=> Rails 3.1.1 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2011-11-13 16:50:49] INFO  WEBrick 1.3.1
[2011-11-13 16:50:49] INFO  ruby 1.8.7 (2011-06-30) [x86_64-linux]
[2011-11-13 16:50:49] INFO  WEBrick::HTTPServer#start: pid=10759 port=3000


Abrir firefox y teclear:
http://localhost:3000

Instalar jruby:
echo ">=dev-util/jay-1.1.1-r2 java" >> /etc/portage/package.use

# emerge -av jruby
These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild  N     ] dev-java/javatoolkit-0.3.0-r6  17 kB
[ebuild  N     ] dev-java/ant-core-1.8.1  USE="-doc -source" 5,740 kB
[ebuild  N     ] dev-java/ant-nodeps-1.8.1  0 kB
[ebuild  N     ] dev-java/jcodings-1.0.4  USE="-source" 89 kB
[ebuild  N     ] dev-java/xml-commons-external-1.3.04  USE="-doc -source" 645 kB
[ebuild  N     ] dev-java/joda-time-1.6  USE="-doc -examples -source -test" 1,242 kB
[ebuild  N     ] dev-java/constantine-0.7  USE="-source -test" 65 kB
[ebuild  N     ] dev-java/bcel-5.2-r2  USE="-doc -findbugs -source" 256 kB
[ebuild   R    ] dev-util/jay-1.1.1-r2  USE="java* -mono" 0 kB
[ebuild  N     ] dev-java/jline-1.0  USE="-source -test" 453 kB
[ebuild  N     ] dev-java/javacup-0.11a_beta20060608  USE="-doc -source" 280 kB
[ebuild  N     ] dev-java/xjavac-20110814  3 kB
[ebuild  N     ] dev-java/xml-commons-resolver-1.2  USE="-doc -source" 257 kB
[ebuild  N     ] dev-java/touchgraph-graphlayout-1.22  USE="-source" 199 kB
[ebuild  N     ] dev-java/jgraph-5.12.0.4  USE="-doc -examples -source" 3,380 kB
[ebuild  N     ] dev-java/junit-3.8.2-r1  USE="-doc -source" 451 kB
[ebuild  N     ] dev-java/java-getopt-1.0.13  USE="-doc -source" 45 kB
[ebuild  N     ] dev-java/log4j-1.2.16  USE="-doc -javamail -jms -jmx -source" 2,727 kB
[ebuild  N     ] dev-java/jakarta-oro-2.0.8-r2  USE="-doc -examples -source" 338 kB
[ebuild  N     ] dev-java/commons-logging-1.1.1  USE="-avalon-framework -avalon-logkit -doc -log4j -servletapi -source -test" 187 kB
[ebuild  N     ] dev-java/bytelist-1.0.6  USE="-source -test" 15 kB
[ebuild  N     ] dev-java/jffi-1.0.0  USE="-source -test" 1,590 kB
[ebuild  N     ] dev-java/xalan-serializer-2.7.1  USE="-doc -source" 6,138 kB
[ebuild  N     ] dev-java/nailgun-0.7.1  USE="-doc -source -test" 1,455 kB
[ebuild  N     ] dev-java/jgrapht-0.7.3  USE="-doc -source -test" 1,113 kB
[ebuild  N     ] dev-java/jnr-x86asm-0.1  USE="-doc -source" 82 kB
[ebuild  N     ] dev-java/jvyamlb-0.2.5  USE="-source -test" 1,727 kB
[ebuild  N     ] dev-java/xerces-2.9.1  USE="-doc -examples -source" 1,672 kB
[ebuild  N     ] dev-java/xalan-2.7.1  USE="-doc -source" 0 kB
[ebuild  N     ] dev-java/bsf-2.4.0-r1  USE="-doc -examples -javascript -python -source -tcl" 293 kB
[ebuild  N     ] dev-java/ant-owanttask-1.1-r12  10 kB
[ebuild  N     ] dev-java/asm-3.2  USE="-doc -source" 832 kB
[ebuild  N     ] dev-java/jaffl-0.5.1  USE="-doc -source -test" 546 kB
[ebuild  N     ] dev-java/joni-1.1.4  USE="-source" 118 kB
[ebuild  N     ] dev-java/jnr-posix-1.1.4  USE="-source -test" 191 kB
[ebuild  N     ] dev-java/jnr-netdb-1.0.1  USE="-doc -source -test" 656 kB
[ebuild  N     ] dev-java/jruby-1.5.6  USE="ssl -bsf -doc -source -test" 10,905 kB
[ebuild   R    ] dev-ruby/rubygems-1.3.7-r1  USE="-doc -server" RUBY_TARGETS="jruby* -ree18 -ruby18*" 0 kB
[ebuild  NS    ] virtual/rubygems-2 [1] RUBY_TARGETS="(jruby)" 0 kB
[ebuild  N     ] dev-ruby/bouncy-castle-java-1.5.0146.1  USE="-test" RUBY_TARGETS="jruby" 1,945 kB
[ebuild  N     ] dev-ruby/jruby-openssl-0.7.4  USE="-doc -test" RUBY_TARGETS="(jruby)" 609 kB

Total: 41 packages (38 new, 1 in new slot, 2 reinstalls), Size of downloads: 46,250 kB

Would you like to merge these packages? [Yes/No] y

MySQL para Ruby:

# emerge -av dev-ruby/dbd-mysql

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild  N     ] dev-ruby/mysql-ruby-2.8.2  USE="-test" RUBY_TARGETS="ruby18 -ree18" 32 kB
[ebuild  N     ] dev-ruby/deprecated-2.0.1-r1  USE="-test" RUBY_TARGETS="ruby18 -jruby (-ruby19)" 13 kB
[ebuild  N     ] dev-ruby/ruby-postgres-0.7.9.20080128-r2  USE="-test" RUBY_TARGETS="ruby18 -ree18" 32 kB
[ebuild  N     ] dev-ruby/ruby-dbi-0.4.3  USE="mysql postgres sqlite -examples -odbc -sqlite3 -test" RUBY_TARGETS="ruby18" 80 kB
[ebuild  N     ] dev-ruby/dbd-mysql-0.4.4  USE="-test" RUBY_TARGETS="ruby18" 56 kB
[ebuild  N     ] dev-ruby/dbd-pg-0.3.8  USE="-test" 64 kB
[ebuild  N     ] dev-ruby/dbd-sqlite-0.1.2  USE="-test" 52 kB

Total: 7 packages (7 new), Size of downloads: 327 kB

Would you like to merge these packages? [Yes/No] y

>>> Verifying ebuild manifests

>>> Starting parallel fetch
....

$ sudo gem install mysql
Password: 
Building native extensions.  This could take a while...
Successfully installed mysql-2.8.1
1 gem installed
Installing ri documentation for mysql-2.8.1...
Installing RDoc documentation for mysql-2.8.1..

Iniciar un nuevo proyecto Ruby on Rails utilizando MysQL:
$ rails new webservmysql -d mysql
 create  
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
...

$ cd webservmysl

En otra terminal:
MySQL debe estar iniciado:
# /etc/initd/mysql start

$ mysql -u root -p
Enter password:




mysql> CREATE DATABASE webservmysql;
Query OK, 1 row affected (0.00 sec)

mysql> use webservmysql;
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> show tables;

+------------------------+
| Tables_in_webservmysql |
+------------------------+
| schema_migrations      |
+------------------------+
1 row in set (0.00 sec)


El archivo database.yml se verá así:
carlos@hypatia ~/code/webservmysql/config $ vi database.yml


Crear un modelo y migrar la base de datos (creará la tabla Persona):

carlos@hypatia ~/code/webservmysql $ rails g model Persona nombre:string      invoke  active_record
      create    db/migrate/20111127091342_create_personas.rb
      create    app/models/persona.rb
      invoke    test_unit
      create      test/unit/persona_test.rb
      create      test/fixtures/personas.yml
carlos@hypatia ~/code/webservmysql $ rake db:migrate
==  CreatePersonas: migrating =================================================
-- create_table(:personas)
   -> 1.6301s
==  CreatePersonas: migrated (1.6303s) ========================================

Ahora si volvemos la terminal anterior y nuevamente hacemos un show tables veremos la tabla persona ya creada:

mysql> show tables;
+------------------------+
| Tables_in_webservmysql |
+------------------------+
| personas               |
| schema_migrations      |
+------------------------+
2 rows in set (0.00 sec)





Linux es genial!.

sábado, 12 de noviembre de 2011

Mover usr a otra particion

Mover /usr a una partición independiente. Todo el proceso lo he realizado en un terminal desde gentoo.
Las etiquetas permiten la identificación de las particiones:

# tune2fs -L usr_gentoo /dev/sda8
tune2fs 1.41.14 (22-Dec-2010)

Sacando información del disco duro, hay varias maneras de conseguirlo:
# blkid
/dev/sda1: LABEL="boot" UUID="3bb6187d-1918-4512-96f3-2ed42fc50c19" TYPE="ext2"
/dev/sda2: LABEL="squeeze" UUID="33b01f6e-1e74-4225-84b5-a66c568b38aa" SEC_TYPE="ext2" TYPE="ext3"
/dev/sda3: LABEL="gentoo" UUID="86fd2e13-119f-4efb-aedd-aa5ebd7c77a8" TYPE="ext4"
/dev/sda5: UUID="afa7c31e-c8bf-41f5-a340-78da2c230362" TYPE="swap"
/dev/sda6: LABEL="squeeze_home" UUID="cd3805eb-25b6-4ba4-b99e-7575407f05be" SEC_TYPE="ext2" TYPE="ext3"
/dev/sda7: LABEL="data" UUID="1ddcb07d-b322-4039-837b-48f3daef1426" TYPE="ext3"
/dev/sda8: LABEL="usr_gentoo" UUID="18536501-37ee-4f40-a362-2d9173c43856" SEC_TYPE="ext2" TYPE="ext3"
/dev/sda9: UUID="a7163b55-b4c6-4e31-bf2b-8aeb6a34bdca" SEC_TYPE="ext2" TYPE="ext3"
/dev/sda10: LABEL="home_gentoo" UUID="bff4d21b-d8cb-422d-8c91-b35c4e43ffbf" TYPE="ext3"
/dev/sda11: LABEL="portage" UUID="a0c335fb-2c70-43d3-9138-ff638e360f36" TYPE="reiserfs"

# ls -l /dev/disk/by-label/
total 0
lrwxrwxrwx 1 root root 10 Nov 12 18:54 boot -> ../../sda1
lrwxrwxrwx 1 root root 10 Nov 12 18:29 data -> ../../sda7
lrwxrwxrwx 1 root root 10 Nov 12 18:29 gentoo -> ../../sda3
lrwxrwxrwx 1 root root 11 Nov 12 18:29 home_gentoo -> ../../sda10
lrwxrwxrwx 1 root root 11 Nov 12 18:29 portage -> ../../sda11
lrwxrwxrwx 1 root root 10 Nov 12 18:54 squeeze -> ../../sda2
lrwxrwxrwx 1 root root 10 Nov 12 18:54 squeeze_home -> ../../sda6
lrwxrwxrwx 1 root root 10 Nov 12 18:36 usr_gentoo -> ../../sda8

# fdisk -l

Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders, total 976773168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x0000bac9

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      210943      104448   83  Linux
/dev/sda2          210944    51410943    25600000   83  Linux
/dev/sda3        51410944   112850943    30720000   83  Linux
/dev/sda4       112852990   976771071   431959041    5  Extended
Partition 4 does not start on physical sector boundary.
/dev/sda5       112855040   117049343     2097152   82  Linux swap / Solaris
/dev/sda6       117051392   137531391    10240000   83  Linux
/dev/sda7       137533440   485693439   174080000   83  Linux
/dev/sda8       485695488   527927295    21115904   83  Linux
/dev/sda9       527929344   550371327    11220992   83  Linux
/dev/sda10      550373376   574251007    11938816   83  Linux
/dev/sda11      574259553   606453749    16097098+  83  Linux
Partition 11 does not start on physical sector boundary.

# cd /
# mkdir usr_nuevo
# mount -v -t ext3 /dev/sda8 /usr_nuevo/
# rm -rf /usr_nuevo/*
# cp -dpR /usr/* /usr_nuevo/
# umount /usr_nuevo
# mv /usr /usr_antiguo
# mkdir /usr
# mount /dev/sda8 /usr
# mount -a

Agregar entrada a /etc/fstab:
# vi /etc/fstab
# /etc/fstab: static file system information.
#
# noatime turns off atimes for increased performance (atimes normally aren't
# needed; notail increases performance of ReiserFS (at the expense of storage
# efficiency).  It's safe to drop the noatime options if you want and to
# switch between notail / tail freely.
#
# The root filesystem should have a pass number of either 0 or 1.
# All other filesystems should have a pass number of 0 or greater than 1.
#
# See the manpage fstab(5) for more information.
#
#                                          

 # NOTE: If your BOOT partition is ReiserFS, add the notail option to opts.
/dev/sda1     /boot          ext2       noauto              1 2
/dev/sda3     /              ext4       noatime             1 1
/dev/sda5     none           swap       sw                  0 0
/dev/sda8     /usr           ext3       auto,noatime        0 1
/dev/sda10    /home          ext3       defaults,noatime    0 2
/dev/sda11    /usr/portage   reiserfs   defaults           0 0
/dev/sda7     /media/data    ext3       defaults,noatime   0 0
/dev/cdrom    /mnt/cdrom     auto       noauto,ro           0 0
#/dev/fd0     /mnt/floppy    auto       noauto             0 0

# glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for
# POSIX shared memory (shm_open, shm_unlink).
# (tmpfs is a dynamically expandable/shrinkable ramdisk, and will
#  use almost no memory if not populated with files)
 shm          /dev/shm    tmpfs     nodev,nosuid,noexec     0 0


Comprobando:
# mount
rootfs on / type rootfs (rw)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)
udev on /dev type tmpfs (rw,nosuid,relatime,size=10240k,mode=755)
devpts on /dev/pts type devpts (rw,relatime,mode=600,ptmxmode=000)
/dev/sda3 on / type ext4 (rw,noatime,commit=0)
rc-svcdir on /lib64/rc/init.d type tmpfs (rw,nosuid,nodev,noexec,relatime,size=1024k,mode=755)
fusectl on /sys/fs/fuse/connections type fusectl (rw,relatime)
shm on /dev/shm type tmpfs (rw,nosuid,nodev,noexec,relatime)
/dev/sda8 on /usr type ext3 (rw,noatime,commit=0)
/dev/sda10 on /home type ext3 (rw,noatime,commit=0)
/dev/sda11 on /usr/portage type reiserfs (rw)
/dev/sda7 on /media/data type ext3 (rw,noatime,commit=0)
usbfs on /proc/bus/usb type usbfs (rw,noexec,nosuid,devmode=0664,devgid=85)

Es el momento de reiniciar el sistema. He reiniciado y todo funciona perfectamente.
Puede borrar el directorio /usr_antiguo.
# rm -rf /usr_antiguo

Linux es genial!.

jueves, 10 de noviembre de 2011

DNSChanger


El Troyano DNSChanger, es un archivo de pequeño tamaño (1.5 Kb aprox.) que como su nombre indica fue creado para cambiar los DNS (Domain Name System – Sistema de Nombres de Dominio-) de nuestro PC, y de ese modo redirigir nuestras búsquedas a sitios desde los cuales se puede infectar nuestro ordenador o nuestra red, de malware, realizar phishing, etc. Los servidores DNS traducen el nombre de la dirección web que se teclea en el navegador (por ejemplo: 'www.gentoo.org' a la dirección IP, numérica = 89.16.167.134.

DNSChanger afecta tanto a Windows como a Mac - puede alterar la configuración DNS en máquinas con los sistemas operativos mencionados.

DNSChanger envía a los usuarios desprevenidos a servidores piratas controlados por delincuentes informáticos, que les permite manipular la actividad de los usuarios.

Según el código malicioso que el troyano contenga.  También abre ventanas emergentes (PopUps) y relentiza los sistemas de la familia de Microsoft.

De esta manera es creada una inmensa red de ordenadores zombis (botnet) dedicados a la estafa en la Red..

Linux es genial!.

domingo, 6 de noviembre de 2011

PostgreSQL


Instalar PostgreSQL, phppgadmin en Gentoo.

Fuente: http://www.gentoo.org/doc/es/postgres-howto.xml
http://www.codigolibre.org


En mi sistema gentoo-linux actual tengo instalado el servidor web apache, el gestor de base de datos mysql y php. Instalar postgresql y phppgadmin, crear la base de datos sacademico y ejecutar un script para importar la estructura de las tablas y los datos, así lo hice:

Añadir al fichero /etc/make.conf la use postgres
# emerge -av postgresql-server

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild   N   ] dev-db/postgresql-server-9.0.5  USE="nls pam xml -doc -perl -pg_legacytimestamp -python (-selinux) -tcl -uuid" LINGUAS="en es -af -cs -de -fa -fr -hr -hu -it -ko -nb -pl -pt_BR -ro -ru -sk -sl -sv -tr -zh_CN -zh_TW" 0 kB

Total: 1 package (1 install), Size of downloads: 14,015 kB

Would you like to merge these packages? [Yes/No]

Editar el fichero /etc/conf.d/postgresql-9.0, para el idioma castellano PG_INITDB_OPTS="--locale=es_ES.UTF-8":
# vim /etc/conf.d/postgresql-9.0

# Location of configuration files
 PGDATA="/etc/postgresql-9.0/"

 # Where the data directory is located/to be created
 DATA_DIR="/var/lib/postgresql/9.0/data"

 # Additional options to pass to initdb.
 # See 'man initdb' for available options.
 PG_INITDB_OPTS="--locale=en_US.UTF-8"

Crear el cluster de base de datos y almacenar los ficheros relacionados con el servidor en PGDATA y DATA_DIR.
# emerge --config dev-db/postgresql-server:9.0

Cambiando 'trust' a 'password' para las conexiones a localhost
vim /etc/postgresql-9.0/pg_hba.conf
# "local" is for Unix domain socket connections only
 local   all             all                        trust
 # IPv4 local connections:
 host    all             all       127.0.0.1/32     trust
 # IPv6 local connections:
host    all             all        ::1/128          trust

Agregar usuario al grupo postgres:
# gpasswd -a carlos postgres

Iniciar el servidor
# /etc/init.d/postgresql-9.0 start
 * Caching service dependencies ...           [ ok ]
 * Starting PostgreSQL ...                    [ ok ]

Abrir una conexión al servidor y cambiar la contraseña:
# psql -U postgres
psql (9.0.3)
Type "help" for help.

postgres=# \password
Enter new password:
Enter it again:
postgres=# \q

Crear un usuario y su password:
# su - postgres
 psql -U postgres
postgres@hypatia ~ $ createuser sacademico -Ws

Clave: kikla
postgres@hypatia ~ $ createdb sacademico


Enlace al script:

enlace_descarga_dhypatia.sql

*Insertar el script bdhypatia.sql:
postgres@hypatia:~$psql sacademico < bdhypatia.sql -U postgres

# /etc/init.d/postgresql-9.0 reload
postgresql-9.0 | * Reloading PostgreSQL configuration ...  [ ok ]

Iniciar postgresql con el sistema:
# rc-update add postgresql-9.0 default
 * service postgresql-9.0 added to runlevel default

Instalar phppgadmin

# emerge -av phppgadmin
Recompila php con soporte postgres e instala phppgadmin.

Para poder logearnos via navegador (/http://localhost/phppgadmin y no recibir un mensaje login failed será necesario editar el fichero /var/www/localhost/htdocs/phppgadmin/conf/config.inc.php y agregar 'localhost':
# vim /var/www/localhost/htdocs/phppgadmin/conf/config.inc.php

// use 'localhost' for TCP/IP connection on this computer
   $conf['servers'][0]['host'] = 'localhost';

# /etc/init.d/postgresql-9.0 reload



Linux es genial!.

viernes, 4 de noviembre de 2011

Fortune


Instalar fortune en Gentoo

# emerge -av fortune-mod

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild  N     ] games-misc/fortune-mod-1.99.1-r2  USE="-offensive" 1,770 kB

Total: 1 package (1 new), Size of downloads: 1,770 kB

Would you like to merge these packages? [Yes/No]

Utilizaremos este codigo para llamar fortune desde /etc/bash/bashrc. Agregar al final del archivo:
# vim /etc/bash/bashrc

if [ $TERM != "dumb" ]; then
 fortune
fi

Al abrir una terminal comprobamos el resultado:

Instalar FBReader.

FBReader es un e-book reader. Soporta los principales formatos e-book y nos permitirá leer ebook's desde nuestro pc. Para Gentoo y gnome:
# echo "app-text/fbreader gtk -debug -qt4"
# emerge -av fbreader

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild   R    ] app-text/fbreader-0.12.10  USE="gtk -debug -qt4" 0 kB

Total: 1 package (1 install), Size of downloads: 2,383 kB
Would you like to merge these packages? [Yes/No] y


Linux es genial!.

f.lux monitor

xflux es una aplicación multiplataforma que cambia la luminosidad de la pantalla de tu monitor cada cierto tiempo basándose en las coordenadas del lugar donde vives, (posición global), conociendo en cada momento si es de dia o de noche. Para las personas que pasamos muchas horas frente al ordenador significa cuidar nuestra vista y reducir considerablemente el cansancio producido por el uso intensivo, ajustando el brillo del monitor.

En gentoo x86_64 se necesitan las librerías de 32 bits:

[ebuild  N     ] app-emulation/emul-linux-x86-xlibs-20120127  USE="opengl -development" 2,414 kB
[ebuild  N     ] app-emulation/emul-linux-x86-opengl-20120127  USE="-development" 35,476 kB

Total: 2 packages (2 new), Size of downloads: 37,889 kB

Would you like to merge these packages? [Yes/No] y


Para conocer las coordenadas de su ciudad puede usar la herramienta que ha implementado la página oficial del programa f.lux:


Para Gentoo, descargar el programa desde la página de sus creadores:
http://stereopsis.com/flux/linux.html

Desplazarse a la parte inferior:

Command-line version (for older distros)
The command-line version remains available here: xflux.tgx

$ cd Downloads
$ tar -xzvf xflux.tgz
$ su
password:

Mover xflux a /usr/bin
# mv xflux /usr/bin/

Activamos el programa como usuario normal en mi caso utilizando las coordenadas 41.387917, 2.1699187:
# exit
$ xflux -l 41.387917, 2.1699187

Agregar a las aplicaciones que se inician con el sistema:


Se creará el archivo xflux.desktop en ~/.config/autostart/
$ cat ~/.config/autostart/xflux.desktop

[Desktop Entry]
Type=Application
Exec=xflux -l 41.387917, 2.1699187
Hidden=false
X-GNOME-Autostart-enabled=true
Name[en_US]=xflux
Name=xflux
Comment[en_US]=Ajustar brillo pantalla
Comment=Ajustar brillo pantalla


En los antiguos monitores ctr hacíamos algo parecido, con el comando:
$ xgamma -gamma x.x

Es similar a Brightness applet (mini aplicación de brillo).

Actualmente hay monitores que reaccionan a los niveles de luz del recinto donde se encuentran, si posees un monitor con estas características no es necesario xflux ya que estaria duplicando funciones.

Linux es genial!

miércoles, 19 de octubre de 2011

Apache2 Mysql Php PhpMyadmin

Fuentes y créditos:
http://www.gentoo.org/proj/en/php/php-installing.xml
http://www.igorgarcia.es/blog/activar-relaciones-phpmyadmin
http://wiki.ballano.net/index.php/Error_Blowfish_phpmyadmin

Después de instalar Apache2, Mysql, Php y PhpMyAdmin en Gentoo he realizado los cambios siguientes para que todo funcione como un reloj:

Iniciando servicios:
carlos@hypatia ~ $ su
Password:
# /etc/init.d/apache2 start
 * Starting apache2 ...                                           [ ok ]
# /etc/init.d/mysql start
 * Starting  ...
 * Starting  (/etc/mysql/my.cnf)                             [ ok ]


Abrir con un editor httpd.conf y agregar ServerName localhost:

# vim /etc/apache2/httpd.conf
ServerName localhost

Configurar /var/www/localhost/htdocs/phpmyadmin/config.inc.php partiendo el archivo /var/www/localhost/htdocs/phpmyadmin/config.sample.inc.php:

cp /var/www/localhost/htdocs/phpmyadmin/config.sample.inc.php /var/www/localhost/htdocs/phpmyadmin/config.inc.php

Agregar -D php5 al archivo /etc/conf.d/apache2
# vi /etc/conf.d/apache2

APACHE2_OPTS="-D DEFAULT_VHOST -D INFO -D SSL -D SSL_DEFAULT_VHOST -D LANGUAGE -D PHP5"

PhpMyAdmin incluye opciones para relacionar tablas que deben ser activadas, por esto al clicar sobre el boton operaciones en la basedatos aparece el error, Las opciones adicionales para trabajar con tablas vinculadas fueron desactivadas. Para saber porqué, haga clic aqui, y veremos algo como esto:
localhost
$cfg['Servers'][$i]['pmadb'] ... OK
$cfg['Servers'][$i]['relation'] ... no recibió el OK [ Documentación ]
Opciones de relación general: Deshabilitado

$cfg['Servers'][$i]['table_info'] ... no recibió el OK [ Documentación ]
Mostrar las opciones: Deshabilitado

$cfg['Servers'][$i]['table_coords'] ... no recibió el OK [ Documentación ]
$cfg['Servers'][$i]['pdf_pages'] ... no recibió el OK [ Documentación ]
Creación de los PDF: Deshabilitado

$cfg['Servers'][$i]['column_info'] ... no recibió el OK [ Documentación ]
Mostrando los comentarios de la columna: Deshabilitado
Transformación del navegador: Deshabilitado

$cfg['Servers'][$i]['bookmarktable'] ... no recibió el OK [ Documentación ]
Consulta guardada en favoritos: Deshabilitado

$cfg['Servers'][$i]['history'] ... no recibió el OK [ Documentación ]
Historial-SQL: Deshabilitado

$cfg['Servers'][$i]['designer_coords'] ... no recibió el OK [ Documentación ]
Diseñador: Deshabilitado

$cfg['Servers'][$i]['tracking'] ... no recibió el OK [ Documentación ]
Seguimiento: Deshabilitado

$cfg['Servers'][$i]['userconfig'] ... no recibió el OK [ Documentación ]
Preferencias de usuario: Deshabilitado

1.- Desde la pestaña importar de phpmyadmin buscar (browser), el archivo
/var/www/localhost/htdocs/phpmyadmin/scripts/create_tables.sql clic en continuar para ejecutarlo:

La importación se ejecutó exitosamente, se ejecutaron 12 consultas. (create_tables.sql)
El mensaje anterior nos confirma el exito de la consulta.

2.- Editar el archivo config.inc.php y descomentar las siguientes líneas:

# vi /var/www/localhost/htdocs/phpmyadmin/config.inc.php

  /* Authentication type */
  $cfg['Servers'][$i]['auth_type'] = 'http';
  /* Server parameters */
  $cfg['Servers'][$i]['host'] = 'localhost';
  $cfg['Servers'][$i]['connect_type'] = 'tcp';
  $cfg['Servers'][$i]['compress'] = false;
  /* Select mysqli if your server has it */
  $cfg['Servers'][$i]['extension'] = 'mysql';
  $cfg['Servers'][$i]['AllowNoPassword'] = false;

  /*
   * phpMyAdmin configuration storage settings.
   */

  /* User used to manipulate with storage */
   $cfg['Servers'][$i]['controluser'] = 'pma';
   $cfg['Servers'][$i]['controlpass'] = 'pmapass';

  /* Storage database and tables */
   $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
   $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
   $cfg['Servers'][$i]['relation'] = 'pma_relation';
   $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
   $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
   $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
   $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
   $cfg['Servers'][$i]['history'] = 'pma_history';
   $cfg['Servers'][$i]['tracking'] = 'pma_tracking';
   $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
   $cfg['Servers'][$i]['userconfig'] = 'pma_userconfig';
  /* Contrib / Swekey authentication */

Cambiar en el mismo archivo cookies por http:
# vi /var/www/localhost/htdocs/phpmyadmin/config.inc.php
$cfg['Servers'][$i]['auth_type'] = 'cookies':
$cfg['Servers'][$i]['auth_type'] = 'http':

Guardar y salir.

3.- Crear un usuario MySQL para utilizar la relación entre tablas (que será el que indicamos anteriormente como controluser con la contraseña indicada en controlpass) y asignarle los correspondientes permisos:
Desde la terminal:

# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 112
Server version: 5.1.56-log Gentoo Linux mysql-5.1.56

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

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

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| phpmyadmin         |
| test               |
+--------------------+
4 rows in set (0.09 sec)

mysql> use phpmyadmin;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------+
| Tables_in_phpmyadmin |
+----------------------+
| pma_bookmark         |
| pma_column_info      |
| pma_designer_coords  |
| pma_history          |
| pma_pdf_pages        |
| pma_relation         |
| pma_table_coords     |
| pma_table_info       |
| pma_tracking         |
| pma_userconfig       |
+----------------------+
10 rows in set (0.00 sec)

mysql> GRANT USAGE ON mysql.* TO 'pma'@'localhost' IDENTIFIED BY 'pmapass';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SELECT (Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv) ON mysql.user TO 'pma'@'localhost';
Query OK, 0 rows affected (0.02 sec)

mysql> GRANT SELECT ON mysql.db TO 'pma'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SELECT ON mysql.host TO 'pma'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SELECT (Host, Db, User, Table_name, Table_priv, Column_priv) ON mysql.tables_priv TO 'pma'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye

Reiniciar apache y acceder al PMA.

Salir de la terminal, y comprobar desde phpmyadmin los privilegios del usuario que acaba de crear (pma):



Si dejamos la autenticación mediante cookies y al cargar la páqina principal de phpmyadmin puede leerse:
El archivo de configuración ahora necesita salvoconducto (una frase secreta) (blowfish_secret). Debemos modificar el siguiente fichero
/var/www/localhost/htdocs/phpmyadmin/config.inc.php y añadir una clave en:

$cfg['blowfish_secret'] = 'palabra_clave'


Problemas:


El código fuente php se está mostrando!:
La razón más común es que short_open_tags está desactivado por defecto. Si el código hace uso de etiquetas cortas,

# vi /etc/php/apache2-php5.3/php.ini

short_open_tag = on

Reiniciar apache
# /etc/init.d/apache2 restart
 * Stopping apache2 ...                                   [ ok ]
 * Starting apache2 ...                                     [ ok ]



Linux es genial!.

viernes, 14 de octubre de 2011

Migrando a OpenRC

SysV init
SysV init scripts (/etc/init.d), usados para el control de inicio y apagado del sistema. El sistema de inicio System V controla el arranque de los programas en el instante de inicio de la máquina.
OpenRC es un sistema de arranque (rc system) con gestión de dependencias que trabaja con cualquier init proporcionado por el sistema, normalmente /sbin/init.

Originalmente el sistema rc de Gentoo formaba parte de baselayout 1 y estaba escrito completamente en bash. Esto conlleva varias limitaciones. Por ejemplo, ciertas llamadas al sistema necesitan ser accedidas durante el arranque, requiriendo agregar llamadas en C. Estas llamadas eran enlazadas estáticamente, aumentando notablemente el tamaño del sistema rc a lo largo del tiempo.

Migrando una máquina con procesador Intel core 2 duo x86_64 T5750 2.00GHz. Intel Mobile GM965/GL960 Integrated Graphics Controller.

Instalar cryptsetup
# emerge -av cryptsetup
Calculating dependencies... done!
[ebuild   R    ] dev-libs/libgcrypt-1.4.6  USE="static-libs*" 0 kB
[ebuild   R    ] dev-libs/popt-1.16-r1  USE="nls static-libs*" 0 kB
[ebuild   R    ] dev-libs/libgpg-error-1.10  USE="nls static-libs* -common-lisp" 0 kB
[ebuild  N     ] sys-fs/cryptsetup-1.1.3-r3  USE="nls -dynamic (-selinux)" 488 kB

Agrego al archivo /etc/make.conf las use "nls static-libs"
# vim /etc/make.conf
USE="... nls static-libs .."

# dispatch-conf
# revdep-rebuild
# emerge -v udev

# dispatch-conf

No es necesario recompilar hal, actualmente no se utiliza.

# emerge -v sysvinit
# dispatch-conf

# emerge -v openrc

 * Please read the migration guide available at:
 * http://www.gentoo.org/doc/en/openrc-migration.xml
>>> Auto-cleaning packages...

>>> No outdated packages were found on your system.

 * GNU info directory index is up-to-date.

 * IMPORTANT: 15 config files in '/etc' need updating.
 * See the CONFIGURATION FILES section of the emerge
 * man page to learn how to update config files.

Actualizo los 15 ficheros en /etc examinando uno por uno, son estos:

 /etc/conf.d/bootmisc          
 /etc/conf.d/consolefont       
 /etc/init.d/consolefont       
 /etc/conf.d/hostname          
 /etc/hosts                    
 /etc/conf.d/hwclock           
 /etc/conf.d/keymaps           
 /etc/init.d/keymaps           
 /etc/conf.d/modules           
 /etc/profile                  
 /etc/protocols                
 /etc/rc.conf                  
 /etc/sysctl.conf              
 /etc/conf.d/urandom
 /etc/timezone

Tiene que comprobar la migración desde /etc/modules.autoload.d/kernel-2.6 a /etc/conf.d/modules. El formato es diferente.

Llegado a este punto es "Muy Importante" comprobar los servicios que arrancarán en fase boot. Los principales están presentes: root, procfs, mtab, swap y fsck:

# ls -l /etc/runlevels/boot/
total 0
lrwxrwxrwx 1 root root 21 Oct 12 20:58 alsasound -> /etc/init.d/alsasound
lrwxrwxrwx 1 root root 20 Oct 12 20:58 bootmisc -> /etc/init.d/bootmisc
lrwxrwxrwx 1 root root 23 Oct 12 20:58 consolefont -> /etc/init.d/consolefont
lrwxrwxrwx 1 root root 25 Oct 12 20:58 device-mapper -> /etc/init.d/device-mapper
lrwxrwxrwx 1 root root 16 Oct 12 20:58 fsck -> /etc/init.d/fsck
lrwxrwxrwx 1 root root 20 Oct 12 20:58 hostname -> /etc/init.d/hostname
lrwxrwxrwx 1 root root 19 Oct 12 20:58 hwclock -> /etc/init.d/hwclock
lrwxrwxrwx 1 root root 19 Oct 12 20:58 keymaps -> /etc/init.d/keymaps
lrwxrwxrwx 1 root root 22 Oct 12 20:58 localmount -> /etc/init.d/localmount
lrwxrwxrwx 1 root root 19 Oct 12 20:58 modules -> /etc/init.d/modules
lrwxrwxrwx 1 root root 16 Oct 12 20:58 mtab -> /etc/init.d/mtab
lrwxrwxrwx 1 root root 18 Oct 12 20:58 net.lo -> /etc/init.d/net.lo
lrwxrwxrwx 1 root root 18 Oct 12 20:58 procfs -> /etc/init.d/procfs
lrwxrwxrwx 1 root root 16 Oct 12 20:58 root -> /etc/init.d/root
lrwxrwxrwx 1 root root 16 Oct 12 20:58 swap -> /etc/init.d/swap
lrwxrwxrwx 1 root root 18 Oct 12 20:58 sysctl -> /etc/init.d/sysctl
lrwxrwxrwx 1 root root 24 Oct 12 20:58 termencoding -> /etc/init.d/termencoding
lrwxrwxrwx 1 root root 19 Oct 12 20:58 urandom -> /etc/init.d/urandom

Aunque es automático durante la instalación de openrc compruebo que añade udev a sysinit correctamente:

# ls -l /etc/runlevels/sysinit
total 0
lrwxrwxrwx 1 root root 17 Oct 12 20:58 devfs -> /etc/init.d/devfs
lrwxrwxrwx 1 root root 17 Oct 12 20:58 dmesg -> /etc/init.d/dmesg
lrwxrwxrwx 1 root root 16 Oct 12 20:58 udev -> /etc/init.d/udev

Para registrar todo el arranque en /var/log/rc.log
# vim /etc/rc.conf
 rc_logger="YES"

Créditos y consultas
http://www.gentoo.org/doc/es/openrc-migration.xml
http://wiki.luispa.com

Linux es genial!.

lunes, 3 de octubre de 2011

Fichero make.conf Gentoo

 Fichero /etc/make.conf optimizado.

Maquina x86_64 Intel(R) Core(TM)2 Duo CPU T5750 @ 2.00GHz GenuineIntel GNU/Linux. Dell Inspiron 1525.

These settings were set by the catalyst build script that automatically
# built this stage.
# Please consult /usr/share/portage/config/make.conf.example for a more
# detailed example.
#
USE_HARD="mmx sse sse2 sse3 ssse3"
CFLAGS="-march=core2 -O2 -pipe"
CXXFLAGS="${CFLAGS}"
#
#LDFLAGS="--as-needed"
#
ACCEPT_LICENSE="* @EULA"
#
# tres compilaciones paralelas
MAKEOPTS="-j3"
# colorear make.conf
NOCOLOR="no"
#
LINGUAS="en es"
#
# Portage
PORTDIR=/usr/portage            # ruta del arbol de portage
PKGDIR=${PORTDIR}/packages    # ruta del arbol de precompilados (GRP)
DISTDIR=${PORTDIR}/distfiles    # ruta de los fuentes
#
AUTOCLEAN="yes"
#
FEATURES="ccache"
 #
# crear fichero /usr/bin/ccache
CCACHE_SIZE="1G"
#
VIDEO_CARDS="intel vesa"
INPUT_DEVICES="udev keyboard mouse"
# These are the USE flags that were used in addition to what is provided by the
# profile used for building.
USE="-qt3 -qt4 -kde ${USE_HARD} static-libs nptl multilib ffmpeg hal dbus nls sqlite device-mapper X dvd alsa cdr gtk gnome"
#
# WARNING: Changing your CHOST is not something that should be done lightly.
# Please consult http://www.gentoo.org/doc/en/change-chost.xml before changing.
CHOST="x86_64-pc-linux-gnu"
#
GENTOO_MIRRORS="http://ftp.fi.muni.cz/pub/linux/gentoo/ \
ftp://ftp.fi.muni.cz/pub/linux/gentoo/ \
http://distfiles.gentoo.org \
http://www.ibiblio.org/pub/Linux/distributions/gentoo \
ftp://ftp.swin.edu.au/gentoo"
#
SYNC="rsync://rsync.europe.gentoo.org/gentoo-portage"


Linux es genial!.

sábado, 17 de septiembre de 2011

Unir Linux a Active Directory

Unir Linux a un dominio Active Directory

Puede parecer mucha cosa, lo que lo que en realidad lo complica es que, por diseño, Windows dificulta la interoperatibilidad. Menos mal que los heroicos programadores de Linux, como el equipo Samba, hacen posible la interoperatibilidad y las redes mixtas.

Las cuentas de usuario son gestionadas en el servidor AD, disponibles para Linux a través de winbind y pam. De manera que no es necesario crear cuentas duplicadas en su máquina Linux.

Sus cuentas locales (en la máquina Linux), son invisibles para Active Directory. Permiten acceder libremente al servidor tanto de manera remota utilizando SSH, como localmente.

Después de tener Samba depurado y en marcha, será tan sencillo como hacer una réplica para los demás hosts Linux que necesiten ser miembros de AD. Dicho esto, para hacernos una idea del escenario::

Dominio: dominio.local

- Servidor nombre: srv-dcfs-01
- Server nombre FQDN del dominio: srv-dcfs-01.dominio.local
- IP Servidor: 192.168.3.1
- IP DNS: 192.168.3.1
- IP PC Linux: 192.168.3.55
- Cliente Linux nombre: maquina-01


En una red Windows gestionada por un dominio AD puede agregar hosts Linux que puedan acceder a los hosts Windows. Lo que quiere es que los equipos Linux sean auténticos mienbros del dominio y manejarlos como cualquier otro objeto AD, tener una entrada unificada para todos los hosts y gestionar usuarios Linux desde AD. Tiene un KDC Kerberos y su DNS en orden.

Paquetes necesarios. Hará falta tener instalados todos los paquetes cliente de Samba, Winbind y Kerberos y compilar en Samba soporte para Kerberos, LDAP, Active Directory y Winbind. Aquí está todo lo que necesita:

Samba 3.0.20 o superior
MIT kerberos 1.4 o superior
OpenLDAP
Winbind 3.0.20 o superior (forma parte de Samba pero pueden estar en distintos paquetes)

Soporte para los compilados en Samba:
Kerberos
LDAP
Winbind
Active Directory

Debian, Ubuntu, mantiene actualizados los binarios además de incluir las opciones necesarias. Es decir que está a un aptitude install.

Samba necesita sambacommon, samba-doc, smbclient y winbind.

Que versión de samba tengo instalada?

$ /usr/sbin/smbd --version
Version 3.5.8
$ /usr/sbin/winbindd --version
Version 3.5.8

Necesitamos los paquetes clientes krb5-config, krb5-doc, krb5-kdc, krb5-user, ldap-utils, ldapscripts, libldap2 y slapd.

Si quiere averiguar todas las opciones compiladas:
$ /usr/sbin/smbd -b | grep -i ldap
HAVE_KRB5_H
HAVE_LDAP
HAVE_LDAP_DOMAIN2HOSTLIST

$ /usr/sbin/smbd -b | grep -i krb5
HAVE_KRB5_H
HAVE_ADDRTYPE_IN_KRB5_ADDRESS
HAVE_KRB5

$ /usr/sbin/smbd -b | grep -i ads
WITH_ADS
WITH_ADS

$ /usr/sbin/smbd -b | grep -i winbind
WITH_WINBIND
WITH_WINBIND

También necesita cuenta(s) para usuario(s) y equipo(s) Linux en AD:

- Tener un servidor NTP (Protocolo de señales horarias de red) disponible para su LAN y los hosts sincronizados, (si, como las pelis de detectives "sincronizemos los relojes").

- Borrar todos los ficheros .tdb si existen y los localizados en /var/lib/samba. Si desea haga copia de seguridad.

- Detenga los demonios Samba y Winbind
# /etc/init.d/smbd stop
# /etc/init.d/winbind stop

- Crear un grupo Linux para las cuentas de equipo.
# groupadd machines

- Configurar /etc/hosts
Agregar
192.168.3.1 srv-dcfs-01.dominio.local srv-dcfs-01
192.168.3.55 maquina-01.dominio.local maquina-01

- Configurar /etc/resolv.conf
#/etc/resolv.conf
domain dominio.local
search dominio.local
nameserver 192.168.3.1
nameserver 192.168.3.2

Ahora pruebe a conectar con el KDC. kinit es parte del paquete kstart es decir que si no lo tiene tendrá que instalarlo. Fíjese que dominio.local debe estar en "mayusculas". En mi caso he utilizado la cuenta Administrator (en inglés), porque la instalación está en inglés:
# kinit Administrator@DOMINIO.LOCAL
Password for Administrator@DOMINIO.LOCAL

- Configurar Samba.

/etc/samba/smb.conf
#
[global]
workgroup = dominio
netbios name = debian-01
realm = DOMINIO.LOCAL
server string = Samba server one
security = ADS
encrypt passwords = yes

idmap uid = 10000-20000
idmap gid = 10000-20000
winbind use default domain = yes
winbind enum users = yes
winbind enum groups = yes
winbind separator = +

log file = /var/log/samba/log
log level = 2
max log size = 50
hosts allow = 192.168.3.

[homes]
comment = Home Directories
valid users =%S
read only = No
browseable = No

- Configurar NSS.

#/etc/nssswitch.conf

passwd:       compat files winbind
group:          compat files winbind
shadow:       compat files

hosts:          files dns winbind

En este momento inicie Samba y Winbind. Una el pc Linux al dominio Active Directory y establezca una Machine Trust Account. con la cuenta de Administrator del servidor AD. Vamos al servidor AD de Windows (srv-dcfs-01).
Inicio, Ejecutar, cmd
C:>netdom add maquina-01

De vuelta a la máquina Linux:
# net ads join -U Administrator
Enter Administrator's password:
Using short domain name -- DOMAIN
Joined 'MAQUINA-01' to realm 'DOMINIO.LOCAL'

Debería haber una nueva cuenta de equipo con el nombre NetBIOS de su máquina Linux en Active Directory, en la carpeta equipos (o computer).

Comprobar la versión de Kerberos:

$ dpkg -l | grep krb5
ii  krb5-admin-server  1.6.dfsg.4~beta1-5lenny6   MIT Kerberos master server (kadmind)
ii  krb5-config  1.22   Configuration files for Kerberos Version 5
ii  krb5-kdc   1.6.dfsg.4~beta1-5lenny6   MIT Kerberos key server (KDC)
ii  krb5-pkinit 1.6.dfsg.4~beta1-5lenny6   PKINIT plugin for MIT Kerberos
ii  krb5-user   1.6.dfsg.4~beta1-5lenny6   Basic programs to authenticate using MIT Kerberos
ii  libkrb53    1.6.dfsg.4~beta1-5lenny6   MIT Kerberos runtime libraries

Lista de paquetes Debian:
$ apt-cache search krb5
krb5-clients - Secure replacements for ftp, telnet and rsh using MIT Kerberos
krb5-ftpd - Secure FTP server supporting MIT Kerberos
ssh-krb5 - secure shell client and server (transitional package)
krb5-admin-server - MIT Kerberos master server (kadmind)
krb5-config - Configuration files for Kerberos Version 5
krb5-doc - Documentation for MIT Kerberos
krb5-kdc - MIT Kerberos key server (KDC)
krb5-user - Basic programs to authenticate using MIT Kerberos
libkrb5-3 - MIT Kerberos runtime libraries
libpam-krb5 - Modulo PAM para MIT Kerberos

Si es necesario instalar Kerberos y kstart
$  sudo apt-get install krb5-{admin-server,kdc} kstart

Fichero de configuración:
# /etc/krb5.conf

 [libdefaults]
default_realm = DOMINIO.LOCAL
clockskw = 300

[realms]
DOMINIO.LOCAL = {
kdc =192.168.3.1
default_domain = dominio.local
admin_server = 192.168.3.1  
}

dominio.local = {
kdc = 192.168.3.1
default_domain = dominio.local
admin_server = 192.168.3.1
}

dominio = {
kdc = 192.168.3.1
default_domain = dominio
admin_server = 192.168.3.1
}

[logging]
kdc = FILE:/var/log/krb5/krb5kdc.log
admin_server = FILE:/var/log/krb5/kadmind.log

default = SYSLOG:NOTICE:DAEMON

 [domain_realms]
.dominio = dominio
.dominio.local = dominio

[appdefaults]
pam = {
ticket_lifetime = 1d
renew_lifetime =1d
forwardable = true
proxiable = false
retain_after_close = false
minimum_uid = 0 try_first_pass = true }

Por último, hay que configurar los PAM para permitir la autenticación vía winbind. Editar los siguientes ficheros para incluir los módulos winbind y el módulo pam_mkhomedir.so
- Configurar PAM.

# cp /etc/pam.d/login /etc/pam.d/login-back

auth requisite pam_securetty.so
auth requisite pam_nologin.so
auth required pam_env.so
auth sufficient pam_winbind.so
auth required pam_unix.so nullok use_first_pass

# cp /etc/pam.d/common-account /etc/pam.d/common-account-back


account requisite pam_time.so
account sufficient pam_winbind.so
account required pam_unix.so

# cp /etc/pam.d/common-session /etc/pam.d/common-session


session required pam_unix.so
session optional pam_lastlog.so
session optional pam_motd.so
session optional pam_mail.so standard noenv
session required pam_mkhomedir.so skel=/etc/skel umask=0027


Agradecimientos especiales a:
Joel Barrio Dueñas por su desinteresado trabajo "Servidores en Linux".
A Carla Schroder por su excelente libro "Redes en Linux".


Linux es genial!.