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

Script Python para generar ficheros LDIF de usuarios

d
Nombre: usuariosGenerarLDIF.py
Autor: Juan Luis García
Descripción: Proceso automatizado de creación de un fichero LDIF que podría servir para dar de alta masivamente a un grupo de usuarios cuyos datos estuvieran almacenados en un fichero csv.
Visto en LDAP Config
#! /usr/bin/env python

# Generar fichero LDIF de usuarios
# CC 2011: Juan Luis Garcia para www.ldapconfig.net 
# juanluisga@ldapconfig.net

# MODULOS
import csv,random,base64,hashlib,ldap,unicodedata,argparse

# FUNCIONES
def filtrarCaracteresEspeciales(cadena):
    return ''.join((c for c in unicodedata.normalize('NFD', unicode(cadena,'UTF8')) if unicodedata.category(c) != 'Mn'))
 
def generarPassword(identificador):
    letrasMin = "abcdefghijklmnopqrstuvwxyz"
    letrasMay = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    numeros = "1234567890"
    especiales="!@#$%&=;."
    secuencia = letrasMin + letrasMay + numeros + especiales
    cadena = ""
    for i in range(8):
       cadena = cadena + random.choice(secuencia)
    k = hashlib.md5(cadena)
    encriptada = k.digest()
    encriptada = "{MD5}" + base64.standard_b64encode(encriptada)
    return cadena,encriptada
    
def conflictoLDAP(host,base,identificador):
    directorio = ldap.open(host)
    directorio.set_option(ldap.OPT_PROTOCOL_VERSION,ldap.VERSION3)
    result_id = directorio.search(base,ldap.SCOPE_SUBTREE,"uid="+identificador)
    result_type, result_data = directorio.result(result_id,0)
    if result_type == ldap.RES_SEARCH_ENTRY:
        return True
    else:
        return False
    
        
# DEFINICION DE PARAMETROS
parser = argparse.ArgumentParser(description="Generar fichero LDIF de usuarios")

parser.add_argument("-f","--ficheroEntrada",action="store",dest="ficheroEntrada",type=str,default="nuevos.csv",help="(Por defecto: nuevos.csv) Fichero en formato csv con los datos de los usuarios. Usar punto y coma ';' como separador y sin delimitacion de campos. Formato: Nombre;Apellidos;uid;departamento ")
parser.add_argument("-s","--servidorLDAP", action="store", dest="servidorLDAP",type=str, default="localhost",help="(Por defecto: localhost) Servidor LDAP sobre el que se cargaran el fichero LDIF generado.")
parser.add_argument("-b","--baseDN", action="store", dest="baseDN",type=str,default="dc=ldapconfig,dc=net",help="(Por defecto: dc=ldapconfig,dc=net) Sufijo del directorio LDAP. ")
parser.add_argument("-u","--uidNumberInicial", action="store", dest="uidNumberInicial", type=int,default=101,help="(Por defecto: 101) Primer uidNumber disponible a partir del cual se numeran las nuevas entradas.")

parametros = parser.parse_args()

ficheroEntrada = parametros.ficheroEntrada
servidorLDAP = parametros.servidorLDAP
baseDN = parametros.baseDN
uidNumberInicial = parametros.uidNumberInicial

rutaFicheros = "./"

ficheroLDIF = rutaFicheros + "usuarios.ldif"
ficheroUsuarios = rutaFicheros + "usuarios.csv"
ficheroConflictos = rutaFicheros + "usuarios.log"

fEntrada = open(ficheroEntrada,"rb")
fLDIF = open(ficheroLDIF,"wb")
fUsuarios = open(ficheroUsuarios,"wb")
fConflictos = open(ficheroConflictos,"wb")

rEntrada = csv.reader(fEntrada,delimiter=";")
wUsuarios = csv.writer(fUsuarios,delimiter=";")
wConflictos = csv.writer(fConflictos,delimiter=";")

uidNumber = uidNumberInicial - 1

wUsuarios.writerow(["APELLIDOS","NOMBRE","UID","PASSWORD"])
wConflictos.writerow(["UID","MOTIVO"])


for index,row in enumerate(rEntrada):
    nombre = row[0]
    apellidos = row[1]
    uid = row[2]
    departamento = row[3]
        
    if (conflictoLDAP(servidorLDAP,baseDN,uid)):
        wConflictos.writerow([uid,"Ya existe la cuenta"])
    else:
        password = generarPassword(uid)
        uidNumber = uidNumber + 1
        
        # ESCRIBE EN EL FICHERO DE USUARIOS
        wUsuarios.writerow([apellidos,nombre,uid,password[0]])
                
        # ESCRIBE EN FICHERO LDIF
        fLDIF.write("dn: uid=" + uid + ",ou=usuarios,ou=" + departamento + "," + baseDN + "\n")
        fLDIF.write("objectClass: inetOrgPerson\n")  
        fLDIF.write("objectClass: posixAccount\n")        
        fLDIF.write("cn: " + nombre + "\n") 
        fLDIF.write("sn: " + apellidos + "\n")
        fLDIF.write("displayName: "+ nombre + " " + apellidos + "\n")
        fLDIF.write("uid: " + uid + "\n")
        fLDIF.write("homeDirectory: /home/" + uid + "\n")        
        fLDIF.write("uidNumber: " + str(uidNumber) + "\n")
        fLDIF.write("gidNumber:1001\n")
        fLDIF.write("userPassword: " + password[1] + "\n")
        fLDIF.write("\n");
        
