Mostrando entradas con la etiqueta Servicios. Mostrar todas las entradas
Mostrando entradas con la etiqueta Servicios. 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...

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

Script para comprobar si una IP genera Spam

d
Autor: Martín Gómez
Visto en Imsitega
#!/bin/bash
 
for ip in `cat /ruta/archivo-ips`
do
        url=http://www.stopforumspam.com/api?ip=$ip
        respuesta=`curl -s $url | sed -ne '/<\/appears>/ { s/<[^>]*>\(.*\)<\/appears>/\1/; p }'`
        if [ $respuesta = "yes" ];
        then
                echo $ip " Aparece"
       else
               echo $ip "  No aparece"
        fi
 
done
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...

Script en bash para hacer una copia de seguridad de un correo o una lista de correo de qmail/vpopmail

d
Autor: Rock Neurotiko
Descripción: Script en bash para hacer una copia de seguridad de un correo o una lista de correo de qmail/vpopmail.
El uso es simple, se le dan permisos de lectura y escritura de root (700) y lo ejecutas con un parámetro, éste parámetro es el nombre de la lista/email.
Por ejemplo, si es hola@dominio.com lo llamas como "./script.sh hola" y te crea un tar.gz.
El script no está mejorado y se podría hacer mejor, ya que necesitas cambiar la variable DIR y que donde ponga dominio ponga el dominio que tienes, y necesita tener los siguientes directorios:
/var/lib/vpopmail/domains/backups
/var/lib/vpopmail/domains/backups/listas
/var/lib/vpopmail/domains/backups/correos
Contacto: @Binaryrock
#####

#!/bin/bash

NOMBRE=""

#Variables de control de directorios
#Han de estar creados los directorios:
#/var/lib/vpopmail/domains/backups/
#/var/lib/vpopmail/domains/backups/listas/
#/var/lib/vpopmail/domains/backups/correos/

DIR="/var/lib/vpopmail/domains/dominio/"
DIR2="/archive/"
DIR3="/Maildir/cur/"
BACKDIR="/var/lib/vpopmail/domains/backups/"
FIN4="listas/"
FIN5="correos/"

cd $BACKDIR

NUM=1
while [ $NUM -le 2 ]; do
#Lee el nombre para hacer el backup
    echo "Escriba el nombre del correo/lista a hacer backup: "
    read NOMBRE
#Si el nombre es exit, se sale
    if [ "$NOMBRE" = "exit" ]; then 
 break
    fi
#Si el nombre es un correo, hace su backup
    if [ -d "$DIR$NOMBRE$DIR3" ]; then
 cd $FIN4
 echo "Haciendo backup de: " $NOMBRE
 tar -cvf $NOMBRE.tar $DIR$NOMBRE$DIR3
 echo "Backup de: " $NOMBRE " terminado."
 cd -
#Si el nombre es una lista, hace su backup
    elif [ -d "$DIR$NOMBRE$DIR2" ]; then
 cd $FIN5
 echo "Haciendo backup de: " $NOMBRE
 tar -cvf $NOMBRE.tar $DIR$NOMBRE$DIR2
 echo "Backup de: " $NOMBRE " terminado."
 cd -
#Si no existe el nombre
    else
 echo "No existe " $NOMBRE ". Recuerda que si quieres salir, has de escribir exit."
    fi


done

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

addsmbuser.bash

d
Nombre: addsmbuser.bash
Autor: @_tty0
Descripción Script que permite añadir un usuario a Samba
Visto en: tty0
#!/bin/bash
# Add user to Samba

USER=${1}
GROUP=repositorio

if [ -z ${1} ]; then
  printf "Use: addsmbuser [username]\n"
  exit 1
fi

if [ ! $(grep ${1} /etc/passwd) ]; then 
  /usr/sbin/useradd ${1} -n -s /sbin/nologin -g ${GROUP}
else
  printf "User exist in /etc/passwd\n"
fi

/usr/sbin/smbpasswd -a -e ${1}

exit $?
Permisos: chmod 700 addsmbuser.bash 
Ejecución: ./addsmbuser.bash [ nombre de usuario ]
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...

revoke-ssh.bash

d
Nombre: revoke-ssh
Autor: nixCraft.
Descripción: Script que permite remover una entrada del archivo ~/.known_hosts, muy útil cuando se ha reinstalado o cuando las llaves ssh han cambiado.
Visto en tty0
#!/bin/bash
# A simple shell script to clean (delete)  ~/.known_hosts file hostname entry.
# This is useful when remote server reinstalled or ssh keys are changed!
# -------------------------------------------------------------------------
# Copyright (c) 2007 nixCraft project [http://cyberciti.biz/fb/]
# 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.
# -------------------------------------------------------------------------
 
host="$1"
 
