Archive for the ‘bash’ Category

Good bye MLDonkey, hello Transmission!

marzo 27, 2012

Ok, I’ve been a while without updating and althoguh I have some post almost written I wanted to share with you my last piece of code.

As you may remember four years ago I writed about an script which was in charge of setting automatically your MLDonkey rates in order to not overload your bandwith according to the number of clients in your local area network. This script has been running for almost four years and has been a really helpful in achieving the following stats:

more than 3 year sharing; 1.6 T shared!!

more than 3 year sharing; 1.6 T shared!!

Well, after this past years I’ve been using MLDonkey as my bittorrent client but as it doesn’t support magnet links I’ve decided to move on and give Tranmission a try. Installing it has been a piece of cake and as I was really glad with its web-ui I’ve decided to make it my default client and therefore, remake that script in order to work with this new client!

The code its a port from the past one, but you can see it here:

#!/bin/bash
####################################################################################
####################################################################################
# A Transmission (http://www.transmissionbt.com/) script that 
# will vary the download and upload speed limits based on the
# number of hosts currently active on the LAN.
#
# Very usefull when installed in a mediabox that when being the
# only host will set no up/down limits but when a shared connection
# will limit to not overload the network
# 
# Author:
# Jaime Bosque jaboto(at)gmail(dot)com
#
# This script is based in a previous work from the author plus
# - Miguel Mtz (aka) Xarmaz
# - aRDi
# - tazok de esdebian.org
#
# Requirements:
# transmission-remote, transmission, grep, nmap, cron 
#
####################################################################################
####################################################################################

#-----------------------------------------------------------------------------------
# Transmission and network vars.
# -hosts should be 2 if you are using typical network config (router + mediabox) 
#  but may  vary if is in the same box or you have an always-active host
#-----------------------------------------------------------------------------------
transmission=/usr/bin/transmission-daemon
config_file=/home/kets/Transmission-script/settings.json
t_remote=/usr/bin/transmission-remote
user=transmission
pass=transmission
lan=192.168.1
server=localhost
port=9091
log=/home/kets/Transmission-script/transmission_limits.log
hosts=2
#-----------------------------------------------------------------------------------
# Specific rate settins according to the lan usage
# -solo_(up|donw) settings for when just this machine is in lan
# -shared_(up|down) settings for when more that this machine are in lan
#-----------------------------------------------------------------------------------
solo_down=4000
solo_up=4000
shared_down=5
shared_up=5

# Detect if transmission is running
running=`pidof transmission-daemon | wc -l`
pid=`pidof transmission-daemon`

if [ "$running" == "1" ]; then
    # Use nmap to retrieve the number of hosts in lan 
    hosts_up=`nmap -sP $lan.* | grep $lan | wc -l`
    last_read=`tail -n1 $log`
    hosts_up_before=`tail -n1 $log | grep -o -E "H[0-9]+" | grep -o -E [0-9]+`
    if [ -z "$hosts_up_before" ]; then hosts_up_before=0; fi


    # If something has changed in the lan update limits
    # echo "Hosts up $hosts_up  vs $hosts_up_before"
    if [ "$hosts_up" -ne "$hosts_up_before" ]; then
        if [ "$hosts_up" -gt "$hosts" ]; then
            down_limit=$shared_down
            up_limit=$shared_up
        else
            down_limit=$solo_down
            up_limit=$solo_up
        fi
        #echo "Setting limits $down_limit and $up_limit "
        $t_remote $server:$port -n $user:$pass -d $down_limit
        $t_remote $server:$port -n $user:$pass -u $up_limit

        #Log that changes were done!
        echo `date +"%d/%m/%y -- %H:%M"` "S$running H$hosts_up U$up_limit D$down_limit P$pid" >> $log
    fi
else
    # Log that daemon is not running :_(
    echo `date +"%d/%m/%y -- %H:%M"` "Transmission-daemon is not running!" >> $log	

    # Start transmission daemon with the specified config file
    `$transmission -g $config_file`
    echo `date +"%d/%m/%y -- %H:%M"` "Transmission-daemon was lunched!" >> $log
