checkMemory.sh

d
Nombre: checkMemory.sh
Autor: Cristian Hernandez
Descripcion: Monitorea el uso total de la memoria.
#!/bin/bash
#===============================================================================
# Author:
#               Cristian Hernandez

#===============================================================================
#
# Description:
#           Monitor total memory usage.
#
# Parameters:
#       -w: Warning threshold (in percentiles)
#       -c: Critical threshold (in percentiles)
#       -h: Help message
#
#===============================================================================

#
# FUNCTIONS:
#
#-------------------------------------------------------------------------------
# Check CPU activity. Returns OK, WARNING or CRITICAL status based on command
# line arguments
function check_memory() {
    local warning=$1
    local critical=$2
    local results=($(free -m | awk 'BEGIN {
                total=0;
                rss=0
            }
            {
                if ($1 == "Mem:") {
                    total=$2; # Memory total
                    vmz=$3;   # Memory in use (VMZ)
                }
                if ($1 == "-/+") {
                    rss=$3         # Memory in use (RSS)
                    cache=vmz-$3;  # Memory in cache
                }
            }
            END {
                # Return array of results: [percent_memory_used, memory_in_cache]
                print int(rss/total*100), cache

            }'))

    echo "Current:${results[0]} Threshold:[${warning}/${critical}]% Cache:${results[1]}MB"
    # Check status and exit accordingly
    [ "${results[0]}" -gt "$critical" ] && exit 2
    [ "${results[0]}" -gt "$warning" ] && exit 1

    exit 0

}

#-------------------------------------------------------------------------------

# Help message
function usage() {
    echo "Usage:
    -w: Warning threshold (in percentiles, i.e. from 0 to 100)
    -c: Critical threshold (in percentiles, i.e. from 0 to 100)
    -h: This Help message

    Example: $0 -w 70 -c 90"
}

#-------------------------------------------------------------------------------

#
# MAIN:
#

#-------------------------------------------------------------------------------

# Check command line options

while getopts 'c:w:h' OPT
do
    case $OPT in
        w) warning=${OPTARG}
        ;;
        c) critical=${OPTARG}
        ;;
        h) usage && exit 1
        ;;
    esac
done

# Validate command line arguments
if [ $# -eq 4 ]; then
    if [ "$critical" -gt "$warning" ]; then
        # Check memory usage and exit accordingly
        check_memory $warning $critical
    else
        echo "ERROR: critical threshold must be greater than warning threshold"
        usage
        exit 1
    fi
else
    echo "ERROR: Missing argument!"
    usage
    exit 1
fi
Leer más...

iptables-rules-generator.sh

d
Nombre: iptables-rule-generator.sh
Autor: Ricardo del Castillo @WizardIP
Descripcion: Generador básico de reglas de IPTables por puerto, interface, dirección IP o segmento para colocar en el archivo generado por el comando iptables-save.
#!/bin/bash 

#@WizardIP

if [ $# -lt 1 ] 
then 
        echo "Usage : $0 [ OPTION  ]" 
        echo "Options are:" 
        echo "by Port" 
        echo "by Interface" 
        echo "by Address (Full Access)" 
        echo "by Segment" 
        exit 1 
fi 

NUM='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' 
NUM2='^-?[0-9]+$' 
case "$1" in 

P) 
echo "Give me the IP" 
        read IP 
        if ! [[ $IP =~ $NUM ]]; then 
                echo "Please use numeric values" 
                exit 1 
        fi 
echo "Give me the Port" 
        read PORT 
        if ! [[ $PORT =~ $NUM2 ]]; then 
                echo "Please use numeric values" 
                exit 1 
        fi 
echo "Generating Rules...Please append it in the config file /etc/iptables.rules.date" 
sleep 3 
echo "-A INPUT -s $IP/32 -p tcp -m tcp --dport $PORT -j ACCEPT" 
echo "-A OUTPUT -d $IP/32 -p tcp -m tcp --sport $PORT -j ACCEPT" 
;; 

I) 
echo "Give me the Interface" 
        read INTER 
echo "Give me the IP" 
        read IP 
        if ! [[ $IP =~ $NUM ]]; then 
                echo "Please use numeric values" 
                exit 1 
        fi 
echo "Generating rules...Please append it in the config file /etc/iptables.rules.date" 
sleep 3 
echo "-A INPUT -i $INTER -p tcp -s $IP/32 -j ACCEPT" 
echo "-A OUTPUT -o $INTER -p tcp -d $IP/32 -j ACCEPT" 
;; 

A) 
echo "Give me the IP" 
        read IP 
        if ! [[ $IP =~ $NUM ]]; then 
                echo "Please use numeric values" 
                exit 1 
        fi 
echo "Generating rules...Please append it in the config file /etc/iptables.rules.date" 
sleep 3 
echo "-A INPUT -s $IP -j ACCEPT" 
echo "-A OUTPUT -d $IP -j ACCEPT" 
;; 

