Watching files with ruby and fssm

On GNU/Linux exists a library called inotify which does that, notifies for changes(change, create, delete) of files into a directory. Over Mac there is FSEvents, which essentially do the same as inotify, with some exceptions of course.

Now, what happened if I have 2 servers which I want to monitor for file changes?. You could say: «write one app and run on 2 servers». Yeah!, nice answer, but 1 of them is running GNU/Linux and the other one is running MacOS, so we need something like Ruby to do so.

First we install fssm(File System State Monitor) from rubygems:

gem install fssm

Maybe you need do the above as root. Next go to your favorite editor, I use Geany.

Of course, the first lines will be:

#!/usr/bin/env ruby

require 'rubygems'
require 'fssm'

The first line calls for the ruby interpreter and the next 2 loads rubygems and fssm ruby extensions.

Now go to the magic code, it’s pretty simple and easy to undestand.


FSSM.monitor("/tmp/test") do
	update do |b, r|
		puts "Someone changes the file '#{r}' into '#{b}'"
	end

	create do |b, r|
		puts "Someone creates the file '#{r}' into '#{b}'"
	end

	delete do |b, r|
		puts "Someone deletes the file '#{r}' into '#{b}'"
	end
end

The first line enters to a loop that watch for filesystem changes only into /tmp/test directory.

The second line states which actions gonna take the program if the some file inside the /tmp/test directory has been updated and passes the variables b and r to the block(in this case just line number 3). r is the relative path to the updated, b is the absolute path(/tmp/test in this case); then a message is printed on the screen.

The code for the created and deleted files are the same.

Now, the FSSM.monitor has 3 possible arguments, we just use 1 of them in the above example.

The second parameter is a glob pattern(or array of glob patterns) that the files must match to be watched by fssm, if this parameter is not specified, the default is **/*.

The third parameter is for watching directories. By default, fssm watch just for file changes, if we want to watch directories too we need to pass the option here, doing this :directories => true, and additionally, the blocks for update, delete and create must have another block variable:

delete do |b, r, t|
	puts "Someone delete #{r} into #{b} which is a #{t == :directory ? 'directory' : 'file'}"
end

Where t is the type, it means if is a directory or a file, we check for this in a «short» if statement. t variable can be the symbols :directory or :file. AFAIK this will not work as expected on MacOS, I appreciate if someone can confirm, I’m a poor guy and I don’t own a Mac. :P . Anyway it don’t watch for created, deleted or updated directories, but if you create a directory inside /tmp/test and then create a file inside, it will be detected.

So, the complete code with checking for directories is:

#!/usr/bin/env ruby

require 'rubygems'
require 'fssm'

FSSM.monitor("/tmp/test", '**/*', :directories => true) do
 update do |b, r, t|
 puts "Someone changes #{r} into #{b} which is a #{t == :directory ? 'directory' : 'file'}"
 end

 create do |b, r, t|
 puts "Someone create #{r} into #{b} which is a #{t == :directory ? 'directory' : 'file'}"
 end

 delete do |b, r, t|
 puts "Someone delete #{r} into #{b} which is a #{t == :directory ? 'directory' : 'file'}"
 end
end

That’s it!. Now we can watch for filesystem changes in many different systems. It’s so nice and useful. Of course we need to develop and work a little more to do something nicer.

I hope this will help someone, works for me.

See you soon.

Changing IP Address of a Thomson TG585-V8 Router

My old ADSL internet modem HG2701was burned for some reason and I requested for a replacement to my ISP and it gave me a Thomson TG585-V8 modem which makes useles a little python script that I found around to change the IP and keep downloading… backup copies of something.

As a coincidence some days ago I read about a library called mechanize and of course using one of my favorite languages(ruby) I decided to write a little program to change my IP address.

Here, the description of mechanize library stolen from it’s website:

«The Mechanize library is used for automating interaction with websites. Mechanize automatically stores and sends cookies, follows redirects, can follow links, and submit forms. Form fields can be populated and submitted. Mechanize also keeps track of the sites that you have visited as a history.»

After read some examples and write some testing code I reach to a very simple script that does the magic:

require 'mechanize'

USER = 'USERNAME'
PASSWORD = 'PASSWORD'

URL = 'http://192.168.1.254/cgi/b/is/_pppoe_/ov/?be=0&l0=2&l1=2&name=Internet'

BUTTONS = ['13', '12'] #First is to deconnect, next for reconnect

FORM = 'PPPConn'
SNAME = 'Internet'

m = Mechanize.new

m.user_agent_alias = 'Windows IE 7'
m.auth(USER, PASSWORD)

BUTTONS.each do |bn|
 page = m.get(URL)
 f = page.form_with(FORM)

 f['0'] = bn
 f['1'] = SNAME

 b = f.button_with(:name => bn)
 f.click_button(b)