fi	
exit 0

I’ve also created a github repository that you might like to follow for further changes or to know a bit more about the script and settings.

Hope it helps!

Anuncios

XFCE display switching (dual & single monitor)

enero 18, 2012

It’s been a long time since I don’t write neither in English nor about computer related stuff. It’s not that I stopped doing things but was a bit lazy about posting them here.

Anyway, a few days ago I bout a new monitor tired of working in a 12” screen. I connected it and nothing happened, i mean, there was no signal output so, as usual, I prompted out a terminal and used that wonderful tool called xrandr. Perfect! I worked like a charm until I disconnected it and realized I have no output trough my laptop screen, dammit! and as my key-combination wasn’t working I had to restart it.

I found that xfce4-settins-manager -> keyboard -> application shortcuts were supposed to launch xfce4-display-settings –minimal which did nothing so, instead of that, based on a script I found in the web (see below) I coded a small script, gave it execution permissions and asigned it to my preferred shortcut (XF86Display – Fn+F7 in my Thinkpad X61s).

Keyboard shortcuts

Keyboard shortcuts

Here is the script, working perfectly:

#!/bin/sh
# Based on the script from
# http://quepagina.es/ubuntarium/vamos-a-personalizar-la-tecla-switch-display-de-portatil.html

# Will do a cycling output from state 0 to 2 and use a sound as feedback
# State VGA LVDS Beeps
#   0    0   1      1
#   1    1   0      2   
#   2    1   1      3
#   (back to state 0)   

#For identifying our monitors use xrandr tool and view output
LVDS=LVDS1      # could be another one like: LVDS, LVDS-1, etc
VGA=VGA1        # could be another one like: VGA, VGA-1, etc
EXTRA="--right-of $LVDS" # addtional info while dual display

# Lets check both LVDS and VGA state from the string "$display connected (" 
xrandr | grep -q "$LVDS connected (" && LVDS_IS_ON=0 || LVDS_IS_ON=1
xrandr | grep -q "$VGA connected (" && VGA_IS_ON=0 || VGA_IS_ON=1

# Output switch cycle
if [ $LVDS_IS_ON -eq 1 ] && [ $VGA_IS_ON -eq 1 ]; then
    #Go to state 0 -> just LVDS
    xrandr --output $LVDS --auto 
    xrandr --output $VGA --off
    beep 
elif [ $LVDS_IS_ON -eq 1 ]; then
    #Go to state 1 -> just VGA
    xrandr --output $LVDS --off
    xrandr --output $VGA --auto 
    beep && beep
elif [ $VGA_IS_ON -eq 1 ]; then
    #Go to state 2 -> both outputs
    xrandr --output $LVDS --auto
    xrandr --output $VGA --auto $EXTRA
    beep && beep && beep
else
    #This should never be reached but just in case..
    xrandr --output $LVDS --auto 
    beep && beep && beep && beep
fi

As you might already guessed, that script will only work as long as you are logged in a Desktop System (XFCE, Gnome, KDE…) and running the daemon listening to your shortcuts. But there’s no problem, you could also use it from a terminal if you assign it to your acpi event (see this) if you previously know which event is being launched on your combination (use acpid_listen).

Hope it helps!

Howto PAN in linux

julio 21, 2008

I generally write in Spanish, but this time I’m gonna try to go a step further so more people can get some profit from my experiences.

I’m going to show you how to create a PAN (Personal Area Network) between two computers running Linux using bluetooth devices. This PAN is supoussed to be set up any time you plug your bluetooth adapter.

First of all, I’ll try to explain how I have set up my network so the following explanation will be easier to understand, here’s in a simple schema:

My LAN

My LAN

I have on router with access point, one personal computer, one server (used to P2P, remote login, FTP…) and my laptop. I usually connect to the network using the wireless connection (shown in blue), but sometimes it seems to fail so I get out of connection and I’m too lazy to move some meeters to reset the router. So, in order to avoid this, I’m gonna show you how to create a bluetooth conection between the server and the laptop (shown in red) that can be used as a gateway to the Internet for both my laptop and my mobile phone or as a simple LAN to perform some administration tasks through ssh.

