Category 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.

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.

Nuevo script para realizar backups

Ayer estuve escribiendo un nuevo script para realizar los backups en mi sistema, ya que mis necesidades han cambiado.

El script está adaptado a mi sistema y como digo, mis necesidades, pero quizás os pueda servir a vosotros.

#!/bin/bash
#    Backup for my system.
#    Copyright (C) <2011>  <Adrian 'aesptux' 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/>.

#    Check if the folder with the ID name exists
#    Mount the device
#    Backup our files
#    Unmount the device
NOW=$(date +%Y-%m-%d)
LOGPATH="/root/backup/"
LOGFILE="$NOW.backup.log"
ERRORMSG="zenity --error --title Error --text "
INFOMSG="zenity --info --title Information --text "
RSYNC="rsync -avuz --progress --delete "
# Device info
DEV1="/dev/sda2/"
LABEL1="Multimedia"
ID1="A61052121051EA37"
PATH1="Backup/actual"

clear
if [ $UID -ne 0 ]; then
	$ERRORMSG "Sorry you have to run this script as root"
	exit 1
else
	if [ ! -d /media/$ID1 ]; then
		mkdir /media/$ID1
		if [ $? -eq 0 ]; then
			echo "Folder created" | tee -a $LOGPATH$LOGFILE
		else
			$ERRORMSG "Error creating folder. Exiting"
			echo "Error creating folder. Exiting" | tee -a $LOGPATH$LOGFILE
			exit 2
		fi
	fi
	mount $DEV1 /media/$ID1
	if [ $? -eq 0 ]; then
		echo "Disk mounted." | tee -a $LOGPATH$LOGFILE
		$INFOMSG "Backup started"
		$RSYNC /etc /media/$ID1/$PATH1 2>> $LOGPATH$LOGFILE
		$RSYNC /var /media/$ID1/$PATH1 --exclude "/var/cache/*" 2>> $LOGPATH$LOGFILE
		$RSYNC /home /media/$ID1/$PATH1 --exclude "/home/mortuus/Downloads/*" --exclude "/home/mortuus/Videos/*" --exclude "/home/mortuus/.VirtualBox/HardDisks/*" --exclude "/home/mortuus/.local/share/Trash/*" --exclude "/home/mortuus/.cache/*" --exclude "/home/mortuus/.thumbnails/*" --exclude "/home/mortuus/Dropbox" 2>> $LOGPATH$LOGFILE
		###### MYSQL DATABASES DUMP
		mysqldump --all-databases -u root -p123456789a > /media/$ID1/$PATH1/$NOW.mysqldump.sql 2>> $LOGPATH$LOGFILE
		umount $DEV1
		$INFOMSG "Backup finished"
	else
		$ERRORMSG "Disk failed to mount. Exiting" 
		echo "Disk failed to mount. Exiting" | tee -a $LOGPATH$LOGFILE
		exit 3
	fi
fi

También podéis encontrarlo en mi Github

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