end

A basic explanation of the above code:

  • We create an instance of the Mechanize class
  • Now we inform to the website which interact to us that we are some kind of webbrowser
  • And then we need to autenticate to the site
  • Then we get the page, the form and fill the correct values
  • Now we click the button to kill the connection
  • So, we repeat the page, form, button, and click the connect button to get a new IP address

Of course, the code has no error checking, it’s a really basic version. But I like it ’cause it’s just a few code.

You can get the code from my bitbucket utils repository and of course I hope to add some features, not so much, it does what suppose to do.

Happy hollidays!.

Generate «secure» passwords

It’s been awhile since I posted something, and even more since I posted computer stuff.

Well, this time I make a little script to generate «secure» passwords from command line with options to modify the number of generated passwords and the number of characters in each password.

The real trick it’s done through a combination of a few shell tools.

  • < : The redirection symbol, it means, send from one side to another.
  • /dev/urandom : «Unblocked» random source
  • tr : Translate or delete characters
  • head : Output the first part of files

So, let’s build the expression which brings to us the passwords. First of all we use

</dev/urandom

to send /dev/urandom output to stdout. The next step is to process the chars dropped by urandom, this can be made with tr command  and the -dc options, d deletes chars and c takes the complement of the given parameter,

</dev/urandom tr -dc '1234567890!@#$%&/()=qwertyuiopQWERTYUIOPasdfghjklASDFGHJKLzxcvbnmZXCVBNM'

, so, tr will take the complement of that ugly string and then delete it, so it removes all the chars that are not inside the long string above, leaving just an «easily» read string.

Now, if we leave the command as is, we get an extremely large string and of course, unusable as password, so we need to cut it, then we pipe to head command with the -cn option, it says «just take the first n characters of anything is given to you». By this time we set n=8, a nice length for a good password.

</dev/urandom tr -dc  '1234567890!@#$%&/()=qwertyuiopQWERTYUIOPasdfghjklASDFGHJKLzxcvbnmZXCVBNM' | head -c8

Now, you can try it!. It gives you a 8 char length password and as you can see, it can be considered(most times) a good password. As an extra, you can put an echo “” at the end of the command to tell bash that puts a new line before the prompt.

</dev/urandom tr -dc   '1234567890!@#$%&/()=qwertyuiopQWERTYUIOPasdfghjklASDFGHJKLzxcvbnmZXCVBNM'  | head -c8; echo ""

And if you want to automatize the generation of passwords and variate the number of generated passwords and the length of it, you can build a little script, I’m not gonna explain to you, but I leave it here, use it and enjoy it.

#!/usr/bin/env bash

genpass()
{
 </dev/urandom tr -dc '1234567890!@#$%&/()=qwertyuiopQWERTYUIOPasdfghjklASDFGHJKLzxcvbnmZXCVBNM' | head -c${1}
}

usage()
{
 echo "${0##*/} c p"
 echo -e "\tc is the number of chars in each generated password"
 echo -e "\tp is the number of password to be generated\n"
 exit 1
}

control()
{
 if [ "$#" = "0" ];then
 npass=1
 cpass=8
 elif [ "$#" = "1" ];then
 if [ "$1" = "-h" ];then
 usage
 elif [ "$1" = "--help" ];then
 usage
 fi

 cpass=$1
 npass=1
 else
 cpass=$1
 npass=$2
 fi

 echo "Chars in each password: ${cpass}"
 echo "Number of passwords to generate: ${npass}"
 echo -e "Generating...\n"

 i=1
 while [ ${i} -le ${npass} ];do
 echo -n -e "\t${i}: "
 genpass ${cpass}
 echo ""
 let i=i+1;
 done

 echo ""
}

control $1 $2

See you soon!.

Sekken Nuevo

Asi es, mi primer sekken. Lo chistoso es que aun no llega mi bogu, de ahi una pregunta que por cierto, tambien se hizo mi mami. “¿Y eso donde se pone?”, “en el tare” le contesto. “¿Ya le dicen asi?, dice ella. XD

Vendido

Ha sido el mundial mas aburrido, vendido, arreglado y horrible que he visto. Si alguna vez creí que esa final Francia vs Brasil estuvo arreglada, fue porque aún no existía Sudáfrica 2010. En fin, lo demás me lo reservo.

Y en otra cosa, espero dentro de poco publicar unas cositas que tengo ya listas por ahí.

Saludos.

El Kendo de Todos los Días

Ayer creí que la clase de Kendo había sido un poco corta. De práctica sólo fue una hora y después a observar a las personas con equipo. Pero la cosa cambió. Bajo invitación de Maya Sensei, acudió al dojo, Camacho Sensei(quien, si no me equivoco, es 4° Dan). Y comenzó a cuestionarnos acerca de cuestiones «teóricas» del Kendo, conceptos, ideas, nombres y demás; muy ilustrativo por cierto, además de que, al menos en mi caso, pude darme cuenta de que el Kendo no sólo es ir a entrenar a tales horas y tales días.

