tag:blogger.com,1999:blog-58796082578846014122024-03-21T07:22:40.857-07:00Geek ScriptingUnknownnoreply@blogger.comBlogger184125tag:blogger.com,1999:blog-5879608257884601412.post-16368848716417185182016-10-20T22:02:00.000-07:002016-10-20T22:02:50.923-07:00checkMemory.shNombre: checkMemory.sh </br>
Autor: Cristian Hernandez </br>
Descripcion: Monitorea el uso total de la memoria. </br>
<pre class="brush:bash">
#!/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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-76765745963984956602016-10-20T21:53:00.000-07:002016-10-20T21:53:39.308-07:00iptables-rules-generator.shNombre: iptables-rule-generator.sh </br>
Autor: Ricardo del Castillo @WizardIP </br>
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. </br>
<pre class="brush:bash">
#!/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
</pre>
Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-61791847661754225162015-08-25T20:29:00.000-07:002015-08-25T20:29:11.132-07:00Audifonos.shAutor: rain </br>
Descripción: Script para quitar el volumen cuando se desconectan los audífonos </br>
Más información del script en: <a href="http://blog.desdelinux.net/script-quitar-volumen-desconectan-audifonos/">Desde Linux</a></br>
NOTA: El script hace uso de alsa-utils por lo que debe instalarse </br>
<pre class="brush:bash">
#!/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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-32422750063296043812015-08-01T18:19:00.001-07:002015-08-01T18:19:30.750-07:00Conversor de videos a mp3 y ogg<span style="background-color: white; color: #222222; font-family: Courier New, Courier, monospace;"><b>Autor:</b> Cristian Sacristán.</span><br />
<div style="background-color: white; color: #222222;">
<span style="font-family: Courier New, Courier, monospace;"><b>Descripción: </b> 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.</span></div>
<div style="background-color: white; color: #222222; font-size: 12.8000001907349px;">
<br /></div>
<pre class="brush:bash">#!/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
</pre>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-51436176005459091702015-07-07T14:24:00.000-07:002015-07-07T14:24:17.579-07:00Lastlog script for SolarisNombre: lastlog.pl <br>
Autor: ph <br>
Visto en: <a href="http://tech-411.blogspot.mx/2008/05/lastlog-script-for-solaris.html">Tech Notes</a>
<pre class="brush:perl">
#!/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;
}
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-27086475274092037162015-07-07T14:20:00.000-07:002015-07-07T14:20:04.518-07:00evomalware.shNombre: evomalware.sh <br>
autor: benpro@benpro.fr <br>
Permite detectar virus, backdoors y malware especialmente en archivos PHP. <br>
Visto en: <a href="https://github.com/evoforge/evomalware">evoforge</a><br>
<pre class="brush:bash">
#!/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<<EOT
$0 to search for known malwares.
$0 --aggressive to include suspicions scripts.
EOT
exit 1
}
if [[ "$1" == "--aggressive" ]]; then
aggressive=true
fi
if [[ -n "$1" && "$1" != "--aggressive" ]]; then
usage
fi
# Download last patterns and filenames.
mkdir -p $databasePATH
mkdir -p $tmpPATH
cd $tmpPATH
for file in evomalware.filenames evomalware.patterns evomalware.whitelist evomalware.suspect; do
$wget ${databaseURL}/${file}
$wget ${databaseURL}/${file}.md5
if $md5sum ${file}.md5; then
cp $file ${databasePATH}/
else
echo "Error with ${databaseURL}/${file}, wrong md5sum!"
exit 1
fi
done
filenames=$(cat ${databasePATH}/evomalware.filenames | tr -d '\n')
patterns=$(cat ${databasePATH}/evomalware.patterns | tr -d '\n')
whitelist=$(cat ${databasePATH}/evomalware.whitelist | tr -d '\n')
suspect=$(cat ${databasePATH}/evomalware.suspect | tr -d '\n')
# Search for .php files (less than 1M).
find $wwwpath -name evobackup -prune -o \( -type f ! -size +1M -name "*.php" \) \
| grep -E -v "$whitelist" > $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
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-65008521296757971672015-05-13T12:20:00.002-07:002015-05-13T12:20:41.099-07:00Script para monitorizar el estado de un servidorNombre: tecmint_monitor.sh <br>
Autor: Tecmint.com <br>
Visto en: <a href="http://www.tecmint.com/linux-server-health-monitoring-script/">Tecmint</a><br>
<pre class="brush:bash">
####################################################################################################
# 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))
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-68178682540340783922015-03-11T11:59:00.000-07:002015-03-11T11:59:41.287-07:00imap2gmail.shNombre: imap2gmail.sh </br>
Autor: Desconocido <br>
Visto en <a href="http://blog.otelconsulting.com/2010/01/imapsync-to-gmail-script/">Otel Consulting </a></br>
Nota: Se necesita tener instalado el programa imapsync </br>
<pre class="brush:bash">
#!/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/' \
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-35957009202722499992015-03-10T13:35:00.000-07:002015-03-10T13:35:31.866-07:00actualizaflash.shNombre: actualizaflash.sh <br>
Autor: Esteban M. Navas <br>
Visto en <a href="http://enavas.blogspot.mx/2015/02/script-para-actualizar-el-plugin-de.html">Algo de Linux</a></br>
@algodelinux <br>
<pre class="brush:bash">
#!/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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-79364834375214900692015-03-03T21:19:00.000-08:002015-03-03T21:19:37.703-08:00Amazon S3 UploaderNombre: Amazon S3 Uploader <br>
Descripción: Script que permite subir archivos a una instancia de S3 vía BASH <br>
Autor: guss77 <br> <a href="http://geek.co.il/">geek.co.il</a><br>
Más información del script en: <a href="http://geek.co.il/2014/05/26/script-day-upload-files-to-amazon-s3-using-bash">Things n' Stuff </a></br>
<pre class="brush:bash">
#!/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"
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-89233854591369033732014-12-03T05:15:00.000-08:002014-12-03T05:15:54.971-08:00Fortibackup.py - Robot para sacar copias de seguridad de dispositivos fortigateNombre: Fortibackup.py<br />
Autor: @epsilon77<br />
Tomado de <a href="http://comunidad.dragonjar.org/f174/fortibackup-py-robot-para-sacar-copias-de-seguridad-de-dispositivos-fortigate-15693/" target="_blank">DragonJar</a><br />
<br />
<pre class="brush:python"> #!/usr/bin/python
import os
import sys
import optparse
"""
FortiBackup
author: epsilon77 at gmail
Licensed under the GNU General Public License Version 2 (GNU GPL v2),
available at: http://www.gnu.org/licenses/gpl-2.0.txt
(C) 2014 Daniel Echeverry
"""
parser = optparse.OptionParser()
parser.add_option('-f', '--file', help='Ruta archivo matrix',dest='file', action='store')
(opts, args) = parser.parse_args()
if opts.file is None:
parser.print_help()
exit(-1)
#Leemos el archivo
file=opts.file
f = open(file)
data = f.read().strip()
f.close()
#Lo pasamos a un arreglo
M = [[num for num in line.strip().split()] for line in data.split('\n')]
lim=len(M)
for i in M:
print "Inicio proceso de backup Nombre: "+i[1]+" Direccion IP: "+i[0]
print "Por favor espere..."
cmd='sshpass -p'+i[4]+' scp -q -P '+i[2]+' '+i[3]+'@'+i[0]+':sys_config '+i[1]+'.conf'
ans=os.system(cmd)
if ans == 0:
print "Copia sacada correctamente... Nombre: "+i[1]+".conf"
else:
print "Hubo un error al generar la copia, puede ser problema de password o que el host aun no conoce la llave y pide confirmacion la primera vez"</pre>
<br />
Ejecucion del Script
<br />
<br />
<pre class="brush:bash">$ python fortibackup.py -f ruta-archivo-matrix</pre>
<br />
<i>Regards, </i><br />
<i>Snifer</i>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-45437674887537506842014-11-06T09:48:00.000-08:002014-11-06T09:48:02.853-08:00apache_access_stats.shNombre: apache_access_stats.sh <br>
Autor: @linuxitux <br>
Tomado de <a href="https://www.linuxito.com/gnu-linux/nivel-alto/450-contabilizar-la-cantidad-de-accesos-por-hora-a-un-servidor-web-apache?hitcount=0"> Linuxito</a> <br>
<pre class="brush:bash">
#!/bin/bash
# apache_access_stats.sh
#
# Muestra un gráfico de accesos por hora a un servidor Apache a partir de un archivo
# de log de accesos
#
mensaje="Muestra un gráfico de accesos por hora a un servidor Apache a partir de un archivo de log de
accesos."
# Variables
ancho=50
if [ $# -lt 1 ]
then
printf "Uso: $0 ARCHIVO\n$mensaje\n"
exit 1
fi
# Defino un arreglo de horas desde 0 a 23
hs=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
# Contabilizo la cantidad de accesos por cada hora
for h in $(cat $* | cut -d '[' -f2 | cut -d "]" -f1 | cut -d ' ' -f1 | cut -d ':' -f2 | sed 's/^0//')
do
(( hs[$h]++ ))
done
# Calculo la máxima cantidad de accesos
max=0
for h2 in ${hs[@]}
do
if [ "$h2" -gt "$max" ]
then
max=$h2
fi
done
# Calculo la longitud de caracteres del máximo
longitud=${#max}
# Imprimo el gráfico
echo "HORA (ACCESOS)"
hora="0"
for h3 in ${hs[@]}
do
# Para cada hora
# Calculo la cantidad de numerales a imprimir
c=$(( h3 * ancho / max ))
# Imprimo la hora con formato "HH:MM"
if [ $hora == "0" ]
then
printf " 0"
else
printf "%2.i" "$hora"
fi
printf ":00"
# Imprimo la cantidad de accesos
printf " (%$longitud.i) " "$h3"
# Imprimo los numerales
for (( i=0; i<$c; i++ ))
do
printf "#"
done
echo
# Siguiente hora
(( hora++ ))
done
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com3tag:blogger.com,1999:blog-5879608257884601412.post-78249427908792366222014-06-05T11:32:00.000-07:002014-06-05T11:32:32.038-07:00apache2-vhosts.shNombre: apache2-vhosts.sh <br>
Autor: @Tonejito <br>
Descripción: List Apache httpd VirtualHost entries <br>
<pre class="brush:bash">
#!/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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-12541141421279116122014-05-23T06:52:00.001-07:002014-05-23T06:52:48.956-07:00File Watcher<div style="text-align: justify;">
<b>Funcionamiento de script:</b> 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. </div>
<br />Además indica los archivos de backup (.*~) que encuentra.<br />
<br />
<b>Autor: </b>11sept<br />
<br />
<br />
<br />
<pre class="brush:python"> # -*- 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]</pre>
<br />
Las opciones son:<br />
<br />-v: para ver la BD de los archivos y hashes md5<br />-a: para actualizar la BD<br />-r: para recorrer las carpetas en modo recursivo<br />
<br />
<br />
<br />
<div align="center">
<img alt="" class="bbc_img" src="http://i.imgur.com/qqyiERt.png" /><br /><br /><img alt="" class="bbc_img" src="http://i.imgur.com/PwOnx9W.png" /><br /><br /><img alt="" class="bbc_img" src="http://i.imgur.com/z8CsEo1.png" /><br /><br /><img alt="" class="bbc_img resized" height="207" src="http://i.imgur.com/Oo1nzBl.png" style="cursor: pointer;" width="600" /></div>
<br />
<strong>Regards,</strong><br />
<strong>Snifer </strong>
<br />
<div class="smalltext modified" id="modified_74693">
</div>
<br />
<i><b>Fuente:</b></i> Underc0de
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-5879608257884601412.post-32392692592085138892014-05-08T11:36:00.001-07:002014-05-08T11:36:33.725-07:00rage-quit support for bash Nombre: rage-quit support for bash <br>
Autor: Namuol <br>
Visto en: <a href="https://gist.github.com/namuol/9122237"> github namuol </a> <br>
Modificado por: SamHocevar <br>
Validaciones y modificaciones para Debian: @Aen3id <br>
La modificación requiere la instalación del paquete "toilet"
<pre class="brush:bash">
#!/bin/bash
KILL=`killall -9 "$2" 2>&1>/dev/null`
ERR=`echo $?`
if [[ "$2" == "" ]]
then
echo ; echo -e "Who the fuck do you want me to kill!?...\n"
else
if [ $ERR -ne 0 ]
then
echo; echo -e "Da fuck is $2..?\n"
else
echo ; echo -e "Fuck you $2!!!\n" ; echo " (╯°□°)╯︵$(echo "$2"|toilet -f term -F rotate)"; echo
fi
fi
</pre>
<div class="separator" style="clear: both; text-align: center;"><a href="https://camo.githubusercontent.com/e504d6e36f0244ba5aa67cd98b8f82d19bba9a2b/687474703a2f2f692e696d6775722e636f6d2f30775878584b582e706e67" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://camo.githubusercontent.com/e504d6e36f0244ba5aa67cd98b8f82d19bba9a2b/687474703a2f2f692e696d6775722e636f6d2f30775878584b582e706e67" /></a></div>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-16418100315148480142014-05-08T09:00:00.000-07:002014-05-08T09:00:00.360-07:00Matrix(ish)Nombre: Matrix(ish) <br>
Autor: Brett Terpstra @ttscoff <br>
Contribuciones: Lauri Ranta and Carl <br>
Visto en: <a href="brettterpstra.com"> Brettterpstra </a>
<pre class="brush:bash">
#!/bin/bash
#
# matrix: matrix-ish display for Bash terminal
# Author: Brett Terpstra 2012 <http://brettterpstra.com>
# Contributors: Lauri Ranta and Carl <http://blog.carlsensei.com/>
#
# A morning project. Could have been better, but I'm learning when to stop.
### Customization:
blue="\033[0;34m"
brightblue="\033[1;34m"
cyan="\033[0;36m"
brightcyan="\033[1;36m"
green="\033[0;32m"
brightgreen="\033[1;32m"
red="\033[0;31m"
brightred="\033[1;31m"
white="\033[1;37m"
black="\033[0;30m"
grey="\033[0;37m"
darkgrey="\033[1;30m"
# Choose the colors that will be used from the above list
# space-separated list
# e.g. `colors=($green $brightgreen $darkgrey $white)`
colors=($green $brightgreen)
### End customization
### Do not edit below this line
spacing=${1:-100} # the likelihood of a character being left in place
scroll=${2:-0} # 0 for static, positive integer determines scroll speed
screenlines=$(expr `tput lines` - 1 + $scroll)
screencols=$(expr `tput cols` / 2 - 1)
# chars=(a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ^)
# charset via Carl:
chars=(ア イ ウ エ オ カ キ ク ケ コ サ シ ス セ ソ タ チ ツ テ ト ナ ニ ヌ ネ ノ ハ ヒ フ ヘ ホ マ ミ ム メ モ ヤ ユ ヨ ラ リ ル レ ロ ワ ン)
count=${#chars[@]}
colorcount=${#colors[@]}
trap "tput sgr0; clear; exit" SIGTERM SIGINT
if [[ $1 =~ '-h' ]]; then
echo "Display a Matrix(ish) screen in the terminal"
echo "Usage: matrix [SPACING [SCROLL]]"
echo "Example: matrix 100 0"
exit 0
fi
clear
tput cup 0 0
while :
do for i in $(eval echo {1..$screenlines})
do for i in $(eval echo {1..$screencols})
do rand=$(($RANDOM%$spacing))
case $rand in
0)
printf "${colors[$RANDOM%$colorcount]}${chars[$RANDOM%$count]} "
;;
1)
printf " "
;;
*)
printf "\033[2C"
;;
esac
done
printf "\n"
# sleep .005
done
tput cup 0 0
done
</pre>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-5879608257884601412.post-21131383770251296102014-05-05T09:00:00.000-07:002014-05-05T09:00:01.926-07:00Script para verificar estado de los servicios.Autor: @D4nnR<br>
Descripción: El script muestra si el servicio HTTPD, MYSQL Y POSTFIX se encuentran en ejecución o si están parados. <br>
Visto en: <a href="http://porunservidorseguro.com/">Por un servidor seguro :)</a><br>
<pre class="brush:bash">
#!/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"
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-49772627419658771222014-05-04T09:00:00.000-07:002014-05-04T09:00:01.432-07:00Servicios: Estado, inicio y reinicioAutor: @D4nnR <br>
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 :]. <br>
Visto en: <a href="http://porunservidorseguro.com/"> Por un servidor seguro :) </a>
<pre class="brush:bash">
#!/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 "##########################################################"
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-55173659862382095462014-05-03T09:00:00.000-07:002014-05-03T09:00:02.577-07:00Evita ser víctima de Nmap Autor: @D4nnR <br>
Visto en <a href="http://porunservidorseguro.com/">Por un servidor seguro :)</a>
<pre class="brush:bash">
#!/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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-69176664611003930992014-05-02T09:00:00.000-07:002014-05-02T09:00:06.139-07:00nopassword.shAutor: nixcraft<br>
Visto en: <a href="http://bash.cyberciti.biz/security/script-to-lock-all-passwordless-accounts/"> nixcraft</a><br>
<pre class="brush:bash">
#!/bin/bash
# Shell script for search for no password entries and lock all accounts
# -------------------------------------------------------------------------
# Copyright (c) 2005 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.
# -------------------------------------------------------------------------
# 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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-42791079532092492152014-05-01T09:00:00.000-07:002014-05-01T09:00:03.270-07:00Monitoreo de Espacio en DiscoMuy útil si no se tiene instalado el plugin en Nagios.<br>
Autor: nixcraft<br>
Visto en: <a href="http://bash.cyberciti.biz/monitoring/shell-script-monitor-unix-linux-diskspace/">nixcraft</a>
<pre class="brush:bash">
#!/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 <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.
# ----------------------------------------------------------------------
# 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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-31151447687347020692014-04-30T20:38:00.001-07:002014-04-30T20:38:57.241-07:00chksysload.bashMuy útil cuando no se tiene instalado Cacti.<br>
Nombre: chksysload.bash<br>
Autor: nixcraft<br>
Visto en <a href="http://bash.cyberciti.biz/monitoring/monitor-unix-linux-system-load/">nixcraft</a>
<br>
<pre class="brush:bash">
#!/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
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-55695274207540775892014-01-01T16:13:00.000-08:002014-01-01T16:13:04.213-08:00Bash Script for ADSL ConnectionVisto en <a href="http://zonadebit.blogspot.com/2011/11/bash-script-for-adsl-connection.html" target="_blank">Zona de Bit</a> acceder alli para mas información ;)<br />
<br />
<br />
<pre class="brush:bash">#!/bin/bash
# Nombre : Automatización de Conexión
# Autor : @_4L3
# Fecha : 11-Nov-2011
clear
echo -e " \033[01;31m -== Automatización de Conexión ADSL ==- \n \033[00m ";
sleep 2
echo -e " \033[01;37m[+] Se procederá con poff ... \n \033[00m ";
sleep 2
sudo poff
sudo pon dls-provider
sleep 2
echo -e " \033[01;37m \n [+] Se encendió la conexión adsl ... \n \033[00m ";
sleep 2
sudo pppoeconf
echo -e " \033[01;37m[+] Se Conecto con éxito con el ISP ...\n \033[00m ";
sleep 2
echo -e " \033[01;37m \n [+] Log de registro sobre la conexión : \n \033[00m ";
sleep 2
sudo plog
sleep 5
exit</pre>
<pre class="brush:html">chmod +x '/home/usuario/scripts/script.sh'</pre>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-51119433948881147002013-10-31T10:00:00.000-07:002013-10-31T10:00:06.642-07:00Ping a varios hosts.Visto en <a href="http://www.thelinuxtips.com/2012/06/shell-script-to-ping-multiple-hosts/">The Linux Tips</a>
<pre class="brush:bash">
#!/bin/bash
for i in 192.168.0.{1..10}
do
ping -c 1 -t 1 "$i" >/dev/null 2>&1 &&
echo "Ping Status of $i : Success" ||
echo "Ping Status of $i : Failed"
done
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0tag:blogger.com,1999:blog-5879608257884601412.post-59925341682440166202013-10-30T10:00:00.000-07:002013-10-30T10:00:01.103-07:00Controlar la cantidad de peticiones de una IP hacia el puerto 80Visto en <a href="http://soyadmin.com/2013/08/como-controlar-la-cantidad-de-peticiones-de-una-ip-hacia-el-puerto-80-httpd/"> soyadmin</a>
<pre class="brush:bash">
#!/bin/sh
# Comando que realiza el reastreo
nroconn=`netstat -nap |grep “:80″ | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n | awk ‘{print $1}’ | tail -1`
# Comando que nos devolverá la ip
ip=`netstat -nap |grep “:80″ | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n | awk ‘{print $2}’ | tail -1`
# Limite a superar para informar, esto se puede variar según las necesidades de cada server
limite=100
if [ $nroconn -gt $limite ]; then
mensaje=”Atencion! la IP $ip tiene $nroconn conexiones activas”
# Realizamos el whois sobre la IP
infor=`whois $ip | grep country`
whois=`whois $ip`
# Generamos el correo
mailto=”"
cc_to=”"
bcc_to=”"
while read direccion mode
do
if [ -z "$direccion" -o "${direccion:0:1}" = "#" ] ; then continue; fi
if [ "x$mode" = "xcc" -o "x$mode" = "xCC" ] ; then
cc_to=${cc_to:+${cc_to},}$direccion
else
if [ "x$mode" = "xbcc" -o "x$mode" = "xBCC" ] ; then
bcc_to=${bcc_to:+${bcc_to},}$direccion
else
mailto=${mailto:+${mailto},}$direccion
fi
fi
# Llamamos al archivo donde guardamos las direcciones de correo
done <~/emails
mailto=${mailto:-operator}
cc_to=${cc_to:+"-c $cc_to"}
bcc_to=${bcc_to:+"-b $bcc_to"}
mail ${cc_to} ${bcc_to} -s "Alerta OJO Muchas conexiones SERVER: (nombre de servidor)" ${mailto} >&2 <<-EOM
$mensaje
Dicha IP es de: $infor
WHOIS de $ip
$whois
EOM
fi
</pre>Anonymoushttp://www.blogger.com/profile/10484756070648653647noreply@blogger.com0