fEntrada.close()
fLDIF.close()
fUsuarios.close()
fConflictos.close()   
Más información del script en el sitio del autor: LDAP Config
Leer más...

nslookup.sh

d
Nombre: nslookup.sh
Autor: Omar A. Orozco @csimxnet @oorozcoo
Descripción: Script que permite usar nslookup de 10 maneras diferentes automatizando su uso
#!/bin/sh
#Fecha: 26 de Julio de 2012
#Autor: Omar A. Orozco
#Twitter: @csimxnet @oorozcoo
#Website: www.csimx.net
#Version: 0.1
#Fecha de modificacion:
#


while [ "$OPCION" != "0" ]; do
  echo ""
  echo "          Menu         "
  echo "      -----------      "
  echo "  1. Simple NSLookup"
  echo "  2. Query the MX Record"
  echo "  3. Query the NS Record"
  echo "  4. Query the SOA Record"
  echo "  5. View Available DNS Records"
  echo "  6. Reverse DNS lookup"
  echo "  7. Using Specific DNS Server"
  echo "  8. Change the port number to connect with"
  echo "  9. Change timeout interval to wait for a reply"
  echo "  10. Enabling debug mode"
  echo "  0. Salir"
  echo -e "\n  Elige una opcion"
    read OPCION

  case $OPCION in
    1) 
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup $DOMAIN
      ;;
    2)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup -query=mx $DOMAIN
      ;;
    3)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup -type=ns $DOMAIN
      ;;
    4)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup -type=soa $DOMAIN
      ;;
    5)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup -type=any $DOMAIN
      ;;
    6)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup $DOMAIN
      ;;
    7)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      echo -e "\nIngresa el servidor DNS a utilizar"
      echo -e "\nEjemplo 8.8.8.8 o ns1.ejemplo.com"
      read SERVER
      nslookup $DOMAIN $SERVER
      ;;
    8)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup -query=mx $DOMAIN
      ;;
    9)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup -timeout=10 $DOMAIN
      ;;
    10)
      echo
      echo -e "\nIngresa el dominio o la IP"
      read DOMAIN
      nslookup -debug $DOMAIN
      ;;
  esac
done
echo "----------------"
echo "Hasta Pronto!!"
echo "----------------"

Leer más...

[Python] Goo - Acorta tu URL

d
Autor: @The_Swash
Descripción : Un acortador de url que la obtiene de goo.gl

#----------------------------------------------------------
# Obtener URL acortada mediante http://goo.gl
# Programador: The Swash
# Agradecimientos: Psymera, 11Sep, [Zero] y todo h-sec
# Website: http://h-sec.org
#----------------------------------------------------------
 
import socket, urllib, re
def GetGooURL(url):
    header = ['POST /api/shorten HTTP/1.1\r\n',
              'Host: goo.gl\r\n',
              'Content-Type: application/x-www-form-urlencoded;charset=utf-8\r\n',
              'Content-Length: 41\r\n',
              'Connection: close\r\n\r\n',
              'URLENCODE']
    if re.match('^http://', url):
        url2 = url
    else:
        url2 = 'http://' + url
    address = socket.gethostbyname('goo.gl')
    link = urllib.urlencode({'url':url2})
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    header[5] = link + '&security_token\r\n'
    length = len(header)
    try:
        sock.connect((address,80))
        for i in range(length):
            sock.send(header[i])
        buff = sock.recv(1024)
    except:
        return 'Error de conexion'
     
    sock.close()
    data = re.findall('Location: (.+)\r\n', buff)
    return data[0]
 
url = GetGooURL('h-sec.org')
print url
raw_input()
Leer más...

Versions.sh

d
Nombre: Versions.sh
Autor: Damon Parker
Descripción: Shell script para encontrar las versiones instaladas de los Demonios Principales de un Servidor.
Visto en Damon Parker
#!/bin/sh

# $Id: versions.sh 30 2007-02-26 19:18:48Z damonp $
#
# Shell script to list versions of common server daemons and utilities
#
# Copyright (c) 2007 Damon Parker < damonp@damonparker.org >
# Licensed under the GNU GPL.  See http://www.gnu.org/licenses/gpl.html

