Mostrando entradas con la etiqueta Script. Mostrar todas las entradas
Mostrando entradas con la etiqueta Script. Mostrar todas las entradas

Conversor de videos a mp3 y ogg

d
Autor: Cristian Sacristán.
Descripción:  Este script, convierte todo el material multimedia a formato MP3 o OGG. Muy útil para descargar varios videos de Youtube y directamente convertirlos todos en formato de solo audio.

#!/bin/bash
#Convierte todo el contenido de una carpeta a un archivo de audio OOG o MP3.
#Hacer que el separador sea un salto de linea y no una palabra.
IFS=$'\n'

echo 'Menu'
echo '1. OGG'
echo '2. MP3'
echo 'Escribe el formato de salida'
read num

#Definir el tipo de archivo para la salida de la conversión
if [ $num = 1 ]; then
 num=ogg
else
 num=mp3
fi

#Meter cada linea del ls en la variable lista.
lista=$(ls)
for i in $lista
 do
  #Quitar el propio archivo de la conversión por posibles fallos.
  if [ $i = "audio.sh" ];
  then
    echo "Debe de instalar ffmpeg y los codec's de conversión"
   else
    #La conversión.
    ffmpeg -i $i $i.$num
  fi
 done

exit
Leer más...

Script para cambiar el mirror de Arch Linux

d
Autor: @jorgicio
Descripción:  Script que nos permite cambiar de mirror en ArchLinux



#!/bin/bash
HORA=`date +%H`
MINUTO=`date +%M`
RUTAMIRRORPACMANCHILE=/etc/pacman.d/mirrorlist.chile
RUTAMIRRORPACMANBRASIL=/etc/pacman.d/mirrorlist.brasil
MIRRORLISTPACMAN=/etc/pacman.d/mirrorlist
if [ $HORA -lt 19 ];then
    if [ $HORA -ge 10 ];then
        cat $MIRRORLISTPACMAN | grep .br
        if [ $? == 1 ];then
            cp $RUTAMIRRORPACMANBRASIL $MIRRORLISTPACMAN
            zenity --info --text="Mirror actualizado a: Brasil"
        fi
    fi
elif [ $HORA == 19 ];then
    if [ $MINUTO -ge 15 ];then
        cat $MIRRORLISTPACMAN | grep .cl
        if [ $? == 1 ];then
            cp $RUTAMIRRORPACMANCHILE $MIRRORLISTPACMAN
            zenity --info --text="Mirror actualizado a: Chile"
        fi
    fi
else
    if [ $HORA -le 23 ];then
        cat $MIRRORLISTPACMAN | grep .cl
        if [ $? == 1 ];then
            cp $RUTAMIRRORPACMANCHILE $MIRRORLISTPACMAN
            zenity --info --text="Mirror actualizado a: Chile"
        fi
    fi
fi
Leer más...

Script UI para MPlayer

d
Autor: Desconocido
Descripción: Script que nos permite tener una pequeña UI por medio de Zenity para Mplayer

#!/bin/bash
function video {
VIDEO=$(zenity --file-selection --title "Selecciona un video")
}
video
if [ "0" = "$?" ]; then
    aoss mplayer -vo x11 $VIDEO
elif [ "1" = "$?" ]; then
   zenity --error --title "Mplayer" --text "No seleccionaste un video"
   exit
fi
Leer más...

wav2mp3.bash

d
Nombre: wav2mp3.bash
Autor: Desconocido
Descripción: Script que permite convertir archivos .wav a .mp3
#!/bin/bash
# name of this script: wav2mp3.sh
# wav to mp3


iflame=`type -p lame`
	if [ -z $iflame ]; then
		echo -e "\n\nlame necesita estar instalado\n"
		exit 1
	fi

for i in *.wav; do
 if [ -e "$i" ]; then
   file=`basename "$i" .wav`
   lame -h -b 192 "$i" "$file.mp3"
 fi
done
exit 0
Permisos: chmod +x wav2mp3.bash 
Ejecución: ./wav2mp3.bash
Leer más...

Scrip para extraer las cuentas de correo pertenecientes a un dominio

d
Descripción El presente Script se diseño para extraer información referente a las cuentas de correo resentes en Zimbra.
Autor: Desconocido



USO:

Para ejecutar el Script vamos al directorio que lo contiene y ejecutamos lo siguiente:

./cuentas.sh "parametros"

Si necesita información sobre el script
./cuentas.sh --help

Ejemplo: ./cuenta.sh example.com lista.txt example@example.com 