[[ $# -eq 0 ]] && { echo "Usage: $0 host.name.com"; exit 1;}
 
ips=$(host "$host" | awk -F'address' '{ print $2}' | sed -e 's/^ //g')
ssh-keygen -R "$host"

for i in $ips
do
  ssh-keygen -R "$i"
done

exit $?
Permisos de ejecución: chmod 700 revoke-ssh.bash 
Ejecución del script: ./revoke-ssh.bash nombre.dominio o ./revoke-ssh.bash IP.
Leer más...

Script Python para respaldar base de datos en Postgrtesql

d
Autor: Carlos Garcia
Descripción: Script en python que permite hacer un respaldo de una base de datos que reside en PostgreSql

Este archivo se ejecuta de la siguiente manera:

$ python respaldo.py

Para Restaurar la Base de Datos: -d Nombre Base Datos -U Usuario
pg_restore -d db -U postgres db.tar

#!/usr/bin/env python
import time
import datetime
import os


def nombre_archivo():
    '''
    Permite Crear el nombre del archivo que tendra el respaldo
    tomando como nombre la fecha dd-mm-aa y la hora hh:mm:ss
    Quedando de la siguiente manera suponiendo que fue realizado
    en la siguiente fecha (24/12/2011 10:30:00) , el resultado seria
    el siguiente: 24_12_2011_103000

    t = time.localtime()
    dia = t.tm_mday
    mes = t.tm_mon
    ano = t.tm_year

    hora = t.tm_hour
    minutos = t.tm_min
    seg = t.tm_sec

    nombre = '%s-%s-%s_%s:%s:%s' % (dia, mes, ano, hora, minutos, seg)
    '''

    t = datetime.datetime.now()
    nombre = t.strftime('%d_%m_%Y_%I%M%S')
    return nombre


def leer_config():
    '''
    Toma los valores del archivo de configuracion llamado config.cfg y los
     guarda en un diccionario {clave:valor} el cual retorna al finalizar.
    Informacion del archivo config.cfg:

    ipservidor=10.121.6.4
    nombrebasedatos=bdhcoromoto
    usuariobasedatos=admhc
    rutarespaldo=/media/respaldo
    nombrearchivo=pg_bdhcoromoto_
    '''
    diccionario = {}
    ruta = "/home/cgarcia/desarrollo/python/respaldo-potgres/config/config.cfg"
    for linea in file(ruta):
        if linea[0] != '#':
            separar = linea.split('=')
            if len(separar) > 1:
                dicc_clave = separar[0]
                dicc_valor = separar[1].rstrip()  # rstrip elimina el retor d c
                diccionario[dicc_clave] = dicc_valor
    return diccionario


def respaldo_pg():
    '''
    Toma los parametros del diccionario con el cual se arma el nombre y
    la ruta que tendra el archivo del respaldo asi como tambien arma
    el comando final a ejecutar
    '''

    diccio = leer_config()
    dic_ipservidor = diccio['ipservidor']
    dic_nombrebasedatos = diccio['nombrebasedatos']
    dic_usuariobasedatos = diccio['usuariobasedatos']
    dic_rutarespaldo = diccio['rutarespaldo']
    dic_nombrearchivo = diccio['nombrearchivo']

    archivofinal = os.path.join(dic_rutarespaldo, dic_nombrearchivo + \
     nombre_archivo() + '.tar')
    comando = 'pg_dump'

    '''
    -Parametros a pasar(Estos tambien se pudieran colocar dentro del
    archivo config.cfg),
    - pero por ahora lo dejaremos asi directo como texto
    -Ft Significa Format tar
    -b Inclute campos Blobs
    -h es el host o la ip del servidor
    -W password
    '''
    comando_a_ejecutar = '%s -Ft -b -h %s %s -U %s > %s' % \
        (comando, dic_ipservidor, dic_nombrebasedatos, dic_usuariobasedatos,\
         archivofinal)
    return comando_a_ejecutar

if __name__ == '__main__':
    print 'Espere un momento ejecutando Proceso de Respaldo...'
    respaldar = respaldo_pg()
    print respaldar
    os.system(respaldar)
    print '*** Respaldo Realizado con Exito ***'
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...

CheckSec.sh

d
Nombre: checksec.sh
Autor: Tobias Klein.
Visto en tty0
Descripción: Script diseñado para probar las características de seguridad "estándar" que están siendo utilizadas en un Sistema Operativo Linux y Pax (http://pax.grsecurity.net/)
#!/bin/bash
#
# The BSD License (http://www.opensource.org/licenses/bsd-license.php) 
# specifies the terms and conditions of use for checksec.sh:
#
# Copyright (c) 2009-2011, Tobias Klein.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions 
# are met:
# 
# * Redistributions of source code must retain the above copyright 
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright 
#   notice, this list of conditions and the following disclaimer in 
#   the documentation and/or other materials provided with the 
#   distribution.
# * Neither the name of Tobias Klein nor the name of trapkit.de may be 
#   used to endorse or promote products derived from this software 
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
# DAMAGE.
#
# Name    : checksec.sh
# Version : 1.5
# Author  : Tobias Klein
# Date    : November 2011
# Download: http://www.trapkit.de/tools/checksec.html
# Changes : http://www.trapkit.de/tools/checksec_changes.txt
#
# Description:
#
# Modern Linux distributions offer some mitigation techniques to make it 
# harder to exploit software vulnerabilities reliably. Mitigations such 
# as RELRO, NoExecute (NX), Stack Canaries, Address Space Layout 
# Randomization (ASLR) and Position Independent Executables (PIE) have 
# made reliably exploiting any vulnerabilities that do exist far more 
# challenging. The checksec.sh script is designed to test what *standard* 
# Linux OS and PaX (http://pax.grsecurity.net/) security features are being 
# used.
#
# As of version 1.3 the script also lists the status of various Linux kernel 
# protection mechanisms.
#
# Credits:
#
# Thanks to Brad Spengler (grsecurity.net) for the PaX support.
# Thanks to Jon Oberheide (jon.oberheide.org) for the kernel support.
# Thanks to Ollie Whitehouse (Research In Motion) for rpath/runpath support.
# 
# Others that contributed to checksec.sh (in no particular order):
#
# Simon Ruderich, Denis Scherbakov, Stefan Kuttler, Radoslaw Madej,
# Anthony G. Basile, Martin Vaeth and Brian Davis. 
#

# global vars
have_readelf=1
verbose=false

# SELinux prefix
# Set where the script must search for the SELinux bin files.
se_prefix='/usr/sbin'

# FORTIFY_SOURCE vars
FS_end=_chk
FS_cnt_total=0x
FS_cnt_checked=0
FS_cnt_unchecked=0
FS_chk_func_libc=0
FS_functions=0
FS_libc=0
 
# version information
version() {
  echo "checksec v1.5, Tobias Klein, www.trapkit.de, November 2011"
  echo 
}

# help
help() {
  echo "Usage: checksec [OPTION]"
  echo
  echo "Options:"
  echo
  echo "  --file "
  echo "  --dir  [-v]"
  echo "  --proc "
  echo "  --proc-all"
  echo "  --proc-libs "
  echo "  --kernel"
  echo "  --fortify-file "
  echo "  --fortify-proc "
  echo "  --version"
  echo "  --help"
  echo
  echo "For more information, see:"
  echo "  http://www.trapkit.de/tools/checksec.html"
  echo
}

# check if command exists
command_exists () {
  type $1  > /dev/null 2>&1;
}

# check if directory exists
dir_exists () {
  [ -d $1 ] || return 1
}

# check user privileges
root_privs () {
  [ $UID -eq 0 ] || return 1
}

# check if input is numeric
isNumeric () {
  echo "$@" | grep -q -v "[^0-9]" && return 0
}

# check if input is a string
isString () {
  echo "$@" | grep -q -v "[^A-Za-z]" && return 0
}

# check file(s)
filecheck() {
  # check for RELRO support
  if readelf -l $1 2>/dev/null | grep -q 'GNU_RELRO'; then
    if readelf -d $1 2>/dev/null | grep -q 'BIND_NOW'; then
      echo -n -e '\033[32mFull RELRO   \033[m   '
    else
      echo -n -e '\033[33mPartial RELRO\033[m   '
    fi
  else
    echo -n -e '\033[31mNo RELRO     \033[m   '
  fi

  # check for stack canary support
  if readelf -s $1 2>/dev/null | grep -q '__stack_chk_fail'; then
    echo -n -e '\033[32mCanary found   \033[m   '
  else
    echo -n -e '\033[31mNo canary found\033[m   '
  fi

  # check for NX support
  if readelf -W -l $1 2>/dev/null | grep 'GNU_STACK' | grep -q 'RWE'; then
    echo -n -e '\033[31mNX disabled\033[m   '
  else
    echo -n -e '\033[32mNX enabled \033[m   '
  fi 

  # check for PIE support
  if readelf -h $1 2>/dev/null | grep -q 'Type:[[:space:]]*EXEC'; then
    echo -n -e '\033[31mNo PIE       \033[m   '
  elif readelf -h $1 2>/dev/null | grep -q 'Type:[[:space:]]*DYN'; then
    if readelf -d $1 2>/dev/null | grep -q '(DEBUG)'; then
      echo -n -e '\033[32mPIE enabled  \033[m   '
    else   
      echo -n -e '\033[33mDSO          \033[m   '
    fi
  else
    echo -n -e '\033[33mNot an ELF file\033[m   '
  fi 

  # check for rpath / run path
  if readelf -d $1 2>/dev/null | grep -q 'rpath'; then
   echo -n -e '\033[31mRPATH    \033[m  '
  else
   echo -n -e '\033[32mNo RPATH \033[m  '
  fi

  if readelf -d $1 2>/dev/null | grep -q 'runpath'; then
   echo -n -e '\033[31mRUNPATH    \033[m  '
  else
   echo -n -e '\033[32mNo RUNPATH \033[m  '
  fi
}

# check process(es)
proccheck() {
  # check for RELRO support
  if readelf -l $1/exe 2>/dev/null | grep -q 'Program Headers'; then
    if readelf -l $1/exe 2>/dev/null | grep -q 'GNU_RELRO'; then
      if readelf -d $1/exe 2>/dev/null | grep -q 'BIND_NOW'; then
        echo -n -e '\033[32mFull RELRO       \033[m '
      else
        echo -n -e '\033[33mPartial RELRO    \033[m '
      fi
    else
      echo -n -e '\033[31mNo RELRO         \033[m '
    fi
  else
    echo -n -e '\033[31mPermission denied (please run as root)\033[m\n'
    exit 1
  fi

  # check for stack canary support
  if readelf -s $1/exe 2>/dev/null | grep -q 'Symbol table'; then
    if readelf -s $1/exe 2>/dev/null | grep -q '__stack_chk_fail'; then
      echo -n -e '\033[32mCanary found         \033[m  '
    else
      echo -n -e '\033[31mNo canary found      \033[m  '
    fi
  else
    if [ "$1" != "1" ] ; then
      echo -n -e '\033[33mPermission denied    \033[m  '
    else
      echo -n -e '\033[33mNo symbol table found\033[m  '
    fi
  fi

  # first check for PaX support
  if cat $1/status 2> /dev/null | grep -q 'PaX:'; then
    pageexec=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b6) )
    segmexec=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b10) )
    mprotect=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b8) )
    randmmap=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b9) )
    if [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "M" && "$randmmap" = "R" ]] ; then
      echo -n -e '\033[32mPaX enabled\033[m   '
    elif [[ "$pageexec" = "p" && "$segmexec" = "s" && "$randmmap" = "R" ]] ; then
      echo -n -e '\033[33mPaX ASLR only\033[m '
    elif [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "m" && "$randmmap" = "R" ]] ; then
      echo -n -e '\033[33mPaX mprot off \033[m'
    elif [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "M" && "$randmmap" = "r" ]] ; then
      echo -n -e '\033[33mPaX ASLR off\033[m  '
    elif [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "m" && "$randmmap" = "r" ]] ; then
      echo -n -e '\033[33mPaX NX only\033[m   '
    else
      echo -n -e '\033[31mPaX disabled\033[m  '
    fi
  # fallback check for NX support
  elif readelf -W -l $1/exe 2>/dev/null | grep 'GNU_STACK' | grep -q 'RWE'; then
    echo -n -e '\033[31mNX disabled\033[m   '
  else
    echo -n -e '\033[32mNX enabled \033[m   '
  fi 

  # check for PIE support
  if readelf -h $1/exe 2>/dev/null | grep -q 'Type:[[:space:]]*EXEC'; then
    echo -n -e '\033[31mNo PIE               \033[m   '
  elif readelf -h $1/exe 2>/dev/null | grep -q 'Type:[[:space:]]*DYN'; then
    if readelf -d $1/exe 2>/dev/null | grep -q '(DEBUG)'; then
      echo -n -e '\033[32mPIE enabled          \033[m   '
    else   
      echo -n -e '\033[33mDynamic Shared Object\033[m   '
    fi
  else
    echo -n -e '\033[33mNot an ELF file      \033[m   '
  fi
}