# This script is not supported in any way.  Use at your own risk.
#

uname -a

if [ -f /etc/redhat-release ]; then
        echo
        echo Redhat Version:
        cat /etc/redhat-release
fi

echo
echo Apache:
httpd -v
php -v

echo
echo MySQL:
mysql -V

echo
echo Security:
ssh -V
openssl version

echo
echo Network:
/sbin/ifconfig
Leer más...

tar.py

d
Nombre: tar.py
Autor: James Knowlton
Descripción: Realiza acciones en un archivo tar basado en la selección de menú
Visto en: Developer Works
                                                              
#!/usr/bin/python

import tarfile, sys

try:
    #open tarfile
    tar = tarfile.open(sys.argv[1], "r:tar")

    #present menu and get selection
    selection = raw_input("Enter\n\
    1 to extract a file\n\
    2 to display information on a file in the archive\n\
    3 to list all the files in the archive\n\n")

    #perform actions based on selection above
    if selection == "1":
        filename = raw_input("enter the filename to extract:  ")
        tar.extract(filename)
    elif selection == "2":
        filename = raw_input("enter the filename to inspect:  ")
        for tarinfo in tar:
            if tarinfo.name == filename:
                print "\n\
                Filename:\t\t", tarinfo.name, "\n\
                Size:\t\t", tarinfo.size, "bytes\n"
    elif selection == "3":
        print tar.list(verbose=True)

except:
    print "There was a problem running the program"

Permisos: chmod 700 tar.py 
Ejecución: ./tar.py [ archivo.tar ]
Leer más...

Userpwd.py

d
Nombre: Userpwd.py
Autor: James Knowlton
Descripción: Comprueba identificadores de usuario y contraseñas para el cumplimiento de políticas de seguridad
Visto en Developer Works
#!/usr/bin/python

import pwd

#initialize counters
erroruser = []
errorpass = []

#get password database
passwd_db = pwd.getpwall()

try:
    #check each user and password for validity
    for entry in passwd_db:
        username = entry[0]
        password = entry [1]
        if len(username) < 6:
            erroruser.append(username)
        if len(password) < 8:
            errorpass.append(username)

    #print results to screen
    print "The following users have an invalid userid (less than six characters):"
    for item in erroruser:
        print item
    print "\nThe following users have invalid password(less than eight characters):"
    for item in errorpass:
        print item
except:
    print "There was a problem running the script."

Leer más...

Process.py

d
Nombre: Process.py
Autor: James Knowlton.
Descripción: Muestra la información de un proceso que se ejecuta en un formato amigable
Visto en Developer Works
#!/usr/bin/python

import commands, os, string

program = raw_input("Enter the name of the program to check: ")

try:
    #perform a ps command and assign results to a list
    output = commands.getoutput("ps -f|grep " + program)
    proginfo = string.split(output)

    #display results
    print "\n\
    Full path:\t\t", proginfo[5], "\n\
    Owner:\t\t\t", proginfo[0], "\n\
    Process ID:\t\t", proginfo[1], "\n\
    Parent process ID:\t", proginfo[2], "\n\
    Time started:\t\t", proginfo[4]
except:
    print "There was a problem with the program."
Leer más...

SearchFiles.py

d
Nombre: SearchFiles.py
Autor: James Knowlton.
Descripción: Script que busca un patrón de archivos y al encontrarlo presenta los archivos y sus permisos UGO correspondientes. Básicamente desarrolla 3 tareas: Obtiene el patrón de búsqueda, realiza la búsqueda de archivos y presenta los resultados en pantalla
Visto en Developer Works
#!/usr/bin/python

import stat, sys, os, string, commands

#Getting search pattern from user and assigning it to a list

try:
    #run a 'find' command and assign results to a variable
    pattern = raw_input("Enter the file pattern to search for:\n")
    commandString = "find " + pattern
    commandOutput = commands.getoutput(commandString)
    findResults = string.split(commandOutput, "\n")

    #output find results, along with permissions
    print "Files:"
    print commandOutput
    print "================================"
    for file in findResults:
        mode=stat.S_IMODE(os.lstat(file)[stat.ST_MODE])
        print "\nPermissions for file ", file, ":"
        for level in "USR", "GRP", "OTH":
            for perm in "R", "W", "X":
                if mode & getattr(stat,"S_I"+perm+level):
                    print level, " has ", perm, " permission"
                else:
                    print level, " does NOT have ", perm, " permission"
except:
    print "There was a problem - check the message above"
Permisos: chmod 700 SearchFiles.py 
Ejecución: ./SearchFiles.py [ Patrón a buscar ]
Ejemplo: ./SearchFiles.py j*.py
Leer más...

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

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

#!/bin/bash

NOMBRE=""

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

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

cd $BACKDIR

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


done

####
Leer más...