S) 
echo "Give me the IP" 
        read IP 
        if ! [[ $IP =~ $NUM ]]; then 
                echo "Please use numeric values" 
                exit 1 
        fi 
echo "Give me the Interface" 
        read INTER 
echo "Generating rules...Please append it in the config file /etc/iptables.rules.date" 
sleep 3 
echo "-A INPUT -i $INTER -s $IP/24 -j ACCEPT" 
echo "-A OUTPUT -o $INTER -d $IP/24 -j ACCEPT" 
;; 

*) 
echo "Invalid option" 
echo "Usage : $0 [ OPTION  ]" 
        echo "Options are:" 
        echo "by Port" 
        echo "by Interface" 
        echo "by Address" 
        echo "by Segment" 
        exit 1 
;; 
esac 
Leer más...

Audifonos.sh

d
Autor: rain
Descripción: Script para quitar el volumen cuando se desconectan los audífonos
Más información del script en: Desde Linux
NOTA: El script hace uso de alsa-utils por lo que debe instalarse
#!/bin/bash
cd ~
#si no existe el archivo se "instala" en realidad solo copia un archivo
if [ ! -f ".audifonos/con" ]; then
mkdir .audifonos
read -n1 -r -p "Por favor conecte los audifonos y presione una tecla " l
echo;
cp "/proc/asound/card0/codec#0" ".audifonos/con"
echo "si los audifonos estaban desconectados borre la carpeta $HOME/.audifonos y repita"
read -n1 -r -p "instalado - ejecute de nuevo para iniciar" k
echo;
else
encontrado="1"
while true; do
echo $encontrado
 #diff muestra las diferencias entre el archivo codec#0 de alsa y el que copiamos con los audifonos puestos y luego filtramos la info sobre la conexion de audifonos con grep
 diff "/proc/asound/card0/codec#0" ".audifonos/con" | grep Pin-ctls 
 #si $? == 0 entonces los audifonos estan desconectados
 if [ "$?" == "0" ]; then
   #la variable encontrado solo es una forma de controlar el flujo del programa asi permito que cuando este desconectado los audifonos se pueda subir el volumen 
   if [ $encontrado == "0" ]; then
   amixer sset 'Master' 0%
   encontrado="1"
   fi
 
 else
  encontrado="0"

 fi
 #espero 0.5 para que no sea pesado el proceso pero si se quisiera que fuera instantanea se puede quitar o pponer menos tiempo
 sleep 0.1
 
done
fi
Leer más...

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

Lastlog script for Solaris

d
Nombre: lastlog.pl
Autor: ph
Visto en: Tech Notes
#!/usr/local/bin/perl

# month names for common usage

@months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
           'Sep', 'Oct', 'Nov', 'Dec');

setpwent;
while (($name, $junk, $uid) = getpwent) {
        $names{$uid} = $name;
}
endpwent;

open(LASTL,'/var/adm/lastlog');

for ($uid = 0; read(LASTL, $record, 28); $uid++) {
    ($time, $line, $host) = unpack('l A8 A16', $record);
    next unless $time;

    $host = "($host)" if $host;
    ($sec, $min, $hour, $mday, $mon, $year) = localtime($time);

    printf "%-9s%-8s%s %2d %4d    %s\n",
        $names{$uid}, $line, $months[$mon], $mday, 1900+$year, $host;
}
Leer más...

evomalware.sh

d
Nombre: evomalware.sh
autor: benpro@benpro.fr
Permite detectar virus, backdoors y malware especialmente en archivos PHP.
Visto en: evoforge

#!/bin/bash
# EvoMalware, script to detect infected websites.

# You can set aggressive to true to search for suspicions scripts.
aggressive=false
# Path to search for.
wwwpath=/home
# URL to download patterns and filenames.
databaseURL="http://antispam00.evolix.org/evomalware"
databasePATH=/var/lib/evomalware
# Tools.
find="ionice -c3 find -O3"
grep="nice -n 19 grep"
wc="nice -n 19 wc"
wget="wget -q -t 3"
md5sum="md5sum --status -c"
# Various.
fileslist=$(mktemp)
tmpPATH=/tmp/evomalware.tmp

trap "rm -rf $fileslist $tmpPATH" EXIT

