miércoles, 28 de noviembre de 2012

Navegar mediante un túnel SSH

Una característica interesante del protocolo ssh, es la posibilidad de establecer túneles o redirecciones de puertos que permiten... más fácil es mostrarlo que explicarlo:

Supongamos que estamos con nuestra notebook en la red de nuestra universidad, queremos acceder a Facebook :-) pero el proxy nos restringe el acceso.
O estamos en un lugar público como un café o un aeropuerto, con muchas redes wifi abiertas disponibles, que son tentadoras pero a la vez riesgosas porque no sabemos quién podría estar husmeando en nuestras comunicaciones.

En ambos casos, podríamos solucionar nuestro problema estableciendo un túnel a un servidor propio (podría ser simplemente una PC en casa), y navegando desde allí (siempre y cuando podamos conectarnos via ssh a nuestro servidor desde esa red).

En el caso de la universidad, nos saltearíamos las restricciones del proxy, y en el caso de las redes wifi evitariamos el riesgo de que alguien husmee nuestro tráfico web.

Para armar el túnel, solo hace falta ejecutar el siguiente comando en nuestro equipo local:

$ ssh -D 12345 usuario@servidor_remoto

(reemplazando con el nombre de usuario y la ip o dirección del servidor correspondientes).

Al ejecutar ese comando nos pedirá nuestra contraseña en el servidor remoto; y con eso estamos creando un túnel que escuchará en el puerto local 12345 (se puede elegir otro puerto), enviando el tráfico a través de ssh (por lo tanto, encriptado) a nuestro servidor remoto.

El siguiente paso es editar la configuración proxy de nuestro navegador, indicando que utilice un proxy socks (servidor 127.0.0.1, y puerto 12345 en este caso):


Una vez habilitada la configuración del proxy, ya podremos empezar a navegar.

Una manera rápida de chequear si el túnel funciona es acceder a alguno de los tantos sitios que nos informan cual es nuestra dirección ip.

Antes y después de habilitar el túnel:






Esta clase de túneles también se podrían utilizar para otro tipo de tráfico, como por ej. descarga de correo electrónico. Pero ya es tema para otro post :-)




Web browsing using a ssh tunnel


A very interesting feature of the ssh protocol is the capability of setting up tunnels or port forwarding, which allow to.... its easier to show than explaining it:

Lets say we are with our notebook in our university network, we want to open Facebook :-) but the proxy denies us the access.
Or we are in a public place like a coffee shop or an airport with many wifi open networks around, all them very tempting but also dangerous because we don't know who could be there sniffing our communications.

In both cases we could solve our problem setting up a ssh tunnel to a server (could be just a computer at home), and surfing from there (remember that ssh access must be permited in the network for this to work).

In the university scenario, we could jump over the proxy restrictions; and in the wi-fi case we would avoid the risk that someone could sniff into our web traffic.

To establish the tunnel, we need to run the following command in our local machine:

$ ssh -D 12345 user@remote-server

(of course, replacing user with our username, and remote-user with the ip or address of our server).

After runnig this command, it will ask for our remote server password; with that we are setting up a tunnel which listens in the local port 12345 (you could choose another port number), sending all the traffic through ssh (encrypted) to our remote server.

The next step is to edit the proxy configuration in our browser, telling it to use a proxy socks (server 127.0.0.1 and port 12345 in this case):



Once the browser configuration is done, we can begin the web browsing.

A quick way to check if the tunnel is working, is to go to one of the many websites that tell us our ip address.

Before and after the tunnel:







These kind of tunnels could also be used for other kind of traffic, ie to download email. But that is a topic for another post :-)

viernes, 23 de noviembre de 2012

Medir la velocidad de conexión a Internet desde línea de comandos


Siempre que necesito medir la velocidad de conexión a Internet utilizo el site speedtest.net. Es una herramienta muy práctica y sencilla para saber las velocidades de subida y bajada del enlace desde donde nos estamos conectando.


Para poder utilizarla solo hace falta un navegador web. Y ahí aparece el problema si queremos hacer el test desde consola sin tener un browser disponible (en un servidor remoto por ej.).