#!/bin/bash
if [ "$1" = "--help" ]; then
echo "./cuenta.sh   "
exit
fi
 
 
if [ "$1" = "" ]; then
echo "DEBE COLOCAR EL NOMBRE DEL DOMINIO DE LAS CUENTAS A EXPORTAR: EJ: synaptic.cl"
exit 
fi
 
if [ "$2" = "" ]; then
echo "DEBE COLOCAR EL NOMBRE DEL ARCHIVO EN EL CUAL EXPORTARA LAS CUENTAS: EJ: LISTAS.TXT"
exit
fi
 
if [ "$3" = "" ]; then
echo "DEBE COLOCAR UNA CUENTA DE CORREO ELECTRONICO PARA ENVIAR EL INFORME: EJ: SOPORTE@SYNAPTIC.CL"
exit
fi
 
 
 
DOMINIO=$1
listaDeNombres=$2
 
COMANDO1='/opt/zimbra/bin/zmprov ga '
 
echo "NOMBRE,CUENTA,ESTADO">$listaDeNombres
clear
echo "Generando Informe Espere Por Favor...."
for usuario in `/opt/zimbra/bin/zmprov -l gaa $DOMINIO`
do
 #echo -e "$usuario\n"
 #echo -e "Comando: zmprov ga $usuario |grep displayName |awk -F': ' '{print $2}'\n"
        $COMANDO1 $usuario >tmp.txt
        nombre=`cat tmp.txt | grep displayName | awk -F': ' '{print $2}'\n`
        cuenta=`cat tmp.txt | grep '# name' | awk '{print $3}'\n`
        estado=`cat tmp.txt | grep "zimbraAccountStatus:" | awk -F': ' '{print $2}'\n`
        echo "$nombre,$cuenta,$estado">>$listaDeNombres
done
echo "Enviando Correos Electronicos del Dominio $1 a $3"
mail -s "CORREOS ELECTRONICOS DOMINIO $1" $3<$listaDeNombres
echo "Proceso Terminado con Exito"
echo "eliminando archivos temporales"
rm -rf tmp.txt

Fuente
Leer más...

Script de instalación de TOR

d
Autor: Anonymous Mexico
Twitter: @MexicanH @Anonymousmexi @rofl4all @Anon_yuc
Descripcion: Script que automatiza la instalación de Tor

#!/bin/sh

colorise=1

print_welcome ()
{

echo " 
 
  @@@@@@  @@@  @@@ @@@@@@@  @@@@@@  @@@ @@@  @@@  @@@@@@ @@@@@@@  @@@@@@  @@@      @@@     
 @@!  @@@ @@!  @@@   @@!   @@!  @@@ @@! @@!@!@@@ !@@       @@!   @@!  @@@ @@!      @@!     
 @!@!@!@! @!@  !@!   @!!   @!@  !@! !!@ @!@@!!@!  !@@!!    @!!   @!@!@!@! @!!      @!!     
 !!:  !!! !!:  !!!   !!:   !!:  !!! !!: !!:  !!!     !:!   !!:   !!:  !!! !!:      !!:     
  :   : :  :.:: :     :     : :. :  :   ::    :  ::.: :     :     :   : : : ::.: : : ::.: :
  
Coded By: Anonymous Mexico
Twitter: @MexicanH @Anonymousmexi @rofl4all @Anon_yuc
"
}

get_test_url ()
{
echo "Antes de instalar tor, tienes que escribir el nombre de tu distribucion:\n"
echo " Debian unstable (sid) is "'sid'" "
echo " Debian testing is "'wheezy'" "
echo " Debian 6.0 (squeeze) is "'squeeze'""
echo " Debian 5.0 (lenny) is "'lenny'""
echo " Ubuntu 12.04 is "'precise'" "
echo " Ubuntu 11.10 is "'oneiric'""
echo " Ubuntu 11.04 is "'natty'""
echo " Ubuntu 10.10 or Trisquel 4.5 is "'maverick'""
echo " Ubuntu 10.04 or Trisquel 4.0 is "'lucid'""
echo " Ubuntu 9.10 or Trisquel 3.5 is "'karmic'""
echo " Ubuntu 8.04 is "'hardy'"\n"
  echo "distribucion : "
  read  distribucion
  echo 
echo "deb  http://deb.torproject.org/torproject.org $distribucion main" >> /etc/apt/sources.list
clear scr
echo "[*] Instalando las llaves...."
gpg --keyserver keys.gnupg.net --recv 886DDD89
gpg --export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | sudo apt-key add -
echo "Done!!"
clear scr
echo "[*] Actualizando repositorios...."
apt-get update
clear scr
echo "[*] Instalando paquetes deb"
apt-get install deb.torproject.org-keyring
echo "[*] Done!!"
clear scr
echo "[*] Instalando TOR, Privoxy, & Polipo"
apt-get install tor
echo "[*] Done!!"
apt-get install privoxy
echo "[*] Configurando privoxy"
echo "forward-socks4a / 127.0.0.1:9050 . " >> /etc/privoxy/config
apt-get install polipo
echo "[*] Configurando polipo"
cd /etc/polipo/
rm  config > /dev/null
wget --output-document=config http://www.pps.univ-paris-diderot.fr/~jch/software/polipo/config.sample 
echo "Done!!"
echo "Tor ha sido instlado satisfactoriamente."

}