Pero lo mejor vino al final, me parece que los últimos 10 minutos. Camacho Sensei nos dio una pequeña charla acerca de lo que en significa el Kendo, más allá de lo deportivo, llegando a convertirse en un estilo de vida, descansando sobre los mismos cimientos.

Para empezar, el respeto, pasando por la cortesía y siempre todo con honestidad; sabiendo aceptar las derrotas con humildad, pero sin humillarse. Así también tomando los triunfos, con más humildad aún, de manera discreta y con el corazón limpio. En cualquier caso, sin rencores, haciendo lo que uno tenga que hacer de todo corazón y siempre teniendo un sólo camino, como una kantana un sólo filo, hacia adelante; siempre avanzando, creciendo humanamente, y sobre todo, retomar el verdadero significado del samurai: SERVIR.

Domo Arigato Gozaimashita Camacho Sensei.

¿Bogu?

Se le llama bogu al conjunto de protecciones(armadura) utilizada en el Kendo. Comprende lo siguiente:

  • Men. Protección de la cabeza. Casco.
  • Do. Protección del torso.
  • Kotes. Protección de las manos, muñecas y antebrazos.
  • Tare. Protección de los costados y cintura.

¿Y a qué viene lo anterior?. Pues a que ya hace unas semanas(como 2) hicieron el favor de prestarme un bogu para la práctica de Kendo y ¡fue sencillamente maravilloso!. Es completamente otro mundo, inclusive el ponerse el equipo hace que te den nervios, pero de esos nervios que te gusta sentir y volver a sentir una y otra vez, si, algo así como cuando estás enamorado… bueno, no es lo mismo evidentemente, pero no encuentro como describir la sensación[no te enojes mi vida, a ti te quiero mas :-P ].

Había estado leyendo y viendo videos de como se coloca el equipo, pero cuando estás ahí, no te funciona, aunque si ayuda bastante no llegar en cero. El tare y el do no tienen tanta bronca, es similar a ponerse el keikogi y la hakama, la bronca llega cuando se pone uno el tenugui, un tipo paliacate que se coloca en la cabeza antes del men para atrapar el sudor; normalmente no te queda a la primera, debe quedar muy muy ajustado. Total, después de hacerle 5 minutos al cuento y medio ponérmelo, vendría lo complicado, colocarse el men. Ponerse el men las primeras veces es un teatro, debe uno de ajustarlo a la perfección y acomodar los himos(hilos que sirven para amarrar el men) de manera correcta, y después de amarrarlo(si es que lo logras) debes asegurarte de que la longitud de los himos ya atados sea la misma. Obviamente después del men, hay que ponerse los kotes, cosa por demás sencilla, comparada con todo lo demás.

Con la novedad de que tener el men al principio resulta incómodo y no apto para claustrofóbicos. Te quita visibilidad hacia los costados, no escuchas prácticamente nada, te aprieta las orejas, no puedes mover casi el mentón(abrir la boca pues) y si te queda chico, como me sucedió hoy, la segunda vez que me puse equipo, te aprieta los cachetes de tal manera que sientes que te sacaron 3 muelas de cada lado y que aún sigues hinchado por la cirugía.

Aún con lo anterior se siente genial, al menos yo, siento que me transformo en otra persona, una gran parte del cansancio se esfuma, enfrente de ti tienes a tu oponente y, sin olvidar la etiqueta y el respeto que le debes, es él o tu, tratas de juntar todo tu espíritu, todos tus conocimientos y te lanzas al combate.

Tuve el honor de que mi primer keiko(combate) haya sido con Maya Sensei, que, para decirlo propiamente, me acomodó una paliza impresionante, no sin antes permitirme, de manera muy cortés, dar unos cuantos golpes.

El día de hoy fue un poco diferente, tuve tres combates, el primero con Sempai Ulises, el más avanzado de todos(3er Dan), a quien siempre es un gusto ver combatir. Después con Sempai Oscar, que me pareció bastante bueno, resalta en demasía cuando se pone el bogu, muy modesto sin el. Y al final Sempai Paulina, agresiva y certera, a quien creo que en un choque lastimé un poco la muñeca sin querer; mi culpa por completo pienso yo, trataré de ser más cuidadoso.

Quiero comprar mi bogu lo antes posible, es como se dice, «otra onda». Por cierto, gracias Sensei por la playera que me obsequió el día de hoy.

El Kendo es de las mejores cosas que me han pasado. Me cansa, me desestreza, me divierte, me disciplina y me apasiona.

[No te enojes tanto corazón, a ti te quiero mas. xD]

Como me encantaría que mi Papá estuviera aquí…