# check mapped libraries
libcheck() {
  libs=( $(awk '{ print $6 }' /proc/$1/maps | grep '/' | sort -u | xargs file | grep ELF | awk '{ print $1 }' | sed 's/:/ /') )
 
  printf "\n* Loaded libraries (file information, # of mapped files: ${#libs[@]}):\n\n"
  
  for element in $(seq 0 $((${#libs[@]} - 1)))
  do
    echo "  ${libs[$element]}:"
    echo -n "    "
    filecheck ${libs[$element]}
    printf "\n\n"
  done
}

# check for system-wide ASLR support
aslrcheck() {
  # PaX ASLR support
  if !(cat /proc/1/status 2> /dev/null | grep -q 'Name:') ; then
    echo -n -e ':\033[33m insufficient privileges for PaX ASLR checks\033[m\n'
    echo -n -e '  Fallback to standard Linux ASLR check'
  fi
  
  if cat /proc/1/status 2> /dev/null | grep -q 'PaX:'; then
    printf ": "
    if cat /proc/1/status 2> /dev/null | grep 'PaX:' | grep -q 'R'; then
      echo -n -e '\033[32mPaX ASLR enabled\033[m\n\n'
    else
      echo -n -e '\033[31mPaX ASLR disabled\033[m\n\n'
    fi
  else
    # standard Linux 'kernel.randomize_va_space' ASLR support
    # (see the kernel file 'Documentation/sysctl/kernel.txt' for a detailed description)
    ASLR=$(/sbin/sysctl -n kernel.randomize_va_space 2> /dev/null)
    printf " (Address Space Layout Randomization): " 
    if [ ! -z $ASLR ] ; then
      if [ $ASLR -ge 2 ]; then
        echo -n -e '\033[32mOn (Setting: 2)\033[m\n\n'
        printf "  Description - Make the addresses of mmap base, heap, stack and VDSO page randomized.\n"
        printf "  This, among other things, implies that shared libraries will be loaded to random \n"
        printf "  addresses. Also for PIE-linked binaries, the location of code start is randomized.\n\n"
      elif [ $ASLR -eq 1 ]; then 
        echo -n -e '\033[33mOn (Setting: 1)\033[m\n\n'
        printf "  Description - Make the addresses of mmap base, stack and VDSO page randomized.\n"
        printf "  This, among other things, implies that shared libraries will be loaded to \n"
        printf "  random addresses. Also for PIE-linked binaries, the location of code start\n"
        printf "  is randomized. Heap addresses are *not* randomized.\n\n"
      elif [ $ASLR -eq 0 ]; then
        echo -n -e '\033[31mOff (Setting:0)\033[m\n'
      fi
    else
      echo -n -e '\033[31mNot kernel support\033[m\n'
    fi
    printf "  See the kernel file 'Documentation/sysctl/kernel.txt' for more details.\n\n"
  fi 
}

# check cpu nx flag
nxcheck() {
  if grep -q nx /proc/cpuinfo; then
    echo -n -e '\033[32mYes\033[m\n\n'
  else
    echo -n -e '\033[31mNo\033[m\n\n'
  fi
}

# check for kernel protection mechanisms
kernelcheck() {
  printf "  Description - List the status of kernel protection mechanisms. Rather than\n"
  printf "  inspect kernel mechanisms that may aid in the prevention of exploitation of\n"
  printf "  userspace processes, this option lists the status of kernel configuration\n"
  printf "  options that harden the kernel itself against attack.\n\n"
  printf "  Kernel version: \033[33m%s\033[m - OS architecture: \033[33m%s\033[m\n" $(/bin/uname -r) $(/bin/uname -m)
  printf "  Kernel config : "
 
  if [ -f /proc/config.gz ] ; then
    kconfig="zcat /proc/config.gz"
    printf "\033[32m/proc/config.gz\033[m\n\n"
  elif [ -f /boot/config-`uname -r` ] ; then
    kconfig="cat /boot/config-`uname -r`"
    printf "\033[33m/boot/config-`uname -r`\033[m\n\n"
    printf "  Warning: The config on disk may not represent running kernel config!\n\n";
  elif [ -f "${KBUILD_OUTPUT:-/usr/src/linux}"/.config ] ; then
    kconfig="cat ${KBUILD_OUTPUT:-/usr/src/linux}/.config"
    printf "\033[33m%s\033[m\n\n" "${KBUILD_OUTPUT:-/usr/src/linux}/.config"
    printf "  Warning: The config on disk may not represent running kernel config!\n\n";
  else
    printf "\033[31mNOT FOUND\033[m\n\n"
    exit 0
  fi

  printf "  GCC stack protector support:            "
  if $kconfig | grep -qi 'CONFIG_CC_STACKPROTECTOR=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi

  printf "  Strict user copy checks:                "
  if $kconfig | grep -qi 'CONFIG_DEBUG_STRICT_USER_COPY_CHECKS=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi

  printf "  Enforce read-only kernel data:          "
  if $kconfig | grep -qi 'CONFIG_DEBUG_RODATA=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi
  printf "  Restrict /dev/mem access:               "
  if $kconfig | grep -qi 'CONFIG_STRICT_DEVMEM=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi

  printf "  Restrict /dev/kmem access:              "
  if $kconfig | grep -qi 'CONFIG_DEVKMEM=y'; then
    printf "\033[31mDisabled\033[m\n"
  else
    printf "\033[32mEnabled\033[m\n"
  fi

  printf "\n"
  printf "* grsecurity / PaX: "

  if $kconfig | grep -qi 'CONFIG_GRKERNSEC=y'; then
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_HIGH=y'; then
      printf "\033[32mHigh GRKERNSEC\033[m\n\n"
    elif $kconfig | grep -qi 'CONFIG_GRKERNSEC_MEDIUM=y'; then
      printf "\033[33mMedium GRKERNSEC\033[m\n\n"
    elif $kconfig | grep -qi 'CONFIG_GRKERNSEC_LOW=y'; then
      printf "\033[31mLow GRKERNSEC\033[m\n\n"
    else
      printf "\033[33mCustom GRKERNSEC\033[m\n\n"
    fi

    printf "  Non-executable kernel pages:            "
    if $kconfig | grep -qi 'CONFIG_PAX_KERNEXEC=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Prevent userspace pointer deref:        "
    if $kconfig | grep -qi 'CONFIG_PAX_MEMORY_UDEREF=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Prevent kobject refcount overflow:      "
    if $kconfig | grep -qi 'CONFIG_PAX_REFCOUNT=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Bounds check heap object copies:        "
    if $kconfig | grep -qi 'CONFIG_PAX_USERCOPY=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Disable writing to kmem/mem/port:       "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_KMEM=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Disable privileged I/O:                 "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_IO=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Harden module auto-loading:             "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_MODHARDEN=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Hide kernel symbols:                    "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_HIDESYM=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi
  else
    printf "\033[31mNo GRKERNSEC\033[m\n\n"
    printf "  The grsecurity / PaX patchset is available here:\n"
    printf "    http://grsecurity.net/\n"
  fi

  printf "\n"
  printf "* Kernel Heap Hardening: "

  if $kconfig | grep -qi 'CONFIG_KERNHEAP=y'; then
    if $kconfig | grep -qi 'CONFIG_KERNHEAP_FULLPOISON=y'; then
      printf "\033[32mFull KERNHEAP\033[m\n\n"
    else
      printf "\033[33mPartial KERNHEAP\033[m\n\n"
    fi
  else
    printf "\033[31mNo KERNHEAP\033[m\n\n"
    printf "  The KERNHEAP hardening patchset is available here:\n"
    printf "    https://www.subreption.com/kernheap/\n\n"
  fi

  # Check SELinux support, status and configuration. 
  printf "  SELinux support:" 

  if $kconfig | grep -qi 'CONFIG_SECURITY_SELINUX=y'; then
    if [ ! -e ${se_prefix}/sestatus ] || [ ! -e ${se_prefix}/getenforce ]; then 
      printf "\033[31m SELinux kernel support but no utils installed\033[m\n\n"
      exit 
    else
      printf "\033[32m SELinux kernel support\033[m\n" 
    fi

    if ( $kconfig 1> /dev/null ); then
      printf "  SELinux mode:  "
      se_status=$($se_prefix/getenforce)
      [ $se_status = 'Enforcing'  ] && printf "\033[32m  Enforcing\033[m\n"
      [ $se_status = 'Permissive' ] && printf "\033[33m  Permissive\033[m\n"
      [ $se_status = 'Disabled'   ] && printf "\033[31m  Disabled\033[m\n"

      printf "  SELinux policy:"
      se_policy=$($se_prefix/sestatus | grep "Policy from config file" | awk -F: {'print $2'})
      [ $se_policy = 'targeted'  ] && printf "\033[33m  Targeted \033[m\n\n"
      [ $se_policy = 'stric'     ] && printf "\033[32m  Stric\033[m\n\n"
    fi
      printf "  Warning: The config may represent the running SELinux config!\n\n"
  else
    printf "\033[31m  No Kernel SELinux support\033[m\n\n"
  fi
  

}

# --- FORTIFY_SOURCE subfunctions (start) ---

# is FORTIFY_SOURCE supported by libc?
FS_libc_check() {
  printf "* FORTIFY_SOURCE support available (libc)    : "

  if [ "${#FS_chk_func_libc[@]}" != "0" ] ; then
    printf "\033[32mYes\033[m\n"
  else
    printf "\033[31mNo\033[m\n"
    exit 1
  fi
}

# was the binary compiled with FORTIFY_SOURCE?
FS_binary_check() {
  printf "* Binary compiled with FORTIFY_SOURCE support: "

  for FS_elem_functions in $(seq 0 $((${#FS_functions[@]} - 1)))
  do
    if [[ ${FS_functions[$FS_elem_functions]} =~ _chk ]] ; then
      printf "\033[32mYes\033[m\n"
      return
    fi
  done
  printf "\033[31mNo\033[m\n"
  exit 1
}

FS_comparison() {
  echo
  printf " ------ EXECUTABLE-FILE ------- . -------- LIBC --------\n"
  printf " FORTIFY-able library functions | Checked function names\n"
  printf " -------------------------------------------------------\n"

  for FS_elem_libc in $(seq 0 $((${#FS_chk_func_libc[@]} - 1)))
  do
    for FS_elem_functions in $(seq 0 $((${#FS_functions[@]} - 1)))
    do
      FS_tmp_func=${FS_functions[$FS_elem_functions]}
      FS_tmp_libc=${FS_chk_func_libc[$FS_elem_libc]}

      if [[ $FS_tmp_func =~ ^$FS_tmp_libc$ ]] ; then
        printf " \033[31m%-30s\033[m | __%s%s\n" $FS_tmp_func $FS_tmp_libc $FS_end
        let FS_cnt_total++
        let FS_cnt_unchecked++
      elif [[ $FS_tmp_func =~ ^$FS_tmp_libc(_chk) ]] ; then
        printf " \033[32m%-30s\033[m | __%s%s\n" $FS_tmp_func $FS_tmp_libc $FS_end
        let FS_cnt_total++
        let FS_cnt_checked++
      fi

    done
  done
}

FS_summary() {
  echo
  printf "SUMMARY:\n\n"
  printf "* Number of checked functions in libc                : ${#FS_chk_func_libc[@]}\n"
  printf "* Total number of library functions in the executable: ${#FS_functions[@]}\n"
  printf "* Number of FORTIFY-able functions in the executable : %s\n" $FS_cnt_total
  printf "* Number of checked functions in the executable      : \033[32m%s\033[m\n" $FS_cnt_checked
  printf "* Number of unchecked functions in the executable    : \033[31m%s\033[m\n" $FS_cnt_unchecked
  echo
}

# --- FORTIFY_SOURCE subfunctions (end) ---

if !(command_exists readelf) ; then
  printf "\033[31mWarning: 'readelf' not found! It's required for most checks.\033[m\n\n"
  have_readelf=0
fi


# parse command-line arguments
case "$1" in

 --version)
  version
  exit 0
  ;;

 --help)
  help
  exit 0
  ;;

 --dir)
  if [ "$3" = "-v" ] ; then
    verbose=true
  fi
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid directory.\033[m\n\n"
    exit 1
  fi
  # remove trailing slashes
  tempdir=`echo $2 | sed -e "s/\/*$//"`
  if [ ! -d $tempdir ] ; then
    printf "\033[31mError: The directory '$tempdir' does not exist.\033[m\n\n"
    exit 1
  fi
  cd $tempdir
  printf "RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE\n"
  for N in [A-Za-z]*; do
    if [ "$N" != "[A-Za-z]*" ]; then
      # read permissions?
      if [ ! -r $N ]; then
        printf "\033[31mError: No read permissions for '$tempdir/$N' (run as root).\033[m\n"
      else
        # ELF executable?
        out=`file $N`
        if [[ ! $out =~ ELF ]] ; then
           if [ "$verbose" = "true" ] ; then
             printf "\033[34m*** Not an ELF file: $tempdir/"
             file $N
             printf "\033[m"
           fi
        else 
          filecheck $N
          if [ `find $tempdir/$N \( -perm -004000 -o -perm -002000 \) -type f -print` ]; then
            printf "\033[37;41m%s%s\033[m" $2 $N
          else
            printf "%s%s" $tempdir/ $N
          fi
          echo
        fi
      fi
    fi
  done
  exit 0
  ;;

 --file)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid file.\033[m\n\n"
   exit 1
  fi
  # does the file exist?
  if [ ! -e $2 ] ; then
    printf "\033[31mError: The file '$2' does not exist.\033[m\n\n"
    exit 1
  fi
  # read permissions?
  if [ ! -r $2 ] ; then
    printf "\033[31mError: No read permissions for '$2' (run as root).\033[m\n\n"
    exit 1
  fi
  # ELF executable?
  out=`file $2`
  if [[ ! $out =~ ELF ]] ; then
    printf "\033[31mError: Not an ELF file: "
    file $2
    printf "\033[m\n"
    exit 1
  fi
  printf "RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE\n"
  filecheck $2
  if [ `find $2 \( -perm -004000 -o -perm -002000 \) -type f -print` ] ; then
    printf "\033[37;41m%s%s\033[m" $2 $N
  else
    printf "%s" $2
  fi
  echo
  exit 0
  ;;

 --proc-all)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  cd /proc
  printf "* System-wide ASLR"
  aslrcheck
  printf "* Does the CPU support NX: "
  nxcheck 
  printf "         COMMAND    PID RELRO             STACK CANARY           NX/PaX        PIE\n"
  for N in [1-9]*; do
    if [ $N != $$ ] && readlink -q $N/exe > /dev/null; then
      printf "%16s" `head -1 $N/status | cut -b 7-`
      printf "%7d " $N
      proccheck $N
      echo
    fi
  done
  if [ ! -e /usr/bin/id ] ; then
    printf "\n\033[33mNote: If you are running 'checksec.sh' as an unprivileged user, you\n"
    printf "      will not see all processes. Please run the script as root.\033[m\n\n"
  else 
    if !(root_privs) ; then
      printf "\n\033[33mNote: You are running 'checksec.sh' as an unprivileged user.\n" 
      printf "      Too see all processes, please run the script as root.\033[m\n\n"
    fi
  fi
  exit 0
  ;;

 --proc)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid process name.\033[m\n\n"
    exit 1
  fi
  cd /proc
  printf "* System-wide ASLR"
  aslrcheck
  printf "* Does the CPU support NX: "
  nxcheck
  printf "         COMMAND    PID RELRO             STACK CANARY           NX/PaX        PIE\n"
  for N in `ps -Ao pid,comm | grep $2 | cut -b1-6`; do
    if [ -d $N ] ; then
      printf "%16s" `head -1 $N/status | cut -b 7-`
      printf "%7d " $N
      # read permissions?
      if [ ! -r $N/exe ] ; then
        if !(root_privs) ; then
          printf "\033[31mNo read permissions for '/proc/$N/exe' (run as root).\033[m\n\n"
          exit 1
        fi
        if [ ! `readlink $N/exe` ] ; then
          printf "\033[31mPermission denied. Requested process ID belongs to a kernel thread.\033[m\n\n"
          exit 1
        fi
        exit 1
      fi
      proccheck $N
      echo
    fi
  done
  exit 0
  ;;

 --proc-libs)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
    exit 1
  fi
  if !(isNumeric "$2") ; then
     printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
     exit 1
  fi
  cd /proc
  printf "* System-wide ASLR"
  aslrcheck
  printf "* Does the CPU support NX: "
  nxcheck
  printf "* Process information:\n\n"
  printf "         COMMAND    PID RELRO             STACK CANARY           NX/PaX        PIE\n"
  N=$2
  if [ -d $N ] ; then
    printf "%16s" `head -1 $N/status | cut -b 7-`
    printf "%7d " $N
    # read permissions?
    if [ ! -r $N/exe ] ; then
      if !(root_privs) ; then
        printf "\033[31mNo read permissions for '/proc/$N/exe' (run as root).\033[m\n\n"
        exit 1
      fi
      if [ ! `readlink $N/exe` ] ; then
        printf "\033[31mPermission denied. Requested process ID belongs to a kernel thread.\033[m\n\n"
        exit 1
      fi
      exit 1
    fi
    proccheck $N
    echo
    libcheck $N
  fi
  exit 0
  ;;

 --kernel)
  cd /proc
  printf "* Kernel protection information:\n\n"
  kernelcheck
  exit 0
  ;;

 --fortify-file)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid file.\033[m\n\n"
   exit 1
  fi
  # does the file exist?
  if [ ! -e $2 ] ; then
    printf "\033[31mError: The file '$2' does not exist.\033[m\n\n"
    exit 1
  fi
  # read permissions?
  if [ ! -r $2 ] ; then
    printf "\033[31mError: No read permissions for '$2' (run as root).\033[m\n\n"
    exit 1
  fi
  # ELF executable?
  out=`file $2`
  if [[ ! $out =~ ELF ]] ; then
    printf "\033[31mError: Not an ELF file: "
    file $2
    printf "\033[m\n"
    exit 1
  fi
  if [ -e /lib/libc.so.6 ] ; then
    FS_libc=/lib/libc.so.6
  elif [ -e /lib64/libc.so.6 ] ; then
    FS_libc=/lib64/libc.so.6
  elif [ -e /lib/i386-linux-gnu/libc.so.6 ] ; then
    FS_libc=/lib/i386-linux-gnu/libc.so.6
  elif [ -e /lib/x86_64-linux-gnu/libc.so.6 ] ; then
    FS_libc=/lib/x86_64-linux-gnu/libc.so.6
  else
    printf "\033[31mError: libc not found.\033[m\n\n"
    exit 1
  fi

  FS_chk_func_libc=( $(readelf -s $FS_libc | grep _chk@@ | awk '{ print $8 }' | cut -c 3- | sed -e 's/_chk@.*//') )
  FS_functions=( $(readelf -s $2 | awk '{ print $8 }' | sed 's/_*//' | sed -e 's/@.*//') )

  FS_libc_check
  FS_binary_check
  FS_comparison
  FS_summary

  exit 0
  ;;

 --fortify-proc)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
    exit 1
  fi
  if !(isNumeric "$2") ; then
     printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
     exit 1
  fi
  cd /proc
  N=$2
  if [ -d $N ] ; then
    # read permissions?
    if [ ! -r $N/exe ] ; then
      if !(root_privs) ; then
        printf "\033[31mNo read permissions for '/proc/$N/exe' (run as root).\033[m\n\n"
        exit 1
      fi
      if [ ! `readlink $N/exe` ] ; then
        printf "\033[31mPermission denied. Requested process ID belongs to a kernel thread.\033[m\n\n"
        exit 1
      fi
      exit 1
    fi
    if [ -e /lib/libc.so.6 ] ; then
      FS_libc=/lib/libc.so.6
    elif [ -e /lib64/libc.so.6 ] ; then
      FS_libc=/lib64/libc.so.6
    elif [ -e /lib/i386-linux-gnu/libc.so.6 ] ; then
      FS_libc=/lib/i386-linux-gnu/libc.so.6
    elif [ -e /lib/x86_64-linux-gnu/libc.so.6 ] ; then
      FS_libc=/lib/x86_64-linux-gnu/libc.so.6
    else
      printf "\033[31mError: libc not found.\033[m\n\n"
      exit 1
    fi
    printf "* Process name (PID)                         : %s (%d)\n" `head -1 $N/status | cut -b 7-` $N
    FS_chk_func_libc=( $(readelf -s $FS_libc | grep _chk@@ | awk '{ print $8 }' | cut -c 3- | sed -e 's/_chk@.*//') )
    FS_functions=( $(readelf -s $2/exe | awk '{ print $8 }' | sed 's/_*//' | sed -e 's/@.*//') )

    FS_libc_check
    FS_binary_check
    FS_comparison
    FS_summary
  fi
  exit 0
  ;;

 *)
  if [ "$#" != "0" ] ; then
    printf "\033[31mError: Unknown option '$1'.\033[m\n\n"
  fi
  help
  exit 1
  ;;
esac
Establecemos permisos de ejecución:
chmod +x checksec.sh
Ejecutamos el script de acuerdo a los parámetros que tiene (ver función "help").
Leer más...