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

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

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

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

rage-quit support for bash

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

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

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

Matrix(ish)

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

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

Ping a varios hosts.

d
Visto en The Linux Tips
#!/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
Leer más...

ansiweather

d
Nombre: ansiweather
Autor: Frederic Cambus
Más información del script en fcambus
#!/usr/bin/env bash

###############################################################################
#                                                                             #
# AnsiWeather 1.00 (c) by Frederic Cambus 2013                                #
# https://github.com/fcambus/ansiweather                                      #
#                                                                             #
# Created: 2013/08/29                                                         #
# Last Updated: 2013/10/19                                                    #
#                                                                             #
# AnsiWeather is released under the BSD 3-Clause license.                     #
# See LICENSE file for details.                                               #
#                                                                             #
###############################################################################



###[ Configuration options ]###################################################

config_file=~/.ansiweatherrc

function get_config {
        ret=""
        if [ -f $config_file ]
        then
                ret=$(grep $1 $config_file | awk -F\: '{print $2}')
        fi

        if [ "X$ret" = "X" ]
        then
                return 1
        else
                echo $ret
        fi
}

# Location : example "Moscow,RU"
if [ ! -z "$1" ]
then
        location=$1;
else
        location=$(get_config "location" || echo "Moscow,RU")
fi

# System of Units : "metric" or "imperial"
if [ ! -z "$2" ]
then
        units=$2
else
        units=$(get_config "units" || echo "metric")
fi

# Display symbols : "true" or "false" (requires an Unicode capable display)
symbols=$(get_config "symbols" || echo true)


#### [ Colors and characters ]#################################################

background=$(get_config "background" || echo "\033[44m")
text=$(get_config "text" || echo "\033[36;1m")
data=$(get_config "data" || echo "\033[33;1m")
delimiter=$(get_config "delimiter" || echo "\033[35m=>")
dashes=$(get_config "dashes" || echo "\033[34m-")



###[ Unicode Symbols for icons ]###############################################

sun=$(get_config "sun" || echo "\033[33;1m\xe2\x98\x80")
moon=$(get_config "moon" || echo "\033[36m\xe2\x98\xbd")
clouds=$(get_config "clouds" || echo "\033[37;1m\xe2\x98\x81")
rain=$(get_config "rain" || echo "\xe2\x98\x94")
fog=$(get_config "fog" || echo "\xe2\x96\x92")



###[ Fetch Weather data ]######################################################

fetch_cmd=$(get_config "fetch_cmd" || echo "curl -s")

weather=$($fetch_cmd "http://api.openweathermap.org/data/2.5/weather?q=$location\&units=$units")



###[ Process Weather data ]####################################################

city=$(echo $weather | jq -r '.name')
temperature=$(printf '%.0f' $(echo $weather | jq '.main.temp'))
humidity=$(echo $weather | jq '.main.humidity')
pressure=$(echo $weather | jq '.main.pressure')
sky=$(echo $weather | jq -r '.weather[0].main')
sunrise=$(echo $weather | jq '.sys.sunrise')
sunset=$(echo $weather | jq '.sys.sunset')
wind=$(echo $weather | jq '.wind.speed')



###[ Set the period ]##########################################################

now=$(date +%s)

if [ $now -ge $sunset ] || [ $now -le $sunrise ]
then
        period="night"
else
        period="day"
fi



###[ Set the scale ]###########################################################

case $units in
        metric)
                scale="°C"
                speed_unit="m/s"
                pressureUnit="hPa"
                pressure=$(printf '%.0f' $pressure)
                ;;
        imperial)
                scale="°F"
                speed_unit="mph"
                pressureUnit="inHg"
                pressure=$(printf '%.2f' $(echo "$pressure*0.0295" | bc))
                ;;
esac



###[ Set icons ]###############################################################

if [ $symbols = true ]
then
        case $sky in
                Clear)
                        if [ $period = "night" ]
                        then
                                icon="$moon "
                        else
                                icon="$sun  "
                        fi
                        ;;
                Clouds)
                        icon="$clouds  "
                        ;;
                Rain)
                        icon="$rain  "
                        ;;
                Fog)
                        icon="$fog  "
                        ;;
        esac
fi



###[ Display current Weather ]#################################################

echo -e "$background$text Current weather in $city $delimiter$data $temperature $scale $icon$dashes$text Humidity $delimiter$data $humidity % $dashes$text Wind $delimiter$data $wind $speed_unit $dashes$text Pressure $delimiter$data $pressure $pressureUnit \033[0m"

Leer más...

Iptables Script

d
Visto en The Lone Pole
#!/bin/bash
if [ -z $1 ]; then
        echo "Usage: $0  [reason]";
        exit;
fi

IP=$1
REASON="denied ip"