usage() {
    cat< $fileslist 2>/dev/null
while read file; do
    # Search known filenames.
    if [[ "$file" =~ $filenames ]]; then
        echo "Known malware: $file"
    # Search .php files in WP's wp-content/uploads/
    elif [[ "$file" =~ "wp-content/uploads/" ]]; then
        echo "PHP file in a non-PHP folder detected: $file"
    # Count the length of the longest line and search if suspect php functions are used.
    elif [[ $($wc -L "$file" 2>/dev/null | cut -d' ' -f1) -gt 10000 ]]; then
        grep -q -E "$suspect" "$file"
        if [[ $? -eq 0 ]]; then
            echo "Suspect file! More than 10000 characters in one line (and suspect PHP functions): $file."
        fi
    else
        # Search for patterns.
        $grep -H -E -r -l -q "$patterns" "$file" 2>/dev/null
        if [[ $? -eq 0 ]]; then
            echo "Contains a known malware pattern: $file"
        fi
    fi
done < $fileslist

# Search for suspicious scripts... Only when in aggressive mode.
if ( $aggressive ); then
    cd $wwwpath
    $find . -name javascript.php
    $find . -name bp.pl
    $find . -name tn.php
    $find . -name tn.php3
    $find . -name tn.phtml
    $find . -name tn.txt
    $find . -name xm.php
    $find . -name logs.php
    $find . -type f -name "*.php" -exec sh -c 'cat {} | awk "{ print NF}" | sort -n | tail -1 | tr -d '\\\\n' && echo " : {}"' \; | sort -n | tail -10
    $find . -type f -name "*.php" -exec sh -c 'cat {} | awk -Fx "{ print NF}" | sort -n | tail -1 | tr -d '\\\\n' && echo " : {}"' \; | sort -n | tail -10
    $grep -r 'ini_set(chr' .
    $grep -r 'eval(base64_decode($_POST' .
    $grep -r 'eval(gzinflate(' .
    $grep -r 'ini_set(.mail.add_x_header' .
    $grep -r '@require' .
    $grep -r '@ini_set' .
    $grep -ri 'error_reporting(0' .
    $grep -r base64_decode .
    $grep -r codeeclipse .
    $grep -r 'eval(' .
    $grep -r '\x..\x..' .
    $grep -r 'chr(rand(' .
fi

Leer más...

Script para monitorizar el estado de un servidor

d
Nombre: tecmint_monitor.sh
Autor: Tecmint.com
Visto en: Tecmint

                  ####################################################################################################
                  #                                        Tecmint_monitor.sh                                        #
                  # Written for Tecmint.com for the post www.tecmint.com/linux-server-health-monitoring-script/      #
                  # If any bug, report us in the link below                                                          #
                  # Free to use/edit/distribute the code below by                                                    #
                  # giving proper credit to Tecmint.com and Author                                                   #
                  #                                                                                                  #
                  ####################################################################################################
#! /bin/bash
# unset any variable which system may be using

# clear the screen
clear

unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage

while getopts iv name
do
        case $name in
          i)iopt=1;;
          v)vopt=1;;
          *)echo "Invalid arg";;
        esac
done

if [[ ! -z $iopt ]]
then
{
wd=$(pwd)
basename "$(test -L "$0" && readlink "$0" || echo "$0")" > /tmp/scriptname
scriptname=$(echo -e -n $wd/ && cat /tmp/scriptname)
su -c "cp $scriptname /usr/bin/monitor" root && echo "Congratulations! Script Installed, now run monitor Command" || echo "Installation failed"
}
fi

if [[ ! -z $vopt ]]
then
{
echo -e "tecmint_monitor version 0.1\nDesigned by Tecmint.com\nReleased Under Apache 2.0 License"
}
fi