Normalmente en estos casos para testear las velocidades de descarga lo más sencillo sería ponerse a descargar un archivo (con wget o curl) relataivamente grande, y ver las estadísticas o hacer un simple cálculo entre tamaño del archivo/tiempo requerido para la descarga.

También existe la herramienta lperf, para probar el ancho de banda entre dos equipos, que también podría servir.

Pero lo más interesante sería tener una herramienta tipo speedtest.net, que mida download y upload, y que sea sencilla de usar.

Buscando algo así me encontré con una herramienta que hace justamente eso: testspeed, un script python disponible en https://github.com/Janhouse/tespeed.

Fue desarrollada por un programados de nombre Janis Jansons de Letonia, y utiliza los servicios de speedtest.net para realizar la prueba de velocidades, pero todo sin salir de la querida consola.

Se puede descargar el script desde github:


$ wget https://github.com/Janhouse/tespeed/archive/master.zip
$ unzip master.zip

Antes de poder utilizarlo, hay que instalar el módulo lxml de python:
$ sudo apt-get install python-lxml

Y ahora si, ya lo podemos ejecutar:

$ cd tespeed-master/
$ ./tespeed.py 

Primero, al igual que la versión tradicional de speedtest, el script testeará la latencia contra servidores cercanos goegráficamente, y una vez seleccionado el mejor, entonces realizará los tests de download y upload.

$ ./tespeed.py
Getting ready. Use parameter -h or --help to see available features.
Loading speedtest configuration...
IP: 198.74.62.154; Lat: 39.489900; Lon: -74.477300; ISP: Linode
Loading server list...
Looking for closest and best server...
Testing latency...
11 ms latency for http://sto-plfi-01.sys.comcast.net/speedtest/ (Comcast, Plainfield, NJ, United States) [37.08 km]
7 ms latency for http://speedtest.monmouth.com/speedtest/ (Monmouth Telecom, Red Bank, NJ, United States) [52.38 km]
3 ms latency for http://speed.fortressitx.com/speedtest/ (Fortress ITX, Clifton, NJ, United States) [54.77 km]
9 ms latency for http://nms.interserver.net/speedtest/speedtest/ (Interserver, inc, Secaucus, NJ, United States) [60.15 km]
2571 ms latency for http://newyork-speedtest.atlanticmetro.net/speedtest/speedtest/ (Atlantic Metro, New York, NY, United States) [64.06 km]
Best server with average latency 3ms - Fortress ITX, Clifton, NJ, United States
Download size: 3.93 MiB; Downloaded in 0.04 s                                              
Download speed: 112.11 Mbit/s
Download size: 16.18 MiB; Downloaded in 0.10 s                                             
Download speed: 164.61 Mbit/s
Download size: 35.78 MiB; Downloaded in 0.20 s                                             
Download speed: 180.54 Mbit/s
Download size: 63.56 MiB; Downloaded in 0.37 s                                             
Download speed: 170.40 Mbit/s
Download size: 142.98 MiB; Downloaded in 0.74 s                                            
Download speed: 194.10 Mbit/s
Download size: 253.05 MiB; Downloaded in 1.34 s                                            
Download speed: 188.53 Mbit/s
Download size: 379.57 MiB; Downloaded in 2.09 s                                            
Download speed: 181.30 Mbit/s
Download size: 595.58 MiB; Downloaded in 3.06 s                                            
Download speed: 194.95 Mbit/s
Download size: 855.21 MiB; Downloaded in 4.40 s                                            
Download speed: 194.54 Mbit/s
Download size: 1164.58 MiB; Downloaded in 6.05 s                                           
Download speed: 192.43 Mbit/s
Upload size: 2.10 MiB; Uploaded in 0.51 s                                                  
Upload speed: 4.09 Mbit/s
Upload size: 2.10 MiB; Uploaded in 0.26 s                                                  
Upload speed: 8.10 Mbit/s
Upload size: 4.19 MiB; Uploaded in 0.56 s                                                  
Upload speed: 7.54 Mbit/s
Upload size: 4.19 MiB; Uploaded in 0.56 s                                                  
Upload speed: 7.53 Mbit/s
Upload size: 16.78 MiB; Uploaded in 1.12 s                                                 
Upload speed: 14.99 Mbit/s
Upload size: 16.78 MiB; Uploaded in 1.51 s                                                 
Upload speed: 11.09 Mbit/s
Upload size: 134.22 MiB; Uploaded in 7.22 s                                                
Upload speed: 18.58 Mbit/s