For both sides:
Be ensure that you have the bnep module compiled in your kernel:


Networking --->
<M>Bluetooth subsystem support --->
<M>BNEP protocol support

The server side:
It is using a bluetooth adapter Conceptronic. The MAC will be used in the client side you can use hcitool dev to get it.

First of all edit the /etc/default/bluetooth adding the following lines:

....
PAND_ENABLED=1
PAND_OPTIONS="--listen --role NAP --devup /etc/bluetooth/pan/dev-up"
....

This will enable PAND and tell the system how to act, if you see, when the system PAND receives a connection it will execute the /etc/bluetooth/pan/dev-up script which has to be set up like this:

#!/bin/sh
ifup bnep0
ifconfig bnep0 up
ifconfig bnep0 192.168.5.1
ifconfig bnep0 netmask 255.255.255.252

Remeber to make it executable and restart the bluetooth system:

$ chmod +x /etc/bluetooth/pand/dev-up
$ /etc/init.d/bluetooth restart

The client side
As well as for the server edit the /etc/default/bluetooth adding the following lines (notice the MAC gotten before is now used):

...
PAND_ENABLED=1
PAND_OPTIONS="--connect 00:80:5A:20:4E:F7 --devup /etc/bluetooth/pan/dev-up"
...

In the same way, the file specifying how to act when the system notices the connection has to be edited, so here is how /etc/bluetooth/pan/dev-up should look like:

#!/bin/sh
ifup bnep0
ifconfig bnep0 up
ifconfig bnep0 192.168.5.2
ifconfig bnep0 netmask 255.255.255.252

Remeber to make it executable and restart the bluetooth system:

$ chmod +x /etc/bluetooth/pand/dev-up
$ /etc/init.d/bluetooth restart

Now, everytime you connect the bluetooth adapter, a new interface bnep0 should be brought up in both sides with the specified rules. You can see it using the ifconfig command. You should be able to do any tasks from both sides like ping, ssh… here’s an expample:

root@Stronghold:/etc/bluetooth/pan# ifconfig
bnep0 Link encap:Ethernet HWaddr 00:80:5a:20:4e:f7
inet addr:192.168.5.1 Bcast:192.168.5.3 Mask:255.255.255.252
inet6 addr: fe80::280:5aff:fe20:4ef7/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:21 errors:0 dropped:0 overruns:0 frame:0
TX packets:43 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3925 (3.8 KiB) TX bytes:7047 (6.8 KiB)
root@Stronghold:/etc/bluetooth/pan# ping 192.168.5.2
PING 192.168.5.2 (192.168.5.2) 56(84) bytes of data.
64 bytes from 192.168.5.2: icmp_seq=1 ttl=64 time=59.9 ms
^C
— 192.168.5.2 ping statistics —
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 59.977/59.977/59.977/0.000 ms

Additional comments:

  • Of course, you will have to change some information as the MAC and the IP address
  • If you get the following error:
    ExoduS:/home/kets# pand --connect 00:80:5A:20:4E:F7 -n
    pand[10820]: Bluetooth PAN daemon version 3.30
    pand[10820]: Connecting to 00:80:5A:20:4E:F7
    pand[10820]: Connect to 00:80:5A:20:4E:F7 failed. File exists(17)

    It’s because you have already a connection set up in your computer, probably running on the background you can see it with pand -l and destroy it with pand -K

  • By now I’m just using this connetion as a simple LAN not as a gateway to the Internet. If you wish to do that, you’ll have to set up some iptables rules in the server side, these rules are very well explained in the first link of the following section.

Useful links:
http://www.howtoforge.com/bluetooth_pand_debian_etch
http://bluez.sourceforge.net/contrib/HOWTO-PAN

Hope it helps & don’t hesitate to contact me for any help.

Script para mlnet -controlador automático de las tasas-