if [ $# -gt 1 ]; then
        shift;
        REASON=$@
fi

iptables -A INPUT -s ${IP}/32 -j LOG --log-prefix "${REASON} "
iptables -A INPUT -s ${IP}/32 -j DROP

Leer más...

Script Full Backup

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

Script para cambiar el mirror de Arch Linux

d
Autor: @jorgicio
Descripción:  Script que nos permite cambiar de mirror en ArchLinux



#!/bin/bash
HORA=`date +%H`
MINUTO=`date +%M`
RUTAMIRRORPACMANCHILE=/etc/pacman.d/mirrorlist.chile
RUTAMIRRORPACMANBRASIL=/etc/pacman.d/mirrorlist.brasil
MIRRORLISTPACMAN=/etc/pacman.d/mirrorlist
if [ $HORA -lt 19 ];then
    if [ $HORA -ge 10 ];then
        cat $MIRRORLISTPACMAN | grep .br
        if [ $? == 1 ];then
            cp $RUTAMIRRORPACMANBRASIL $MIRRORLISTPACMAN
            zenity --info --text="Mirror actualizado a: Brasil"
        fi
    fi
elif [ $HORA == 19 ];then
    if [ $MINUTO -ge 15 ];then
        cat $MIRRORLISTPACMAN | grep .cl
        if [ $? == 1 ];then
            cp $RUTAMIRRORPACMANCHILE $MIRRORLISTPACMAN
            zenity --info --text="Mirror actualizado a: Chile"
        fi
    fi
else
    if [ $HORA -le 23 ];then
        cat $MIRRORLISTPACMAN | grep .cl
        if [ $? == 1 ];then
            cp $RUTAMIRRORPACMANCHILE $MIRRORLISTPACMAN
            zenity --info --text="Mirror actualizado a: Chile"
        fi
    fi
fi
Leer más...

m4a2mp3.bash

d
Nombre: m4a2mp3.bash
Autor: Desconocido
Descripción: Script que permite convertir archivos m4a a mp3
#!/bin/bash

iflame=`type -p lame`
 if [ -z $iflame ]; then
  echo -e "\n\nlame necesita estar instalado\n"
  exit 1
 fi

for i in *.m4a; do
echo "Convirtiendo: ${i%.m4a}.mp3"
faad -o - "$i" | lame - "${i%.m4a}.mp3"
done
Permisos: chmod 700 m4a2mp3.bash 
Ejecución: ./m4a2mp3.bash
Leer más...

identificadorIP.bash

d
Nombre: identificadorIP.bash
Autor: Desconocido
Descripción: Script que permite identificar las IP's activas de un segmento determinado
#!/bin/bash
for IPS in `seq 1 255`; do
IP=`ping -c 1 172.16.0.$IPS | grep '100% packet loss' | wc -l` 
if [ $IP = 0 ]; then
echo "IP que responde: 172.16.0.$IPS"
else
echo "IP que no responde: 172.16.0.$IPS"
fi
done

Permisos: chmod 700 identificadorIP.bash 
Ejecución: ./identificadorIP.bash
Leer más...

wav2mp3.bash

d
Nombre: wav2mp3.bash
Autor: Desconocido
Descripción: Script que permite convertir archivos .wav a .mp3
#!/bin/bash
# name of this script: wav2mp3.sh
# wav to mp3


iflame=`type -p lame`
	if [ -z $iflame ]; then
		echo -e "\n\nlame necesita estar instalado\n"
		exit 1
	fi

for i in *.wav; do
 if [ -e "$i" ]; then
   file=`basename "$i" .wav`
   lame -h -b 192 "$i" "$file.mp3"
 fi
done
exit 0
Permisos: chmod +x wav2mp3.bash 
Ejecución: ./wav2mp3.bash
Leer más...

pentestlab_scanner.sh

d
Nombre: pentestlab_scanner.sh
Autor: netbiosX
Descripción: Script que actúa como un simple scanner de puertos TCP
Visto en Pentestlab
#!/bin/bash
#Autor: netbiosX
#Website:https://pentestlab.wordpress.com
#Defining the variables
IP=$1
firstport=$2
lastport=$3

function portscan
{
	for ((counter=$firstport; counter<=$lastport; counter++))
		do
		 	(echo > /dev/tcp/$IP/$counter) > /dev/null 2>&1 && echo "$counter -- open"
		done
}

portscan
Permisos: chmod 700 pentestlab_scanner.sh 
Ejecución: ./pentestlab_scanner.sh [ IP ] [ Primer Puerto ] [ Último Puerto ]
Leer más...

Scrip para extraer las cuentas de correo pertenecientes a un dominio

d
Descripción El presente Script se diseño para extraer información referente a las cuentas de correo resentes en Zimbra.
Autor: Desconocido



USO:

Para ejecutar el Script vamos al directorio que lo contiene y ejecutamos lo siguiente:

./cuentas.sh "parametros"

Si necesita información sobre el script
./cuentas.sh --help

Ejemplo: ./cuenta.sh example.com lista.txt example@example.com 

#!/bin/bash
if [ "$1" = "--help" ]; then
echo "./cuenta.sh   "
exit
fi
 
 
if [ "$1" = "" ]; then
echo "DEBE COLOCAR EL NOMBRE DEL DOMINIO DE LAS CUENTAS A EXPORTAR: EJ: synaptic.cl"
exit 
fi
 
if [ "$2" = "" ]; then
echo "DEBE COLOCAR EL NOMBRE DEL ARCHIVO EN EL CUAL EXPORTARA LAS CUENTAS: EJ: LISTAS.TXT"
exit
fi
 
if [ "$3" = "" ]; then
echo "DEBE COLOCAR UNA CUENTA DE CORREO ELECTRONICO PARA ENVIAR EL INFORME: EJ: SOPORTE@SYNAPTIC.CL"
exit
fi
 
 
 
DOMINIO=$1
listaDeNombres=$2
 
COMANDO1='/opt/zimbra/bin/zmprov ga '
 
echo "NOMBRE,CUENTA,ESTADO">$listaDeNombres
clear
echo "Generando Informe Espere Por Favor...."
for usuario in `/opt/zimbra/bin/zmprov -l gaa $DOMINIO`
do
 #echo -e "$usuario\n"
 #echo -e "Comando: zmprov ga $usuario |grep displayName |awk -F': ' '{print $2}'\n"
        $COMANDO1 $usuario >tmp.txt
        nombre=`cat tmp.txt | grep displayName | awk -F': ' '{print $2}'\n`
        cuenta=`cat tmp.txt | grep '# name' | awk '{print $3}'\n`
        estado=`cat tmp.txt | grep "zimbraAccountStatus:" | awk -F': ' '{print $2}'\n`
        echo "$nombre,$cuenta,$estado">>$listaDeNombres
done
echo "Enviando Correos Electronicos del Dominio $1 a $3"
mail -s "CORREOS ELECTRONICOS DOMINIO $1" $3<$listaDeNombres
echo "Proceso Terminado con Exito"
echo "eliminando archivos temporales"
rm -rf tmp.txt

Fuente
Leer más...

Script de instalación de TOR

d
Autor: Anonymous Mexico
Twitter: @MexicanH @Anonymousmexi @rofl4all @Anon_yuc
Descripcion: Script que automatiza la instalación de Tor

#!/bin/sh

colorise=1

print_welcome ()
{

echo " 
 
  @@@@@@  @@@  @@@ @@@@@@@  @@@@@@  @@@ @@@  @@@  @@@@@@ @@@@@@@  @@@@@@  @@@      @@@     
 @@!  @@@ @@!  @@@   @@!   @@!  @@@ @@! @@!@!@@@ !@@       @@!   @@!  @@@ @@!      @@!     
 @!@!@!@! @!@  !@!   @!!   @!@  !@! !!@ @!@@!!@!  !@@!!    @!!   @!@!@!@! @!!      @!!     
 !!:  !!! !!:  !!!   !!:   !!:  !!! !!: !!:  !!!     !:!   !!:   !!:  !!! !!:      !!:     
  :   : :  :.:: :     :     : :. :  :   ::    :  ::.: :     :     :   : : : ::.: : : ::.: :
  
Coded By: Anonymous Mexico
Twitter: @MexicanH @Anonymousmexi @rofl4all @Anon_yuc
"
}

get_test_url ()
{
echo "Antes de instalar tor, tienes que escribir el nombre de tu distribucion:\n"
echo " Debian unstable (sid) is "'sid'" "
echo " Debian testing is "'wheezy'" "
echo " Debian 6.0 (squeeze) is "'squeeze'""
echo " Debian 5.0 (lenny) is "'lenny'""
echo " Ubuntu 12.04 is "'precise'" "
echo " Ubuntu 11.10 is "'oneiric'""
echo " Ubuntu 11.04 is "'natty'""
echo " Ubuntu 10.10 or Trisquel 4.5 is "'maverick'""
echo " Ubuntu 10.04 or Trisquel 4.0 is "'lucid'""
echo " Ubuntu 9.10 or Trisquel 3.5 is "'karmic'""
echo " Ubuntu 8.04 is "'hardy'"\n"
  echo "distribucion : "
  read  distribucion
  echo 
echo "deb  http://deb.torproject.org/torproject.org $distribucion main" >> /etc/apt/sources.list
clear scr
echo "[*] Instalando las llaves...."
gpg --keyserver keys.gnupg.net --recv 886DDD89
gpg --export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | sudo apt-key add -
echo "Done!!"
clear scr
echo "[*] Actualizando repositorios...."
apt-get update
clear scr
echo "[*] Instalando paquetes deb"
apt-get install deb.torproject.org-keyring
echo "[*] Done!!"
clear scr
echo "[*] Instalando TOR, Privoxy, & Polipo"
apt-get install tor
echo "[*] Done!!"
apt-get install privoxy
echo "[*] Configurando privoxy"
echo "forward-socks4a / 127.0.0.1:9050 . " >> /etc/privoxy/config
apt-get install polipo
echo "[*] Configurando polipo"
cd /etc/polipo/
rm  config > /dev/null
wget --output-document=config http://www.pps.univ-paris-diderot.fr/~jch/software/polipo/config.sample 
echo "Done!!"
echo "Tor ha sido instlado satisfactoriamente."

}

if [ "$colorise" = 1 ]; then print_welcome  ; fi ;
get_test_url
Leer más...