Un script muy práctico, que si bien aún se encuentra en versión alpha con algunos pequeños bugs, cumple muy bien su tarea.

Test Internet speed from the command line


Every time I need to measure my Internet speed I use the speedtest.net website. Its a very handy and easy tool, useful for knowing the upload and download speed of the internet link from where we are connecting.


To be able to use it, we just need a web browser. And there is the problem if we want to perform the test from the command line without a browser available (ie on a remote server),

Usually, in these cases the easy way would be to download a file (using wget or curl), and see the stats or make a simple calculation between filesize/time needed to finish the download.

There is also the lperf tool, to test the bandwith between two machines and could be useful too.

But it would be more interesting to have a tool like speedtest.net, capable of measuring the download and upload speeds, and be easy to use.

Looking for something like that I found this tool: testspeed, a python script available at https://github.com/Janhouse/tespeed.

It was developed by a programmer named Janis Jansons from Latvia, and it uses the speedtest.net service to perform the test, all that without leaving the beloved command line.

It can be downloaded from github:

$ wget https://github.com/Janhouse/tespeed/archive/master.zip
$ unzip master.zip

Before using it, the lxml python module must be installed:
$ sudo apt-get install python-lxml

And then we can run it:

$ cd tespeed-master/
$ ./tespeed.py 

As the browser version of speedtest, first the script will check the latency from geographically close servers, and select the best one; then will run the download and upload tests.

$ ./tespeed.py
Getting ready. Use parameter -h or --help to see available features.
Loading speedtest configuration...
IP: 198.74.62.154; Lat: 39.489900; Lon: -74.477300; ISP: Linode
Loading server list...
Looking for closest and best server...
Testing latency...
11 ms latency for http://sto-plfi-01.sys.comcast.net/speedtest/ (Comcast, Plainfield, NJ, United States) [37.08 km]
7 ms latency for http://speedtest.monmouth.com/speedtest/ (Monmouth Telecom, Red Bank, NJ, United States) [52.38 km]
3 ms latency for http://speed.fortressitx.com/speedtest/ (Fortress ITX, Clifton, NJ, United States) [54.77 km]
9 ms latency for http://nms.interserver.net/speedtest/speedtest/ (Interserver, inc, Secaucus, NJ, United States) [60.15 km]
2571 ms latency for http://newyork-speedtest.atlanticmetro.net/speedtest/speedtest/ (Atlantic Metro, New York, NY, United States) [64.06 km]
Best server with average latency 3ms - Fortress ITX, Clifton, NJ, United States
Download size: 3.93 MiB; Downloaded in 0.04 s                                              
Download speed: 112.11 Mbit/s
Download size: 16.18 MiB; Downloaded in 0.10 s                                            
Download speed: 164.61 Mbit/s
Download size: 35.78 MiB; Downloaded in 0.20 s                                            
Download speed: 180.54 Mbit/s
Download size: 63.56 MiB; Downloaded in 0.37 s                                            
Download speed: 170.40 Mbit/s
Download size: 142.98 MiB; Downloaded in 0.74 s                                            
Download speed: 194.10 Mbit/s
Download size: 253.05 MiB; Downloaded in 1.34 s                                            
Download speed: 188.53 Mbit/s
Download size: 379.57 MiB; Downloaded in 2.09 s                                            
Download speed: 181.30 Mbit/s
Download size: 595.58 MiB; Downloaded in 3.06 s                                            
Download speed: 194.95 Mbit/s
Download size: 855.21 MiB; Downloaded in 4.40 s                                            
Download speed: 194.54 Mbit/s
Download size: 1164.58 MiB; Downloaded in 6.05 s                                          
Download speed: 192.43 Mbit/s
Upload size: 2.10 MiB; Uploaded in 0.51 s                                                  
Upload speed: 4.09 Mbit/s
Upload size: 2.10 MiB; Uploaded in 0.26 s                                                  
Upload speed: 8.10 Mbit/s
Upload size: 4.19 MiB; Uploaded in 0.56 s                                                  
Upload speed: 7.54 Mbit/s
Upload size: 4.19 MiB; Uploaded in 0.56 s                                                  
Upload speed: 7.53 Mbit/s
Upload size: 16.78 MiB; Uploaded in 1.12 s                                                
Upload speed: 14.99 Mbit/s
Upload size: 16.78 MiB; Uploaded in 1.51 s                                                
Upload speed: 11.09 Mbit/s
Upload size: 134.22 MiB; Uploaded in 7.22 s                                                
Upload speed: 18.58 Mbit/s