if [[ $# -eq 0 ]]
then
{


# Define Variable tecreset
tecreset=$(tput sgr0)

# Check if connected to Internet or not
ping -c 1 google.com &> /dev/null && echo -e '\E[32m'"Internet: $tecreset Connected" || echo -e '\E[32m'"Internet: $tecreset Disconnected"

# Check OS Type
os=$(uname -o)
echo -e '\E[32m'"Operating System Type :" $tecreset $os

# Check OS Release Version and Name
cat /etc/os-release | grep 'NAME\|VERSION' | grep -v 'VERSION_ID' | grep -v 'PRETTY_NAME' > /tmp/osrelease
echo -n -e '\E[32m'"OS Name :" $tecreset  && cat /tmp/osrelease | grep -v "VERSION" | cut -f2 -d\"
echo -n -e '\E[32m'"OS Version :" $tecreset && cat /tmp/osrelease | grep -v "NAME" | cut -f2 -d\"

# Check Architecture
architecture=$(uname -m)
echo -e '\E[32m'"Architecture :" $tecreset $architecture

# Check Kernel Release
kernelrelease=$(uname -r)
echo -e '\E[32m'"Kernel Release :" $tecreset $kernelrelease

# Check hostname
echo -e '\E[32m'"Hostname :" $tecreset $HOSTNAME

# Check Internal IP
internalip=$(hostname -I)
echo -e '\E[32m'"Internal IP :" $tecreset $internalip

# Check External IP
externalip=$(curl -s ipecho.net/plain;echo)
echo -e '\E[32m'"External IP : $tecreset "$externalip

# Check DNS
nameservers=$(cat /etc/resolv.conf | sed '1 d' | awk '{print $2}')
echo -e '\E[32m'"Name Servers :" $tecreset $nameservers 

# Check Logged In Users
who>/tmp/who
echo -e '\E[32m'"Logged In users :" $tecreset && cat /tmp/who 

# Check RAM and SWAP Usages
free -h | grep -v + > /tmp/ramcache
echo -e '\E[32m'"Ram Usages :" $tecreset
cat /tmp/ramcache | grep -v "Swap"
echo -e '\E[32m'"Swap Usages :" $tecreset
cat /tmp/ramcache | grep -v "Mem"

# Check Disk Usages
df -h| grep 'Filesystem\|/dev/sda*' > /tmp/diskusage
echo -e '\E[32m'"Disk Usages :" $tecreset 
cat /tmp/diskusage

# Check Load Average
loadaverage=$(top -n 1 -b | grep "load average:" | awk '{print $10 $11 $12}')
echo -e '\E[32m'"Load Average :" $tecreset $loadaverage

# Check System Uptime
tecuptime=$(uptime | awk '{print $3,$4}' | cut -f1 -d,)
echo -e '\E[32m'"System Uptime Days/(HH:MM) :" $tecreset $tecuptime

# Unset Variables
unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage

# Remove Temporary Files
rm /tmp/osrelease /tmp/who /tmp/ramcache /tmp/diskusage
}
fi
shift $(($OPTIND -1))

Leer más...

imap2gmail.sh

d
Nombre: imap2gmail.sh
Autor: Desconocido
Visto en Otel Consulting
Nota: Se necesita tener instalado el programa imapsync
#!/bin/sh
 
#Configure User
SERVER1=imap.anotherserver.com
UNAME1=demo@anotherserver.com
PWORD1=54321
UNAME2=demo@gmail.com
PWORD2=12345
 
#Blank this out if you want to see folder sizes
HIDE="--nofoldersizes --skipsize"
 
imapsync --syncinternaldates --useheader 'Message-Id' \
--host1 ${SERVER1} --user1 ${UNAME1} \
--password1 ${PWORD1} --ssl1 \
--host2 imap.googlemail.com \
--port2 993 --user2 ${UNAME2} \
--password2 ${PWORD2} --ssl2 \
--authmech1 LOGIN --authmech2 LOGIN --split1 200 --split2 200 ${HIDE} \
--exclude 'Drafts|Trash|Spam|Sent'
 
#TO Sync Special Folders to Gmail
imapsync --syncinternaldates --useheader 'Message-Id' \
--host1 ${SERVER1} --user1 ${UNAME1} \
--password1 ${PWORD1} --ssl1 \
--host2 imap.googlemail.com \
--port2 993 --user2 ${UNAME2} \
--password2 ${PWORD2} --ssl2 \
--ssl2 --noauthmd5 --split1 200 --split2 200 ${HIDE} \
--folder "Inbox/Sent" --prefix2 '[Gmail]/' --regextrans2 's/Inbox\/Sent/Sent Mail/' \
--folder "Inbox/Spam" --prefix2 '[Gmail]/' --regextrans2 's/Inbox\/Spam/Spam/' \
--folder "Inbox/Trash" --prefix2 '[Gmail]/' --regextrans2 's/Inbox\/Trash/Trash/' \
--folder "Inbox/Drafts" --prefix2 '[Gmail]/' --regextrans2 's/Inbox\/Drafts/Drafts/' \
Leer más...

actualizaflash.sh

d
Nombre: actualizaflash.sh
Autor: Esteban M. Navas
Visto en Algo de Linux
@algodelinux
#!/bin/bash # 
# actualizaflash -> Actualiza el plugin de flash, si no se encuentra actualizado ya 
# # Esteban M. Navas 
# IES Valle del Jerte - Plasencia 
# 26/02/2015  

# Instalamos el paquete flashplugin-nonfree, si no está instalado aún 
dpkg -l | grep ^"ii flashplugin-nonfree" > /dev/null || apt-get -y install flashplugin-nonfree

update-flashplugin-nonfree --status | grep -e installed -e available > /tmp/flashplugin installed=`grep "installed" /tmp/flashplugin | cut -f2 -d":" | sed 's/^ *//g'` available=`grep "available" /tmp/flashplugin | cut -f2 -d":" | sed 's/^ *//g'`

if [ "$installed" != "$available" ]; 
       then update-flashplugin-nonfree --install 
fi 
Leer más...

Amazon S3 Uploader

d
Nombre: Amazon S3 Uploader
Descripción: Script que permite subir archivos a una instancia de S3 vía BASH
Autor: guss77
geek.co.il
Más información del script en: Things n' Stuff
#!/bin/bash
file="$1"

key_id="YOUR-AWS-KEY-ID"
key_secret="YOUR-AWS-KEY-SECRET"
path="some-directory/$file"
bucket="s3-bucket-name"
content_type="application/octet-stream"
date="$(LC_ALL=C date -u +"%a, %d %b %Y %X %z")"
md5="$(openssl md5 -binary < "$file" | base64)"

sig="$(printf "PUT\n$md5\n$content_type\n$date\n/$bucket/$path" | openssl sha1 -binary -hmac "$key_secret" | base64)"

curl -T $file http://$bucket.s3.amazonaws.com/$path \
    -H "Date: $date" \
    -H "Authorization: AWS $key_id:$sig" \
    -H "Content-Type: $content_type" \
    -H "Content-MD5: $md5"
Leer más...

Fortibackup.py - Robot para sacar copias de seguridad de dispositivos fortigate

d
Nombre: Fortibackup.py
 Autor: @epsilon77
 Tomado de DragonJar

 #!/usr/bin/python
import os
import sys
import optparse
"""
        FortiBackup
       
        author: epsilon77 at gmail
       
        Licensed under the GNU General Public License Version 2 (GNU GPL v2),
            available at: http://www.gnu.org/licenses/gpl-2.0.txt
       
        (C) 2014 Daniel Echeverry
"""

parser = optparse.OptionParser()
parser.add_option('-f', '--file', help='Ruta archivo matrix',dest='file', action='store')
(opts, args) = parser.parse_args()

if opts.file is None:
    parser.print_help()
        exit(-1)

#Leemos el archivo
file=opts.file
f = open(file)
data = f.read().strip()
f.close()

#Lo pasamos a un arreglo
M = [[num for num in line.strip().split()] for line in data.split('\n')]


lim=len(M)

for i in M:
    print "Inicio proceso de backup Nombre: "+i[1]+" Direccion IP: "+i[0]
        print "Por favor espere..."
        cmd='sshpass -p'+i[4]+' scp -q -P '+i[2]+' '+i[3]+'@'+i[0]+':sys_config '+i[1]+'.conf'
    ans=os.system(cmd)
    if ans == 0:
         print "Copia sacada correctamente... Nombre: "+i[1]+".conf"
    else:
          print "Hubo un error al generar la copia, puede ser problema de  password o que el host aun no conoce la llave y pide confirmacion la  primera vez"

Ejecucion del Script

$ python fortibackup.py -f ruta-archivo-matrix

Regards, 
Snifer
Leer más...

apache_access_stats.sh

d
Nombre: apache_access_stats.sh
Autor: @linuxitux
Tomado de Linuxito
#!/bin/bash

# apache_access_stats.sh
#
#     Muestra un gráfico de accesos por hora a un servidor Apache a partir de un archivo
#     de log de accesos
#

mensaje="Muestra un gráfico de accesos por hora a un servidor Apache a partir de un archivo de log de
accesos."

# Variables
ancho=50

if [ $# -lt 1 ]
then
        printf "Uso: $0 ARCHIVO\n$mensaje\n"
        exit 1
fi

# Defino un arreglo de horas desde 0 a 23
hs=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)

# Contabilizo la cantidad de accesos por cada hora
for h in $(cat $* | cut -d '[' -f2 | cut -d "]" -f1 | cut -d ' ' -f1 | cut -d ':' -f2 | sed 's/^0//')
do
        (( hs[$h]++ ))
done

# Calculo la máxima cantidad de accesos
max=0
for h2 in ${hs[@]}
do
        if [ "$h2" -gt "$max" ]
        then
                max=$h2
        fi
done

# Calculo la longitud de caracteres del máximo
longitud=${#max}

# Imprimo el gráfico
echo "HORA (ACCESOS)"
hora="0"
for h3 in ${hs[@]}
do
        # Para cada hora
        # Calculo la cantidad de numerales a imprimir
        c=$(( h3 * ancho / max ))

        # Imprimo la hora con formato "HH:MM"
        if [ $hora == "0" ]
        then
                printf " 0"
        else
                printf "%2.i" "$hora"
        fi
        printf ":00"

        # Imprimo la cantidad de accesos
        printf " (%$longitud.i) " "$h3"

        # Imprimo los numerales
        for (( i=0; i<$c; i++ ))
        do
                printf "#"
        done
        echo

        # Siguiente hora
        (( hora++ ))
done
Leer más...

apache2-vhosts.sh

d
Nombre: apache2-vhosts.sh
Autor: @Tonejito
Descripción: List Apache httpd VirtualHost entries
#!/bin/bash
 
for bin in which apache2ctl grep awk sort
do
  if [ ! -x "`which $bin`" ]
  then
    exit 1
  fi
done
 
apache2ctl -S 2>/dev/null | grep vhost | awk '{print $4}' | sort -u
Leer más...

File Watcher

d
Funcionamiento de script: El script crawlea un directorio y guarda en una "base de datos" (en este caso un diccionario serializado) la ruta de los archivos y sus respectivos hash md5. Para comprobar si un archivo a sido modificado, simplemente se compara su hash md5 con el que está en la BD y obviamente si el archivo no se encuentra en la BD es porque fue creado despues. 

Además indica los archivos de backup (.*~) que encuentra.

Autor: 11sept



    # -*- coding: utf-8 -*-
     
    #11Sep
     
    import os
    import sys
    import hashlib
    import cPickle
     
    recursividad = False
    diccionario = {}
    COLORES = {
        "archivo": "\033[91m\t[Archivo nuevo] %s\033[0m",     # Rojo
        "carpeta": "\033[94m\t[Carpeta nueva] %s\033[0m",     # Azul
        "modificado": "\033[93m\t[Modificado] %s\033[0m",     # Amarillo
        "backup": "\033[91m\t[BACKUP] %s\033[0m",             # Rojo
    }
     
    MENU = """Modo de uso:
    %s ruta [parametros]
     
    -r          Modo recursivo
    -a          Actualiza la BD
    -v          Para ver archivos y hashes
    """
     
     
    def imprimir(data, color):
        if its_linux:
            print COLORES[color] % data
        else:
            print data
     
    def es_archivo(ruta):
        if os.path.isfile(ruta):
            return True
     
    def es_directorio(ruta):
        if os.path.isdir(ruta):
            return True
     
    def guardar():
        with open("./data.sf", "wb") as archivo:
            cPickle.dump(diccionario, archivo, 2)
     
    def cargar():
        global diccionario
        try:
            with open("./data.sf", "rb") as archivo:
                diccionario = cPickle.load(archivo)
            return True
        except:
            return False
     
    def get_md5(ruta):
        md5 = hashlib.md5()
        with open(ruta, "r") as hash:
            for linea in hash.readlines():
                md5.update(linea)
        return md5.hexdigest()
     
    def recorrer(path, opt):
        if es_directorio(path):
           
            if not diccionario.has_key(path):
                diccionario[path] = {}
                imprimir(path, "carpeta")
           
            archivos = os.listdir(path)
           
            for archivo in archivos:
                ruta_completa = os.path.join(path, archivo)
                if es_archivo(ruta_completa):
                    extension = os.path.splitext(ruta_completa)[1]
                    if extension.endswith("~"):
                        imprimir(ruta_completa, "backup")
                   
                    if opt == 1:
                        diccionario[path][archivo] = get_md5(ruta_completa)
                    else:
                        md5 = get_md5(ruta_completa)
                        md5_bd = diccionario[path].get(archivo)
                        if md5_bd:    
                            if md5_bd != md5:
                                imprimir(ruta_completa, "modificado")
                        else:
                            imprimir(ruta_completa, "archivo")
     
                elif es_directorio(ruta_completa) and recursividad:
                    recorrer(ruta_completa, opt)
     
    its_linux = (os.name == "posix")
     
    argumentos = sys.argv
    if len(argumentos) > 1:
        parametros = []
        ruta = argumentos[1]
        parametros = argumentos[2:]
       
        if "-r" in parametros:
            recursividad = True
       
        if not es_directorio(ruta):
            print "Ruta no valida"
            exit()
        else:
            if "-a" in parametros:
                diccionario = {}
                recorrer(ruta, 1)
                guardar()
                exit()
            if cargar():
                recorrer(ruta, 2)
            else:
                recorrer(ruta, 1)
                guardar()
       
        if "-v" in parametros:
            for x, y in diccionario.iteritems():
                print x
                for archivo, hash in sorted(y.iteritems()):
                    print "\t", archivo, hash
           
    else:
        print MENU % os.path.split(argumentos[0])[-1]

Las opciones son:

-v: para ver la BD de los archivos y hashes md5
-a: para actualizar la BD
-r: para recorrer las carpetas en modo recursivo










Regards,
Snifer  

Fuente: Underc0de
Leer más...

rage-quit support for bash

d
Nombre: rage-quit support for bash
Autor: Namuol
Visto en: github namuol
Modificado por: SamHocevar
Validaciones y modificaciones para Debian: @Aen3id
La modificación requiere la instalación del paquete "toilet"
#!/bin/bash

KILL=`killall -9 "$2" 2>&1>/dev/null`
ERR=`echo $?`

if [[ "$2" == "" ]]
 then
  echo ; echo -e "Who the fuck do you want me to kill!?...\n"
 else
   if [ $ERR -ne 0  ]
   then 
    echo; echo -e "Da fuck is $2..?\n"
   else
       echo ; echo -e  "Fuck you $2!!!\n" ; echo " (╯°□°)╯︵$(echo "$2"|toilet -f term -F rotate)"; echo
  fi
 fi
Leer más...

Matrix(ish)

d
Nombre: Matrix(ish)
Autor: Brett Terpstra @ttscoff
Contribuciones: Lauri Ranta and Carl
Visto en: Brettterpstra
#!/bin/bash
#
# matrix: matrix-ish display for Bash terminal
# Author: Brett Terpstra 2012 
# Contributors: Lauri Ranta and Carl 
#
# A morning project. Could have been better, but I'm learning when to stop.
 
### Customization:
blue="\033[0;34m"
brightblue="\033[1;34m"
cyan="\033[0;36m"
brightcyan="\033[1;36m"
green="\033[0;32m"
brightgreen="\033[1;32m"
red="\033[0;31m"
brightred="\033[1;31m"
white="\033[1;37m"
black="\033[0;30m"
grey="\033[0;37m"
darkgrey="\033[1;30m"
# Choose the colors that will be used from the above list
# space-separated list
# e.g. `colors=($green $brightgreen $darkgrey $white)`
colors=($green $brightgreen)
### End customization
 
### Do not edit below this line
spacing=${1:-100} # the likelihood of a character being left in place
scroll=${2:-0} # 0 for static, positive integer determines scroll speed
screenlines=$(expr `tput lines` - 1 + $scroll)
screencols=$(expr `tput cols` / 2 - 1)
 
# chars=(a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ^)
# charset via Carl:
chars=(ア イ ウ エ オ カ キ ク ケ コ サ シ ス セ ソ タ チ ツ テ ト ナ ニ ヌ ネ ノ ハ ヒ フ ヘ ホ マ ミ ム メ モ ヤ ユ ヨ ラ リ ル レ ロ ワ ン)
 
count=${#chars[@]}
colorcount=${#colors[@]}
 
trap "tput sgr0; clear; exit" SIGTERM SIGINT
 
if [[ $1 =~ '-h' ]]; then
 echo "Display a Matrix(ish) screen in the terminal"
 echo "Usage:  matrix [SPACING [SCROLL]]"
 echo "Example: matrix 100 0"
 exit 0
fi
 
 
clear
tput cup 0 0
while :
 do for i in $(eval echo {1..$screenlines})
  do for i in $(eval echo {1..$screencols})
   do rand=$(($RANDOM%$spacing))
    case $rand in
     0)
      printf "${colors[$RANDOM%$colorcount]}${chars[$RANDOM%$count]} "
      ;;
     1)
      printf "  "
      ;;
     *)
      printf "\033[2C"
      ;;
    esac
   done
   printf "\n"
 
   # sleep .005
  done
  tput cup 0 0
 done
Leer más...

Script para verificar estado de los servicios.

d
Autor: @D4nnR
Descripción: El script muestra si el servicio HTTPD, MYSQL Y POSTFIX se encuentran en ejecución o si están parados.
Visto en: Por un servidor seguro :)
#!/bin/sh


#Verificar estados servicios SOLAMENTE... 


echo "///////////////////////////////////////////////////"


echo "Comprobando servicio WEB"


SERVICE='httpd'


if ps ax | grep -v grep | grep $SERVICE > /dev/null


then


echo "El servicio $SERVICE esta ejecutandose :)"


else


echo "¡¡ Cuidado !! El servicio $SERVICE esta DETENIDO x("


fi


echo "///////////////////////////////////////////////////"


echo "Comprobando servicio MYSQL"


SERVICE2='mysqld'


if ps ax | grep -v grep | grep $SERVICE2 > /dev/null


then


echo "El servicio $SERVICE2 esta ejecutandose :)"


else


echo "¡¡ Cuidado !! El servicio $SERVICE2 esta DETENIDO x("


fi


echo "///////////////////////////////////////////////////"


echo "Comprobando servicio de CORREO"


SERVICE3='postfix'


if ps ax | grep -v grep | grep $SERVICE3 > /dev/null


then


echo "El servicio $SERVICE3 esta ejecutandose :)"


else


echo "¡¡ Cuidado !! El servicio $SERVICE3 esta DETENIDO x("


fi


echo "By Daniel Romo - www.PorunServidorSeguro.com"
Leer más...

Servicios: Estado, inicio y reinicio

d
Autor: @D4nnR
Descripción: Este script es para verificar el estado de los servicios del servidor, si algún servicio está caído automaticamente se inicia y si está en ejecución automaticamente se reinicia. La utilidad le das tu :].
Visto en: Por un servidor seguro :)
#!/bin/bash



