Tag Archives: bash

Convert m4a files to mp3 with this script.

Some of my library was in m4a files, which I have problems to play, furthermore I prefer having everything in mp3 format.

So I wrote the following script:

echo "Dependencies: mplayer and lame"
if [ $# -lt 1 ]; then
	echo "Usage: sh m4a2mp3.sh '/path/to/files'"
else 
	echo "This could take sometime. Converting to 320kbps MP3 files..."
	sleep 1
	cd "$1"
	for i in *.m4a; do mplayer -ao pcm "$i" -ao pcm:file="$i.wav"; done
	for i in *.wav; do lame -h -b 320 "$i" "$i.mp3"; done
	echo "Cleaning the house..."
	rm -rf *.m4a
	rm -rf *.wav
fi
echo "All files converted. Thank you."

Usage is pretty straightforward:

sh m4a2mp3.sh /path/to/your/songs

The only dependencies, as you can see also in the script are mplayer and lame

You can install them with the following command:

# Yum based (Fedora, CentOS, SuSE)
yum install mplayer lame
# Apt based (Debian, Ubuntu, Mint) (NOT TESTED)
apt-get install mplayer lame

As always, you also can find the script on my Github.

Reset NICs by unloading / loading network drivers

This script is specially useful when you clone VMs, but can be used in any other kind of situation where you have problems with network cards, say, duplicated cards for X reason.

Try to run this script I wrote:

if [ $UID -ne 0 ] 
then
	echo "Sorry, you have to run this script as root"
else
	cat /etc/udev/rules.d/70-persistent-net.rules | grep PCI | cut -d' ' -f5 | cut -b 2-6 | uniq > /tmp/drivers
	for driver in $(cat /tmp/drivers); do
		rm -rf /etc/udev/rules.d/70-persistent-net.rules && echo "Removing 70-persistent-net.rules"
		rmmod $driver && echo "Removing $driver"
		modprobe $driver && echo "Loading $driver"
	done
	echo "Done."
	rm -rf /tmp/drivers
fi

Tested under Debian and Fedora, but should work fine on other distributions.

The code is also on my github

Examples of APG

Generate random password with apg.

Quick tip.

If you want to generate a random password, you could use /dev/random, but it is more complex than using apg (Automated Password Generator).

So, to install apg on Fedora, run this command:

# yum install apg

Useful parameters:

  • -a algorithm choose algorithm
    • 1 – random password generation according to password modes
    • 0 – pronounceable password generation
  • -n num_of_pass           generate num_of_pass passwords
  • -m min_pass_len         minimum password length
  • -x max_pass_len          maximum password length
  • -l spell generated password
  • -t print pronunciation for generated pronounceable password

Some examples:

Examples of APG
Examples of APG. Click to zoom.

Short and useful tip: How to make “tail -f” beep on each new line.

Just in case you do not know, tail prints the last ten lines of the indicated file. Like this:

tail /var/log/yum.log

Furthermore, if you want to print more lines you can do it with -n parameter:

tail -n 20 /var/log/yum.log

But I think the most interesting parameter for tail  is -f. This parameter allows tail to “follow” the file. New data is displayed as the file grows.

Now, using sed  we can append to each new line, a bell sound:

tail -f /var/log/yum.log | sed -e $'s/$/\a/'

Notice that ‘$’ escape sequences will only work on bash.

This was tested on Fedora 16.

Bash script que busca hosts en tu red, sincroniza carpetas y después apaga los hosts.

En clase nos pidieron hacer un script que buscase hosts en tu red para después apagarlos, o que incluso antes de apagarse sincronizasen unas carpetas.

He tratado de automatizarlo todo lo que he podido, en mi red funciona perfectamente, y el único requerimiento previo es que todos los hosts tengan instalado un servidor SSH. Este script esta pensado para hosts Linux, pero con algunos pequeños cambios se podría adaptar para Windows también.

El código es el siguiente:

#!/bin/bash
# Find online hosts on your network, backup a directory and halt them
# Copyright (C) <2011> <Adrian Espinosa>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# If you don't want to write every password, you should add the hosts keys to your machine.
clear
f=`echo networkscanned_$(date +%Y%m%d)`
me=`echo $(whoami)`
DIR="put_here_your_dir_to_sync"
DEST="put_here_your_destination"
if [ $UID -ne 0 ]
then
   echo "Sorry, you have to run this script as root"
else
   net=`ip route show | grep / | cut -d " " -f1`
   echo "Please, wait while your network is scanned"
   completescan=`nmap -sP $net | grep "is up" | cut -d " " -f2`
   clear
   echo "$completescan" > $f
   gateway=`ip route show | grep via | cut -d " " -f3`
   cat $f | egrep -v `echo $gateway$` > /tmp/net
   cat /tmp/net > $f
   rm -rf /tmp/net
   ownip=`ip route show | grep src | cut -d " " -f12`
   cat $f | grep -v $ownip > /tmp/net
   cat /tmp/net > $f
   rm -rf /tmp/net
   echo "Starting synchronization"
   for host in $(cat $f)
   do
     echo "Syncing with $host"
     rsync --progress -avhe ssh $me@$host:$DIR $DEST &> backup.log
     ssh $me@$host "shutdown -h now" &> backup.log
   done
   echo "Done. You may check backup.log to see if there are any errors"
   rm -rf $f
   exit 0
fi # END

 

Hay que ser root para ejecutarlo y básicamente lo que hace es lo siguiente

  • Si NO eres root
    • Sale del programa
  • Si eres root
    • Detecta tu red y máscara
    • Escanea con nmap y recoge sólo la IP de los hosts y la guarda en fichero
    • Detecta cuál es tu ip y tu gateway y los elimina del fichero anterior
    • Recorre el fichero leyendo cada hosts y haciendo las correspondientes operaciones

.

Este script lo he probado en Debian, y como digo funciona correctamente. En ubuntu hay que hacer unos pequeños cambios que podéis encontrar en mi github, también está publicado este script.

10 herramientas para dar más vida a tus scripts en shell

En la mayoría de nuestros scripts, no utilizamos para nada una GUI, pero a veces, si es un script que va a ir enfocado al usuario, es mejor intentar usar una GUI para que sea más amigable.

Es una tarea que a lo mejor cuesta más porque hay que dedicarle un poco más de tiempo, pero es algo que merece la pena, no todos aprecian la belleza de la consola :D

  • Notify-send

Comando que envía notificaciones a través del daemon de notificaciones (por defecto, se muestran casi en la esquina superior derecha). Para poder utilizar ese comando, debemos instalar:

$ sudo apt-get install libnotify-bin

Después basta con un simple:

$ notify-send “texto”

Esto puede ser útil para mensajes que no tengan por qué interferir en la actividad, del usuario… por ejemplo para informarle de algo.

notify-send

notify-send

  • Comando setleds

Cambiar el estado de los leds del teclado

$ setleds -D +num

Activaría el NumLock

$ setleds -D -caps

Desactivaría el CapsLock

  • Zenity

Uno de mis favoritos. Muestra diálogos utilizando GTK+. Nos permite mostrar información, pedir datos al usuario, etc…

Zenity

Zenity

El resto de las herramientas, las podéis encontrar aquí

Enlace | nixCraft

Cambiar la shell por defecto

El comando chsh, permite cambiar la shell que tenemos por defecto.

Es práctico, si nuestro administrador nos ha asignado una shell con la que no estamos cómodos, o simplemente, que queremos probar otras shells.

La sintaxis básica del comando es

Chsh usuario nueva_shell

El parámetro de la shell, debe ser la ruta completa a la shell, como por ejemplo /bin/bash

Si no sabes que shell tienes, puedes escribir:

Echo $SHELL