mayo 25, 2008

Hace unos días recibí un e-mail que hacía referencia al script que escribí para controlar las tasas del mldonkey: Controlador automático de los rates del MLDonkey.

Cito textualmente dicho e-mail:
Saludos, este script lo hice basado en uno que publicaste, me gustaria que lo vieras, agradeceria tus comentarios.
lo uso con cron cada 10 minutos, en un servidor ciego con debian.

Estamos en contacto.

Y me puse en contacto con él para ver si podía subirlo al blog, ante su afirmativa aquí está (he modificado algunas variables bajo su permiso para que no de pie a errores):

#!/bin/bash
# Script para Variar las tasas subida/bajan en el Mlnet en una LAN
#Elaborado por Miguel Mtz (aka) Xarmaz
#Basado en trabajos tomados de la RED de:
# Jaime Bosque (aka) KetS e-mail: jaboto (at) gmail.com
# aRDi
# tazok de esdebian.org
#Requerimientos:
#nmap telnet MLdonkey
#
#Se Requiere programar una entrada en Cron para que lo ejecute con regularidad
#Al ejecutarse inicia el demonio mlnet si no esta corriendo,
#determina cuantos equipos estan conectados y asigna la tasa mas
#adecuada de descarga.
#sirve para maquinas basadas en Debian y ubuntu

# definir Variables
#-----------------------------------------------------------------------------------
Usuario=admin
Contrasenna= (pon tu contraseña)
LAN=192.168.1
Servidor=192.168.1.xxx
Puerto=4000
Registro="/var/lib/mldonkey/acelerador.log"

# Establece los criterios y las tasas mas adecuadas
# Todo al Mlnet, solo servidor
TSalta=0
TDalta=0
# 1 o 2 maquinas aparte del servidor
TSMedia=5
TDMedia=15
#mas de 3 maquinas Conectadas.
TSBaja=2
TDBaja=6
#-----------------------------------------------------------------------------------
#Determina si el demonio esta corriendo y de no ser así lo lanza.
EstadoDemonio=`pidof mlnet|wc -l`
Proceso=`pidof mlnet`

if [ "$EstadoDemonio" == "1" ]; then

# Determina cuantas Maquinas estan Conectadas a la LAN
# si hubo cambios procede a modificar estado
NumMaqAct=`nmap -sP $LAN.* | grep $LAN | wc -l`
UltimoReg=`tail -n1 $Registro`
NumMaqAnt=${UltimoReg:22:1}

if [ "$NumMaqAnt" == "$NumMaqAct" ]; then
echo "nada que hacer"
exit 0
else
# Asigna la tasa mas Adecuada en Funcion de las maquinas conectadas
# el valor mas bajo es 2 (router y Servidor)

case $NumMaq in
0|1|2)
TasaS=$TSalta
TasaD=$TDalta
;;
3|4)
TasaS=$TSMedia
TasaD=$TDMedia
;;
5|6|7|8|9|10|11|12)
TasaS=$TSBaja
TasaD=$TDBaja
;;
esac

#Envia la instruccion al Servidor via telnet
{
sleep 1
echo auth $Usuario "$Contrasenna"
sleep 1
echo set max_hard_upload_rate $TasaS
sleep 1
echo set max_hard_download_rate $TasaD
sleep 1
echo q
} | telnet $Servidor $Puerto

#introduce en registro el movimiento.
echo `date +"%d/%m/%y -- %H:%M"` E$EstadoDemonio M$NumMaqAct S$TasaS D$TasaD P$Proceso >> $Registro
fi
else
#Borrar Archivos que pueden impedir el arranque
if [ -f /var/run/mldonkey/mlnet.pid ]; then
rm /var/run/mldonkey/mlnet.pid
rm /var/lib/mldonkey/mlnet.pid
#introducir en registro el movimiento.
echo `date +"%d/%m/%y -- %H:%M"` "mlnet se encontro parado y con archivo pid sin eliminar" >> $Registro
fi
#Inicia el demonio mlnet
/etc/init.d/mldonkey-server start
echo `date +"%d/%m/%y -- %H:%M"` "mlnet lanzado" >> $Registro
fi
exit 0