#Este script revisa los servicios httpd, mysqld y postfix si estan parados los inicia y si estan en ejecucion los reinicia.



# Lista de servicios



echo "##########################################################"



echo "##########################################################"



SERVICIOS=(mysqld)



# Funcion para inicializar/reiniciar servicios



function servicioInit (){



if ! service $1 status &>/dev/null; then



echo -n -e "\t  El servicio esta parado, !! INICIAR $1 !!..."



service $1 start



echo '---Inicio OK---'



service  mysqld status



else



echo -n -e "\t El servicio $1 esta en ejecucion, sin embargo se  va a !! REINICIAR !!"



service $1 restart



echo '---Reinicio-OK---'



service  mysqld status



fi



}






for ((i=0; i<${#SERVICIOS[*]}; i++)) do #if $estado = "start"; then if [ -z $1 ]; then echo "Verificando servicio: ${SERVICIO[$i]} ->"



servicioInit ${SERVICIOS[$i]}



done



echo "##########################################################"



echo "##########################################################"



SERVICIOS=(httpd)



# Funcion para inicializar/reiniciar servicios



function servicioInit (){



if ! service $1 status &>/dev/null; then



echo -n -e "\t  El servicio esta parado, !! INICIAR $1 !!..."



service $1 start



echo '---Inicio OK---'



service  httpd status



else



echo -n -e "\t El servicio $1 esta en ejecucion, sin embargo se  va a !! REINICIAR !!"



service $1 restart



echo '---Reinicio-OK---'



service  httpd status



fi



}






for ((i=0; i<${#SERVICIOS[*]}; i++)) do #if $estado = "start"; then if [ -z $1 ]; then echo "Verificando servicio: ${SERVICIO[$i]} ->"



servicioInit ${SERVICIOS[$i]}



done



echo "##########################################################"



echo "##########################################################"



SERVICIOS=(postfix)



# Funcion para inicializar/reiniciar servicios



function servicioInit (){



if ! service $1 status &>/dev/null; then



echo -n -e "\t  El servicio esta parado, !! INICIAR $1 !!..."



service $1 start



echo '---Inicio OK---'



service  postfix status



else



echo -n -e "\t El servicio $1 esta en ejecucion, sin embargo se  va a !! REINICIAR !!"



service $1 restart



echo '---Reinicio-OK---'



service  postfix status



fi



}






for ((i=0; i<${#SERVICIOS[*]}; i++)) do #if $estado = "start"; then if [ -z $1 ]; then echo "Verificando servicio: ${SERVICIO[$i]} ->"



servicioInit ${SERVICIOS[$i]}



done



echo "##########################################################"



echo "##########################################################"

Leer más...

Evita ser víctima de Nmap

d
Autor: @D4nnR
Visto en Por un servidor seguro :)
#!/bin/bash
echo 'C0NF1GUR4ND0 F1R3W411'
echo 'LIMPIANDO IPTABLES'
iptables -Z
iptables -F
#echo '# Denegando el ping #'
iptables -A INPUT -p icmp -j DROP
#echo ''
#iptables -t filter -A INPUT -p tcp -s 0/0 -d localhost --dport 25 -j DROP

echo '## Blocking portscan ##'
# Attempt to block portscans
# Anyone who tried to portscan us is locked out for an entire day.
iptables -A INPUT   -m recent --name portscan --rcheck --seconds 86400 -j DROP
iptables -A FORWARD -m recent --name portscan --rcheck --seconds 86400 -j DROP

# Once the day has passed, remove them from the portscan list
iptables -A INPUT   -m recent --name portscan --remove
iptables -A FORWARD -m recent --name portscan --remove
# These rules add scanners to the portscan list, and log the attempt.
iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP

iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP

echo '## Spoofed Invalid packets ##'# Reject spoofed packets
# These adresses are mostly used for LAN's, so if these would come to a WAN-only server, drop them.
iptables -A INPUT -s 10.0.0.0/8 -j DROP
iptables -A INPUT -s 169.254.0.0/16 -j DROP
iptables -A INPUT -s 172.16.0.0/12 -j DROP
iptables -A INPUT -s 127.0.0.0/8 -j DROP

#Multicast-adresses.
iptables -A INPUT -s 224.0.0.0/4 -j DROP
iptables -A INPUT -d 224.0.0.0/4 -j DROP
iptables -A INPUT -s 240.0.0.0/5 -j DROP
iptables -A INPUT -d 240.0.0.0/5 -j DROP
iptables -A INPUT -s 0.0.0.0/8 -j DROP
iptables -A INPUT -d 0.0.0.0/8 -j DROP
iptables -A INPUT -d 239.255.255.0/24 -j DROP
iptables -A INPUT -d 255.255.255.255 -j DROP

# Drop all invalid packets
iptables -A INPUT -m state --state INVALID -j DROP
iptables -A FORWARD -m state --state INVALID -j DROP
iptables -A OUTPUT -m state --state INVALID -j DROP

echo '#### Stop smurf attacks ####'
# Don't allow pings through
iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j DROP
Leer más...

nopassword.sh

d
Autor: nixcraft
Visto en: nixcraft
#!/bin/bash
# Shell script for search for no password entries and lock all accounts
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project 
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
# Set your email 
ADMINEMAIL="admin@somewhere.com"
 
### Do not change anything below ###
#LOG File
LOG="/root/nopassword.lock.log"
STATUS=0
TMPFILE="/tmp/null.mail.$$"
 
echo "-------------------------------------------------------" >>$LOG
echo "Host: $(hostname),  Run date: $(date)" >> $LOG
echo "-------------------------------------------------------" >>$LOG
 
# get all user names
USERS="$(cut -d: -f 1 /etc/passwd)"
 
# display message
echo "Searching for null password..."
for u in $USERS
do
  # find out if password is set or not (null password)
   passwd -S $u | grep -Ew "NP" >/dev/null
   if [ $? -eq 0 ]; then # if so 
     echo "$u" >> $LOG 
     passwd -l $u #lock account
     STATUS=1  #update status so that we can send an email
   fi  
done
echo "========================================================" >>$LOG 
if [ $STATUS -eq 1 ]; then
   echo "Please see $LOG file and all account with no password are locked!" >$TMPFILE
   echo "-- $(basename $0) script" >>$TMPFILE
   mail -s "Account with no password found and locked" "$ADMINEMAIL" < $TMPFILE
#   rm -f $TMPFILE
fi
Leer más...