if [ "$colorise" = 1 ]; then print_welcome  ; fi ;
get_test_url
Leer más...

Ruletas Rusas solo para arriesgados

d
Autor: @jorgicio
Descripción: Script para jugar a la ruleta ;)
Nota: No nos hacemos responsable por el uso de los siguientes script, solo los traemos para poder dar a conocer, la ejecución de los mismos es total responsabilidad del que los haga correr.
Verifica si eres root si es asi simplemente reinicia el sistema.

#!/bin/sh
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]; then
    [ $[ $RANDOM % 6 ] == 0 ] && (echo "Moriste xD" && sleep 3 && /sbin/reboot ) || echo "Tu sistema aun vive"
else
    echo "Para jugar a la ruleta rusa debes ser root"
fi
exit 0

Lo mismo borra el directorio raiz (Root)

#!/bin/sh
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]; then
    [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "Tu sistema aun vive"
else
    echo "Para jugar a la ruleta rusa debes ser rooEtiquetast"
fi
exit 0
#!/bin/sh
[ $[ $RANDOM % 6 ] == 0 ] && (echo "moriras muahahahahaha" && :(){ ;|:& };: ) || echo "Todo esta bajo control" 

Ruleta rusa con Fork Bomb pero en Python


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import random
def fork_bomb():
    while True:
        os.fork()
aleatorio = random.randint(0,100000000)
if aleatorio % 6 == 0:
    fork_bomb()
else:
    print "Te salvaste weon xD"
Leer más...

Script para verificar la clave de una DB y verificar si fue crackeada

d
Autor: Desconocido
Descripción: Script en Python para verificar la presencia de la clave en la DB y si fué crackeada.

#! /usr/bin/env python

from hashlib import sha1
import getpass

def get_hash(plaintext, offset=5):
  hashed = sha1(plaintext).hexdigest()
  return '0' * offset + hashed[offset:]

def check_database(database, plaintext):
  uncracked_hash = get_hash(plaintext, 0)
  cracked_hash = get_hash(plaintext)

  database.seek(0);
  line_count = 0

  for line in database:
    line_count += 1
    if uncracked_hash in line:
      print ">Found somethng on line: %d" % line_count
      return ">Warning: Your password hash is in the database but uncracked. :|"
    elif cracked_hash in line:
      print ">Found somethng on line: %d" % line_count
      return ">Warning: Your password hash is in the database and was cracked. :["

  print ">Checked all %d lines" % line_count
  return "All Clear: your password hash isn't in the database! :]"



def main():
  database = open("combo_not.txt")
  while(True):
    password = getpass.getpass("Input a password to check: \n").strip()

    print check_database(database, password) 
    print "\n\n"
    

if __name__ == "__main__":
    main()
Visto en Twitter
Leer más...

Script para limpiar la memoria de Linux

d
Autor:  Kalambu
Descripción:  Script que nos permite liberar la memoria en Linux.
Visto en: Kalambu

Uso: puede cambiar la variable percent = 70 por la que deseemos para que posteriormente lo libere

#!/bin/sh
PATH=”/bin:/usr/bin:/usr/local/bin”
# Porcentagem maxima (mude se vc achar q deve) eu deixo em 70%
percent=70
 
# Total da memoria:
ramtotal=`grep -F “MemTotal:” < /proc/meminfo | awk ‘{print $2}’`
# Memoria livre:
ramlivre=`grep -F “MemFree:” < /proc/meminfo | awk ‘{print $2}’`
 
# RAM utilizada pelo sistema:
ramusada=`expr $ramtotal – $ramlivre`
 
# Porcentagem de RAM utilizada pelo sistema:
putil=`expr $ramusada \* 100 / $ramtotal`
 
echo =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
date
echo
echo “Mem. utilizada: $putil %”;
 
if [ $putil -gt $percent ]
then
date=`date`
echo $date >> /var/log/memoria.log
echo “Mem. utilizada: $putil %” >> /var/log/memoria.log
 
echo “Memoria acima de $percent %, cache foi limpado!”;
sync
# ‘Dropando’ cache:
echo 3 > /proc/sys/vm/drop_caches
echo
free -m
echo
echo =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
else
echo “Não há necessidade de limpar o cache!”;
echo =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
unset percent ramtotal ramlivre ramusada putil
exit $?
fi
Leer más...

Script Compartir Internet móvil

d
Autor: Uremix
Descripción: Script que nos permite compartir internet.
Basado en : BrianDB


Crea un archivo iptables.conf:

#!/bin/bash
 
# Dispositivo de red de internet
EXIF="ppp0"
 
# Dispositivo de red local
INIF="eth0"
 
iptables --flush
iptables -A INPUT -i $INIF -j ACCEPT
iptables -t nat -A POSTROUTING -o $EXIF -j MASQUERADE
 
# Aceptar paquetes para reenviar procedentes de internet de conexiones ya establecidas
 
iptables -A FORWARD -i $INIF -o $EXIF -j ACCEPT
iptables -A FORWARD -i $EXIF -o $INIF -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i $INIF -j ACCEPT
iptables -P OUTPUT ACCEPT
 
echo 1 > /proc/sys/net/ipv4/ip_forward

Dar permisos al archivo.

$ chmod -v 755 iptables.conf

Darle permisos de ejecucion:

$ chmod -v 755 iptables.conf

Ejecutamos el script como root:

$ sudo ./iptables.conf

Verificamos que se han definido las reglas:


$ iptables -L -n -v

Revisar que el gateway principal sea la salida del ppp0


$ route -n

Si deseamos que las reglas se apliquen al iniciar el equipo:

$ iptables-save

Verificaciones:

 En la maquina que es el gateway verificar si tiene salida a Internet

$ dig  //Esto nos dira si podemos resolver nombres.
$ ping google.com

Realizar una traza de ruta desde una maquina de nuestra LAN(eth0). Si llega a nuestro gateway y no pasa volver a ejecutar el escript del Iptables.

$ traceroute 8.8.8.8

Nota: en caso de no conectar verificar que las maquinas clientes estén en la misma red que eth0.


Leer más...

Script Nautilus DropBox Shared

d
Autor: Kalpa
Descripción: Script que nos permite compartir directamente un archivo a nuestra carpeta de DropBox. Para hacer uso de el lo copiamos en .gnome2/nautilus-scripts y se da los permisos respectivos.

#!/bin/sh
#
# W.H. Kalpa Pathum 
# 1st June, 2010
#

# Dropbox directory
DROPBOX_DIR="$HOME/Dropbox/"

# creates a temporary file
file_list=$(mktemp)

# writes the URIs of the selected file to the temp file
echo $NAUTILUS_SCRIPT_SELECTED_URIS | sed 's/ \//\n/g' > $file_list

# iterete through the file list
for file in $(cat $file_list)
  do
 # extract the last filed from the URI, that is the file name
    filename="$(echo $file | awk -F'/' '{print $NF}' | sed 's/%20/ /g')"
    
    # creates the symbolic link
    ln -s "$(pwd)/$filename" "$DROPBOX_DIR$filename"
    
    # sets the emblem
    gvfs-set-attribute -t stringv "$filename" metadata::emblems default
    done

exit 0
Leer más...

Juego del Ahorcado.

d
Nombre: Ahorcado.bash
Autor: blackman
Descripción: Script que permite jugar "Ahorcado" en la terminal
Visto en Espacio Linux
El script hace uso de un archivo de texto donde va sacando las palabras a adivinar
#!/bin/bash

function message() {
    case $mensage in
 game_banner) #tput cup 1 $cols
   echo
   tput rev
   echo "$(tput setaf 4)EL JUEGO DEL AHORCADO EN BASH SCRIPT$(tput sgr0)"
   echo
   echo "$(tput setaf 7)$(tput bold)Contiene $(tput setaf 1)$(( $long_palabra-$espacios ))$(tput setaf 7) caracteres sin contar los espacios"
   echo "$(tput setaf 7)Puedes usar los comodines. Dispones de $(tput setaf 1)$comodines$(tput setaf 7). Para usarlos pulsa $(tput setaf 1)+"
   [[ $(( 6-intentos )) -lt 2 ]] && vida="vida" || vida="vidas"
   echo "$(tput setaf 7)Dispones de $(tput setaf 1)$(( 6-intentos )) $vida"
   #echo "$(tput setaf 7)El nombre de este país es $(tput setaf 1)$palabra"¡
   echo
   echo "$(tput setaf 7)El nombre de este país es: $(tput setaf 1)$word"
   echo -n "$(tput setaf 7)Vidas: $(tput setaf 1)"
   for (( i=1; i<=$(( 6-intentos )); i++ )); do echo -n $'\342\231\245'; done; echo
   echo -n "$(tput setaf 7)Comodines: $(tput setaf 1)"
   for (( i=1; i<=$comodines; i++ )); do echo -n $'\342\230\245'; done; echo
   echo "$(tput setaf 7)Caracteres restantes: $(tput setaf 1)$(( ($long_palabra-$espacios)-$aciertos ))"
   echo "$(tput setaf 7)Puntuación: $(tput setaf 1)$score";;
 game_over)  echo "$(tput setaf 2)Fenomenal, eres un crack";;
 game_read) read -n1 -p "$(tput setaf 7)Vida $(tput setaf 1)$intentos $(tput setaf 7)de $(tput setaf 1)5$(tput setaf 7). Introduce una letra: $(tput setaf 1)" caracter
   echo;;
 salir)  echo
   tput rev
   echo "$(tput setaf 1)GameOver$(tput sgr0)"
   echo "$(tput setaf 7)$(tput bold)Tu mejor puntuación es: $(tput setaf 1)$best_score"
   echo "$(tput setaf 7)Tu puntuación acumulada es: $(tput setaf 1)$acumulado"
   echo
   echo "$(tput setaf 7)La solución es: $(tput setaf 1)$palabra"
   echo "$(tput setaf 7)Que deseas hacer?"
   read -n1 -p "$(tput setaf 7)Pulsa $(tput setaf 1)Q $(tput setaf 7)para $(tput setaf 1)salir $(tput setaf 7)o $(tput setaf 1)G $(tput setaf 7)para $(tput setaf 1)volver a jugar$(tput setaf 7). Introduce una letra: $(tput setaf 1)" caracter
   echo "$(tput setaf 7)";;
 comodines_restantes) echo "$(tput setaf 4)Te dispones a usar un comodín. Suerte, sólo dispones de $(tput setaf 1)$comodines"
    echo "$(tput setaf 2)Comodín = $(tput setaf 1)$caracter";;
 comodines_finalizados) echo "$(tput setaf 4)Ups, has gastado todos los comodines";;
 continuar) read -n1 -p "$(tput setaf 1)Pulsar cualquier tecla para continuar$(tput setaf 7)";;
 acierto_mal) echo "$(tput setaf 4)Has fallado, ahora tienes un intento menos";;
 #acierto_letra) echo "$(tput setaf 7)Letra introducida: $(tput setaf 1)$letra";;
 acierto_bien) echo "$(tput setaf 2)Muy bien, ya casi lo tienes";;
 acierto_repetido) echo "$(tput setaf 3)Upps, Esa letra ya la has introducido";;
    esac
}
function init {
#file="diccionario"
    file="paises"
    max=$(cat $file | wc -l)
    num=$(( $RANDOM%$max ))
    palabra=$(head -$num $file | tail -1)
    aciertos=0
    #diccionario
    #palabra=$(echo ${palabra%% *,,} | sed 's/á/a/g;s/é/e/g;s/í/i/g;s/ó/o/g;s/ú/u/g')

    palabra=$(echo ${palabra,,} | sed 's/á/a/g;s/é/e/g;s/í/i/g;s/ó/o/g;s/ú/u/g;s/-/ /g;s/Á/a/g')
    long_palabra=${#palabra}
    comodines=$(( long_palabra/4 ))
    score=$(( (comodines*50)+500 ))
    #PROVISIONAL
    ###########################
    #[[ $long_palabra -lt 15 ]] && main;
    ###########################
    unset array[*]
    i=0; espacios=0; unset word
    while [[ $i -le $(( $long_palabra-1 )) ]]
 do
     caracter="${palabra:$i:1}"
     if [[ $caracter = " "  ]]
  then
      (( espacios++ ))
      caracter=" "
  else
      array=( ${array[*]} $caracter )
      caracter="-"
     fi
     word="$word $caracter"
     (( i++ ))
    done
}

function comodin {
    if [[ $comodines -gt 0 ]]
 then
     long_array=$(( ${#array[*]}-1 ))
     index=$(( $RANDOM%${#array[*]} ))
     caracter=${array[$index]}
     i=0
     while [[ $i -le $long_array ]]
  do
      if [[ ${array[$i]} = $caracter ]]
   then
       unset array[$i]
       array2=( ${array2[*]} $caracter )
       (( aciertos++ ))
       score=$(( score+50 ))
      fi
      (( i++ ))
     done
     array=( ${array[*]} )
     array2=( ${array2[*]} )
     (( comodines-- ))
     (( intentos-- ))
     mensage="comodines_restantes"; message mensage
    else
 (( intentos-- ))
 mensage="comodines_finalizados"; message mensage
    fi
    mensage="continuar"; message mensage
    game
}

function acierto {
    unset find
    long_array=$(( ${#array[*]}-1 ))
    i=0
    while [[ $i -le $long_array ]]
 do
     if [[ ${array[$i]} = $caracter ]]
  then
      unset array[$i]
      find="true"
      array2=( ${array2[*]} $caracter )
      (( aciertos++ ))
      score=$(( score+100 ))
     fi
     (( i++ ))
    done
    if [[ $find = "true" ]]
 then
     mensage="acierto_bien"; message mensage
     (( intentos-- ))
 else
     long_array2=$(( ${#array2[*]}-1 ))
     i=0
     while [[ $i -le $long_array2 ]]
  do
      if [[ ${array2[$i]} = $caracter ]]
   then
       find="true"
      fi
      (( i++ ))
     done
     if [[ $find = "true" ]]
  then
      mensage="acierto_repetido"; message mensage
      (( intentos-- ))
      score=$(( score-10 ))
  else
      mensage="acierto_mal"; message mensage
      score=$(( score-50 ))
     fi
    fi
    array=( ${array[*]} )
    array2=( ${array2[*]} )
    mensage="continuar"; message mensage
    game
}
function game {
    clear
    lines=$(( $(tput lines)/10 ))
    cols=$(( $(tput cols)/10 ))
    i=0; unset word;
    while [[ $i -le $(( $long_palabra-1 )) ]]
 do
     letra="${palabra:$i:1}"
     if [[ $letra = " "  ]]
  then
      letra=" "
  else
      unset letra_acertada
      for x in ${array2[*]}
   do
       if [[ $x = $letra ]]
    then
        letra_acertada="true"
       fi
      done
      if [[ $letra_acertada != "true" ]]
   then
       letra="-"
      fi
     fi
     word="$word $letra"
     (( i++ ))
    done
    (( intentos++ ))
    mensage="game_banner"; message mensage
    dibujo
    if [[ $intentos -gt 5 ]]
 then
     [[ $best_score -eq 0 ]] && best_score=0
     [[ $acumulado -eq 0 ]] && acumulado=0
     salir
    fi

    if [[ -z ${array[*]} ]]
 then
     [[ $score -gt $best_score ]] && best_score=$score
     acumulado=$(( acumulado+score ))
     mensage="game_over"; message mensage
     salir
    fi
    mensage="game_read"; message mensage
    if [[ $caracter = "+" ]]
 then
     comodin
    fi
    acierto
}

function dibujo {
    case $intentos in
 1) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo;;
 2) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "               | "
  echo "               | "
  echo;;
 3) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \| "
  echo "               | "
  echo;;
 4) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \|/"
  echo "               | "
  echo;;
 5) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \|/"
  echo "               | "
  echo "              /  "
  echo;;
 *) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \|/"
  echo "               | "
  echo "              / \\"
  echo;;
    esac
}
function salir {
    mensage="salir"; message mensage
    case $caracter in
 q) clear;exit;;
 g) unset word; unset intentos; unset comodines; unset aciertos; unset score; unset array[*]; unset array2[*];main;;
 *) clear; mensage="game_banner"; message mensage; dibujo; salir;;
    esac
    clear
}

function main {
    init
    game
}
main
Permisos: chmod 700 ahorcado.bash 
Ejecución: ./ahorcado.bash
Y a jugar! :D
Leer más...

Django Backup Script

d
Nombre: DJANGO BACKUP SCRIPT
Autor: (C) 2009 Guy Rutenberg
Descripción: Script que permite generar un backup del proyecto
Formas de uso
$ django_backup /path/to/my/proj
$ django_backup --db-only /path/to/my/proj
#!/bin/bash
 
# (C) 2009 Guy Rutenberg
# Backup Django sites
 
BACKUP_DIR=
FTP_HOST=
FTP_USER=
FTP_PASS=
FTP_BACKUP_DIR=
 
# end of user configurable section
 
PROG=`basename "$0"`
print_usage () {
    echo "USAGE: $0 [options] PROJ_ROOT"
    echo "Backup a Django project located in PROJ_ROOT"
}
 
print_help ()  {
    print_usage
    cat << EOF
 
Options:
    -h, --help          show this help message and exit
    --db-only           only backup the database
 
EOF
}
 
TEMP=`getopt -o h --long help,db-only -n "$PROG" -- "$@"`
if (($?)); then
    print_usage
    exit 1
fi
 
eval set -- "$TEMP"
 
DB_ONLY=0
while true ; do
    case "$1" in
        -h|--help) print_help; exit ;;
        --db-only) DB_ONLY="1" ; shift ;;
        --) shift; break;;
    esac
done
 
 
 
if [ -z "$1" ]
then
 print_usage > /dev/stderr
 exit 1
fi
 
PROJECT_DIR=$1
 
# extract database variables from settings.py
cd "$PROJECT_DIR"
 
 
DB_ENGINE=`python -c "from settings import *; print DATABASE_ENGINE"`
if [ "$DB_ENGINE" != "mysql" ]; then
 echo $DB_ENGINE
 echo "Only mysql databases are supported!">/dev/stderr
 exit 1
fi
 
DB_NAME=`python -c "from settings import *; print DATABASE_NAME"`
DB_USER=`python -c "from settings import *; print DATABASE_USER"`
DB_PASS=`python -c "from settings import *; print DATABASE_PASSWORD"`
DB_HOST=`python -c "from settings import *; print DATABASE_HOST"`
#TODO find how to use it
DB_PORT=`python -c "from settings import *; print DATABASE_PORT"`
 
# set optional parameters: host, port
HOST_ARGS=''
if [ -n "$DB_HOST" ]; then
 HOST_ARGS="--host $DB_HOST"
fi
 
PORT_ARGS=''
if [ -n "$DB_PORT" ]; then
 PORT_ARGS="--port $DB_HOST"
fi
 
SITE_DIR=`dirname "$PROJECT_DIR"`/`basename "$PROJECT_DIR"`
BACKUP_DIR=`dirname "$BACKUP_DIR"`/`basename "$BACKUP_DIR"`
 
echo -n "dumping database... "
DUMP_NAME=${DB_NAME}-$(date +%Y%m%d).sql.bz2
mysqldump --user=${DB_USER} --password=${DB_PASS} $HOST_ARGS \
 $PORT_ARGS --databases ${DB_NAME} \
 | bzip2 -c > ${BACKUP_DIR}/${DUMP_NAME}
if (($?)); then
	echo "failed!"
	exit 1
fi
echo "done"
 
PUT_TARBALL_FTP=""
if [ "$DB_ONLY" -eq "0" ]; then
	echo -n "Creating tarball... "
	TAR_NAME=${SITE_DIR##*/}-$(date +%Y%m%d).tar.bz2
	tar -cjf ${BACKUP_DIR}/${SITE_DIR##*/}-$(date +%Y%m%d).tar.bz2 ${SITE_DIR}
	if (($?)); then
		echo "failed!"
		exit 2
	fi
	echo "done"
	PUT_TARBALL_FTP="put \"${BACKUP_DIR}/${TAR_NAME}\""
fi
 
echo -n "Uploading backup to FTP... "
 
lftp -u ${FTP_USER},${FTP_PASS} ${FTP_HOST} 
Leer más...

Script para cambiar resolucion de fotos de una carpeta

d
Autor: Desconocido Descripción:Este script cambia la resolución de las fotos en una carpeta con imagemagick a 1600x1200 el cual puede ser cambiable
#!/bin/bash

echo "Resizing jpg. This may take some time. Please stand-by."
for img in `ls *.JPG`
do
  echo "processing" $img
  convert $img -resize 1600x1200 file-$img
  rm $img
done
echo "Done. Have a nice day!"
Leer más...

Envio de email cuando cambia tu IP en linux

d
Nombre: Password.pl
Autor: Caymcorp
Descripción: El script se encarga de comprobar cuál era tu dirección ip antes de ejecutarse y, si ha cambiado, te envía un correo con la nueva. La dirección de correo antigua se guarda en el fichero /etc/myip,
Visto en Caymcorp

Requerimientos.


  • sendEmail
  • El paquete knetfilter, que nos proporciona el comando getip
  • Un servidor smtp al que mandar los correos 
La automatización para el envio se puede usar el amigo CRON

#!/bin/bash

FCONF=/etc/myip
MAIL=tu_direccion_de_correo
SERVER=servidor_smtp

# Get your ip
ip=`getip eth0 | head -n 1 | cut -d ":" -f 2`;
# Get your old ip
oldip=`head -n 1 $FCONF`

# If ip has changed, send email
# and save new ip in config file
if [ $ip != $oldip ];
then
	sendEmail -f $MAIL -t $MAIL -u "Your ip: ${ip}" -m " " -s $SERVER
	echo $ip > $FCONF;
fi
Necesitamos crear el archivo myip en /etc y asignar permisos.

sudo touch /etc/myip
sudo chmod a+w /etc/myip
Leer más...

WordPress Backup Script

d
Nombre: WordPress Backup
Autor: Guy Rutenberg
Descripción: Script que automatiza y permite generar Backup de Wordpress
Visto en Guy Rutenberg
#!/bin/bash
# (C) 2008 Guy Rutenberg - http://www.guyrutenberg.com
# This is a script that creates backups of blogs.
 
DB_NAME=
DB_USER=
DB_PASS=
DB_HOST=
 
#no trailing slash
BLOG_DIR=
BACKUP_DIR=
 
 
echo -n "dumping database... "
mysqldump --user=${DB_USER} --password=${DB_PASS} --host=${DB_HOST} ${DB_NAME} \
 | bzip2 -c > ${BACKUP_DIR}/${DB_NAME}-$(date +%Y%m%d).sql.bz2
if [ "$?" -ne "0" ]; then
	echo -e "\nmysqldump failed!"
	exit 1
fi
echo "done"
 
 
echo -n "Creating tarball... "
tar -cjf ${BACKUP_DIR}/${BLOG_DIR##*/}-$(date +%Y%m%d).tar.bz2 ${BLOG_DIR}
if [ "$?" -ne "0" ]; then
	echo -e "\ntarball creation failed!"
	exit 1
fi
echo "done"
Leer más...

Script Automatizacion para instalar gcc-4.6.2

d
Autor: Joelinoff
Descripción: Script que nos automatiza la instalación de Gcc 4.6.2 descargando, compilando y ejecutando debidamente


#!/bin/bash
umask 0
mkdir -p /shared/tools/gcc/gcc-4.6.2
cd /shared/tools/gcc/gcc-4.6.2
wget http://projects.joelinoff.com/gcc-4.6.2/bld.sh
chmod a+x bld.sh
./bld.sh 2>&1 | tee bld.log
Leer más...

Script borrado interactivo

d
Autor: Leo Gutierrez
Descripción: Script para hacer un borrado interactivo

#!/bin/bash
# Script de borrado interactivo.
# Leo Gutiérrez Ramírez. leorocko13@hotmail.com
 
function rmsecure()
{
 
 select archivos in * "SALIR"
 do
  if [ "${archivos}" = "SALIR" ]
  then
 
   exit 0;
 
  elif [[ -n "${archivos}" ]]
  then
 
   sudo rm -rvi "${archivos}" || {
   echo -e "Error borrando archivo : ${archivos}";
   exit 0;
  }
 
  clear;
  rmsecure;
 
  else
 
   echo -e "Error eligiendo archivo.";
 
  fi
 
 done
}
 
clear;
rmsecure;
Leer más...

Script Cambiando de directorios interactivamente

d
Autor: |Leo Gutiérrez R.
Descripción: Script para cambiar de directorios interactivamente.
 Mail: leorocko13[at]hotmail


#!/bin/bash - 
#===============================================================================
#
#          FILE:  cdprompt.sh
# 
#         USAGE:  ./cdprompt.sh 
# 
#   DESCRIPTION:  Cambio de directorios interactivamente.
# 
#       OPTIONS:  ---
#  REQUIREMENTS:  ---
#          BUGS:  ---
#         NOTES:  ---
#        AUTHOR: |Leo Gutiérrez R.| (), |leorocko13[at]hotmail|
#       COMPANY: 
#       CREATED: 02/26/2011 01:51:28 AM CST
#      REVISION:  ---
#===============================================================================
 
select directorio in */ "SALIR"
do
 if [ "$directorio" = "SALIR" ]
 then
  break;
 elif [[ -n "$directorio" ]]
 then
  cd "$directorio"
  break;
 else 
  echo -e "\aError de opción.";
  break;
 fi
done
Leer más...

Script para navegar entre los DIspositivos USB

d
Autor: Leo Gutierrez R
Descripcion: Script que permite Navegar sobre los dispositivos USB del sistema

#!/bin/bash
# Leo Gutiérrez R.
# Script para navegar por sobre los dispositivos USB en el sistema.
# Uso personal.
select archivo in `ls -1 /media/ | grep -v "^cd$" | grep -v "^dvd$" | grep -v "^fl$" | grep -v "^ubuntu$" | grep -v "^windows$"` 
do
 if [ -n "$archivo" ]
 then
  cd /media/"$archivo"
  break;
 else
  echo -e "Error eligiendo dispositivo";
  exit 1;
 fi
done
Leer más...