Espero que os sirva de ayuda, los agradecimientos a Xarmaz, yo sólo me limito a publicar su trabajo 😉

Scripting: detector de presencia bluetooth

abril 30, 2008

Una noche de insomnio no puede ser desaprovechada, así que estaba hurgando en mi ordenador cuando he descubierto un script que hice hace mucho tiempo.

Se trata de un script que al detectar la presencia de un dispositivo bluetooth (ya sea por el nombre o por la MAC) ejecuta un programa. Algunos pensarán, pues vaya chorrada y yo digo, pues sí, pero bueno, cuando a veces te aburres y practicas pequeñas cosas que vas aprendiendo de scripting te salen cosas que pueden tener cierta utilidad.

A continuación dejo una lista de diversas utilidades que se le podría dar:

  • Cuando llegas a casa el ordenador te pone música. Se podría hacer que en función del nombre de tu dispositivo te ponga un tipo de música u otro, ejemplo, llegas el sábado con una chati así que estableces el nombre de tu móvil a “romantico” y el programa se encarga de lanzar tu reproductor de música con las canciones que derretirían a cualquiera, encender las velas no está al alcance de este script 😉
  • Activar el bluetooth del móvil de tu padre/madre/hermano/hermana para que cuando estén llegando a casa te avise mediante una alarma (comando beep), por si estás haciendo algo raro que no quieres que se enteren
  • Arrancar los programas que más utilizas, como por ejemplo tu programa de mensajería instantánea, por si no te gusta dejarlo siempre conectado
  • Autosincronizar el teléfono móvil para que se bajen las nuevas citas, cumpleaños y contactos
  • Muchas cosas más…

Así mismo se podría invertir la lógica para que en vez de detectar tu presencia detectase tu ausencia y en función de ello realizase alguna opción (esto vi que estaba por ahí hecho y bloqueaba tu ordenador). A mi se me ocurrió que si se alejaba tu teléfono (te lo roban) se pusiese a pitar el ordenador alertando del hurto.

Bueno, no me extiendo más, aquí va el script que está suficientemente comentado:


#!/bin/bash

#Este script se encarga de detectar los dispostivos bluetooth disponibles.
#Si encuentra uno que coincide con la variable device lanza el programa que queramos.

#Author: Jaime Bosque (aka KetS)
#e-mail: jaboto {arroba} gmail {punto} com
#date 6 / 5 / 2005

#licencia GPL
# ---------GPL-------
# Este scrip se distribuye bajo licencia GPL, puede distribuirlo y/o
# modificarlo bajo los terminos de la GNU General Public License.
# para mas informacion en castellano visite:
# http://es.tldp.org/Otros/gples/gples.html
# ---------------------
# modificado (30/04/2008): dominio público, haz con el lo que quieras... ;)

#mandar sugerencias y/o bugs a la direccion de arriba!

#En device introduce el nombre de tu móvil o dispositivo bluetooth
device=Original
file=scanBT.txt
program="xmms -p -Q ~/musiquita.m3u"

#primero eliminamos el archivo $file si existiese
rm $file

while true
do
#Scanneo de dispositivos BT
echo "Buscando dispositivos BlueTooth"
`hcitool sca > $file`

#Buscamos dentro del archivo que queremos $file, con una entrada nos bastara
# ademas con el parametro -o evitamos que salga la parte de la linea
# que no coincide con nuestra variable que buscamos.

var1=`grep --max-count=1 -o $device $file`

if [ $var1 = $device ]
then
break
else
echo "no encontrada"
fi

#Dormimos 10 segundos
sleep 10
done

echo "Encontrado $device"
echo "Ahora lanzara el programa $program"
$program

Algunas anotaciones:

  • Cambiar el nombre del dispositivo
  • Recomiendo ejecutarlo redirigiendo la salida a null (ej: ./bluetooth > /dev/null) para que no muestre las salidas