Its a very handy script, and although its still in alpha version with some minor bugs, performs its task very well.

jueves, 22 de noviembre de 2012

Instalar y ejecutar Dropbox desde línea de comandos

Para poder instalar y ejecutar un cliente Dropbox en un servidor Linux, solo es necesario seguir estos pasos (ver https://www.dropbox.com/install).

Primero descargamos y descomprimimos el paquete (como usuario normal, no es necesario hacerlo como root):

aarrieta@kooka:~$ cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86" | tar xzf -   

Se descargarán los archivos necesarios y serán descomprimidos en el directorio (oculto) .dropbox-dist.

El siguiente paso es lanzar el daemon. Al ser la primera vez, pedirá que accedamos desde un navegador web a una url para asociar el cliente con nuestra cuenta:


aarrieta@kooka:~$ ~/.dropbox-dist/dropboxd
This client is not linked to any account...
Please visit https://www.dropbox.com/cli_link?host_id=5c707a104e389bb7a0c2c36a3e79afc5 to link this machine.
This client is not linked to any account...
(seguirá repitiendo el mensaje hasta que hagamos lo que nos pide)

Hay que ir a esa direccion e ingresar nuestra contraseña de Dropbox. 



Una vez hecho eso, aparecerá un mensaje (en el navegador y en la consola), informando que se asoció exitosamente el cliente con nuestra cuenta.

Client successfully linked, Welcome Ariel!

Damos Ctrl-c para cerrar el daemon por el momento.

Si nos fijamos, en nuestro directorio home aparecerá una nueva carpeta con el nombre Dropbox, que es donde se almacenarán los archivos.

El próximo paso es descargar un script en python que nos servirá para administrar al daemon:

aarrieta@kooka:~$ wget https://www.dropbox.com/download?dl=packages/dropbox.py -O dropbox.py

Le damos permiso de ejecución:
aarrieta@kooka:~$ chmod +x dropbox.py 

Y lo ejecutamos sin parámetros para que nos muestre las opciones disponibles:

aarrieta@kooka:~$ ./dropbox.py 
Dropbox command-line interface

commands:

Note: use dropbox help <command> to view usage for a specific command.

 status       get current status of the dropboxd
 help         provide help
 puburl       get public url of a file in your dropbox
 stop         stop dropboxd
 running      return whether dropbox is running
 start        start dropboxd
 filestatus   get current sync status of one or more files
 ls           list directory contents with current sync status
 autostart    automatically start dropbox at login
 exclude      ignores/excludes a directory from syncing
 lansync      enables or disables LAN sync


aarrieta@kooka:~$ ./dropbox.py status
Dropbox isn't running!

Lo arrancamos:

aarrieta@kooka:~$ ./dropbox.py start
Starting Dropbox...Dropbox isn't running!
Done!

Y podemos ver como empieza a sincronizar con nuestros archivos "en la nube":

aarrieta@kooka:~$ ./dropbox.py status
Downloading 2,732 files (110.7 kB/sec, 8 hr left)

Tema para un futuro post o tarea para el hogar: configurar para que el daemon sea ejecutado automáticamente al arrancar el sistema, sin necesidad de arrancarlo "a mano" con el comando ./dropbox.py start.

Install and run Dropbox from the command line

To be able to install and run a Dropbox client in a Linux server, follow these steps (see https://www.dropbox.com/install).

To begin, we must download and uncompress the package (as a normal user, root is not needed):

aarrieta@kooka:~$ cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86" | tar xzf -   

The needed files will be downloaded and uncompressed in the (hidden) .dropbox-dist directory.

Next step is to launch the daemon. Because it is the first time, it will ask us to go to an website with a browser to link the client we are installing with our Dropbox account:

aarrieta@kooka:~$ ~/.dropbox-dist/dropboxd
This client is not linked to any account...
Please visit https://www.dropbox.com/cli_link?host_id=5c707a104e389bb7a0c2c36a3e79afc5 to link this machine.
This client is not linked to any account...
(it will keep repeating the message until we do what it wants)

We must go to that address and enter our Dropbox password:

Once finished, a message telling us about the success of the action will appear in the console and in the browser:

Client successfully linked, Welcome Ariel!

We type Ctrl-c to close the daemon now.

If we look into our home directory, there will be a new folder called Dropbox, where the files will be stored.

Next step is to download a pythons script that will be used to manage the daemon:

aarrieta@kooka:~$ wget https://www.dropbox.com/download?dl=packages/dropbox.py -O dropbox.py

We give it execute permission:
aarrieta@kooka:~$ chmod +x dropbox.py 

And then launch it without parameters, to see the available options:

aarrieta@kooka:~$ ./dropbox.py 
Dropbox command-line interface

commands:

Note: use dropbox help <command> to view usage for a specific command.

 status       get current status of the dropboxd
 help         provide help
 puburl       get public url of a file in your dropbox
 stop         stop dropboxd
 running      return whether dropbox is running
 start        start dropboxd
 filestatus   get current sync status of one or more files
 ls           list directory contents with current sync status
 autostart    automatically start dropbox at login
 exclude      ignores/excludes a directory from syncing
 lansync      enables or disables LAN sync


aarrieta@kooka:~$ ./dropbox.py status
Dropbox isn't running!

We start it:
aarrieta@kooka:~$ ./dropbox.py start
Starting Dropbox...Dropbox isn't running!
Done!

And now we can see how it begins to sync with our files "in the cloud":
aarrieta@kooka:~$ ./dropbox.py status
Downloading 2,732 files (110.7 kB/sec, 8 hr left)

Topic for a future post or for homework: configure the dameon so it runs automatically when the system starts, without the need of launching it "by hand" with the command ./dropbox.py start.

miércoles, 21 de noviembre de 2012

Configurando un servidor en Linode (parte 2)

Ahora que ya tenemos creada la cuenta en Linode, vamos a crear y luego arrancar el servidor.

Para eso primero desde la web de Linode mediante la opción Log In accedemos al panel de administración, o Linode Manager.

Una vez dentro, vamos  hasta el Dashboard, y allí seleccionamos la opción Deploy a Linux Distribution.



Aparecerá una pantalla con las opciones básicas para la creación del servidor:

  • Distribución (hay para elegir entre diversas versiones de Arch, Ubuntu, Debian, openSuse Fedora, Gentoo y Slackware), 
  • Tamaño del Disco
  • Tamaño de Swap 
  • y contrasela del Root.

Seteamos esas opciones según lo que deseemos y luego le damos al botón Deploy. Linode creará el servidor con los parámetros que hayamos seleccionado y nos enviará un mail informando de la acción.


Luego de crear el servidor, solo queda arrancarlo. Clickeamos en el botón Boot y eso es todo, el servidor recien creado ahora se iniciará y estará listo para ser accedido.

En la sección Remote Access del Linode Manager, podemos ver la dirección IP a la cual conectarnos. Entonces, mediante ssh podremos loguearnos por primera vez a nuestro flamante servidor.



Y ahora si, a divertirse :-)

Sugerencia: revisar y famliarizarse con las diversas opciones del Linode Manager, como así también la excelente documentación existente en la web de Linode acerca de configuraciones y administraciones varias.