checkMemory.sh

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

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

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

            }'))

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

    exit 0

}

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

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

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

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

#
# MAIN:
#

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

# Check command line options

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

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

iptables-rules-generator.sh

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

#@WizardIP

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

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

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

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

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

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

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

Audifonos.sh

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

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

Conversor de videos a mp3 y ogg

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

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

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

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

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

exit
Leer más...

Lastlog script for Solaris

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

# month names for common usage

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

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

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

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

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

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

evomalware.sh

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

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

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

trap "rm -rf $fileslist $tmpPATH" EXIT

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

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

Leer más...

Script para monitorizar el estado de un servidor

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

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

# clear the screen
clear

unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage

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

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

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

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


# Define Variable tecreset
tecreset=$(tput sgr0)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Leer más...

imap2gmail.sh

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

actualizaflash.sh

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

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

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

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

Amazon S3 Uploader

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

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

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

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