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

Fortibackup.py - Robot para sacar copias de seguridad de dispositivos fortigate

d
Nombre: Fortibackup.py
 Autor: @epsilon77
 Tomado de DragonJar

 #!/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"

Ejecucion del Script

$ python fortibackup.py -f ruta-archivo-matrix

Regards, 
Snifer
Leer más...

File Watcher

d
Funcionamiento de script: El script crawlea un directorio y guarda en una "base de datos" (en este caso un diccionario serializado) la ruta de los archivos y sus respectivos hash md5. Para comprobar si un archivo a sido modificado, simplemente se compara su hash md5 con el que está en la BD y obviamente si el archivo no se encuentra en la BD es porque fue creado despues. 

Además indica los archivos de backup (.*~) que encuentra.

Autor: 11sept



    # -*- coding: utf-8 -*-
     
    #11Sep
     
    import os
    import sys
    import hashlib
    import cPickle
     
    recursividad = False
    diccionario = {}
    COLORES = {
        "archivo": "\033[91m\t[Archivo nuevo] %s\033[0m",     # Rojo
        "carpeta": "\033[94m\t[Carpeta nueva] %s\033[0m",     # Azul
        "modificado": "\033[93m\t[Modificado] %s\033[0m",     # Amarillo
        "backup": "\033[91m\t[BACKUP] %s\033[0m",             # Rojo
    }
     
    MENU = """Modo de uso:
    %s ruta [parametros]
     
    -r          Modo recursivo
    -a          Actualiza la BD
    -v          Para ver archivos y hashes
    """
     
     
    def imprimir(data, color):
        if its_linux:
            print COLORES[color] % data
        else:
            print data
     
    def es_archivo(ruta):
        if os.path.isfile(ruta):
            return True
     
    def es_directorio(ruta):
        if os.path.isdir(ruta):
            return True
     
    def guardar():
        with open("./data.sf", "wb") as archivo:
            cPickle.dump(diccionario, archivo, 2)
     
    def cargar():
        global diccionario
        try:
            with open("./data.sf", "rb") as archivo:
                diccionario = cPickle.load(archivo)
            return True
        except:
            return False
     
    def get_md5(ruta):
        md5 = hashlib.md5()
        with open(ruta, "r") as hash:
            for linea in hash.readlines():
                md5.update(linea)
        return md5.hexdigest()
     
    def recorrer(path, opt):
        if es_directorio(path):
           
            if not diccionario.has_key(path):
                diccionario[path] = {}
                imprimir(path, "carpeta")
           
            archivos = os.listdir(path)
           
            for archivo in archivos:
                ruta_completa = os.path.join(path, archivo)
                if es_archivo(ruta_completa):
                    extension = os.path.splitext(ruta_completa)[1]
                    if extension.endswith("~"):
                        imprimir(ruta_completa, "backup")
                   
                    if opt == 1:
                        diccionario[path][archivo] = get_md5(ruta_completa)
                    else:
                        md5 = get_md5(ruta_completa)
                        md5_bd = diccionario[path].get(archivo)
                        if md5_bd:    
                            if md5_bd != md5:
                                imprimir(ruta_completa, "modificado")
                        else:
                            imprimir(ruta_completa, "archivo")
     
                elif es_directorio(ruta_completa) and recursividad:
                    recorrer(ruta_completa, opt)
     
    its_linux = (os.name == "posix")
     
    argumentos = sys.argv
    if len(argumentos) > 1:
        parametros = []
        ruta = argumentos[1]
        parametros = argumentos[2:]
       
        if "-r" in parametros:
            recursividad = True
       
        if not es_directorio(ruta):
            print "Ruta no valida"
            exit()
        else:
            if "-a" in parametros:
                diccionario = {}
                recorrer(ruta, 1)
                guardar()
                exit()
            if cargar():
                recorrer(ruta, 2)
            else:
                recorrer(ruta, 1)
                guardar()
       
        if "-v" in parametros:
            for x, y in diccionario.iteritems():
                print x
                for archivo, hash in sorted(y.iteritems()):
                    print "\t", archivo, hash
           
    else:
        print MENU % os.path.split(argumentos[0])[-1]

Las opciones son:

-v: para ver la BD de los archivos y hashes md5
-a: para actualizar la BD
-r: para recorrer las carpetas en modo recursivo










Regards,
Snifer  

Fuente: Underc0de
Leer más...

WhoPingMe.py

d
Script: WhoPingMe.py
Description: Detect if you receive a Ping and make a list with Date.
Autor: @LordRNA


#! /usr/bin/env python
########################################################################
#Script     : WhoPingMe.py                                             #
#Description: Detect if you receive a Ping and make a list with Date.  #
#By         : LordRNA                                                  #
#Comments   : Tested on Python 2.6.5                                   #
########################################################################
import socket, datetime
def whopingme(date):

    source = '' #To put the IP Source.
    header = ["%i"%ord(x) for x in data]
#I made a list of int values for each byte in data variable. 
    if int(header[20])==8:#If Type(ICMP) is 8, i received a Echo Request.
        for x in range(4):#To make a string with the IP Source.
            source += str(header[12+x])
            if x<3:source data-blogger-escaped----="---" data-blogger-escaped-date="date" data-blogger-escaped-len="len" data-blogger-escaped-print="print"> "+ str(source)
#I deleted the Miliseconds with [:len(date)-7]

sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)

#ICMP Protocol on RAW Socket

while 1:

    data = sock.recv(21)#I Just want these bytes, IPHeader Lenght + Type(ICMPHeader)
    whopingme(data)#Sending data to whopingme() function.
Leer más...

Zone-H Reporter

d
Autor: @SankoSK
Descripcion: Script que interactua con Zone H permitiendo reportar desde la querida terminal. 
Nombre: ZoneHReporter.py

###################
#!/usr/bin/python #
# Zone-H Reporter #
# Coded by Sanko  #
###################
 
import urllib,urllib2
 
def main():
        options = """
#######################
#                     #
#  Zone - H Reporter  #
#  [0] Login          #
#  [1] Single Deface  #
#  [2] Mass Deface    #
#  [i] info methods   #
#                     #
#######################"""
 
        print options
        entrada = raw_input("Choose an option -> ")
        if entrada == 0:
                login('user','password')
        elif entrada == 1:
                uploadsingle('defacer','http://web.com/','15','1')
        elif entrada == 2:
                uploadmass('defacer','15','1') #Deben indicar en la funcion los domains defaceados
        elif entrada == 'i':
                info()
        else:
                print "Error , try again\n"
                main()
 
def login(user,password):
        url = 'http://www.zone-h.org/login'
        values = {'user':user,
                 'password':password}
 
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        resp = urllib2.urlopen(req)
        page = resp.read()
        print page
 
def uploadsingle(defacer,domain,hackmode,reason):
        url = 'http://www.zone-h.org/notify/single'
        values = {'defacer':defacer,
                  'domain1':domain,
                  'hackmode':hackmode,
                  'reason':reason,
                  'submit':'Send'}
 
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        resp = urllib2.urlopen(req)
        page = resp.read()
        print page
 
 
def uploadmass(defacer,hackmode,reason):
        url = 'http://www.zone-h.org/notify/mass'
        values = {'defacer':defacer,
                  'domain1':'',
                  'domain2':'',
                  'domain3':'',
                  'domain4':'',
                  'domain5':'',
                  'domain6':'',
                  'domain7':'',
                  'domain8':'',
                  'domain9':'',
                  'domain10':'',
                  'domain1':domain,
                  'hackmode':hackmode,
                  'reason':reason,
                  'submit':'Send'}
 
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        resp = urllib2.urlopen(req)
        page = resp.read()
        print page
 
def info():
        hackmodes = """
        [1] known vulnerability (i.e. unpatched system)
        [2] undisclosed (new) vulnerability
        [3] configuration / admin. mistake
        [4] brute force attack
        [5] social engineering
        [6] Web Server intrusion
        [7] Web Server external module intrusion
        [8] Mail Server intrusion
        [9] FTP Server intrusion
        [10] SSH Server intrusion
        [11] Telnet Server intrusion
        [12] RPC Server intrusion
        [13] Shares misconfiguration
        [14] Other Server intrusion
        [15] SQL Injection
        [16] URL Poisoning
        [17] File Inclusion
        [18] Other Web Application bug
        [19] Remote administrative panel access through bruteforcing
        [20] Remote administrative panel access through password guessing
        [21] Remote administrative panel access through social engineering
        [22] Attack against the administrator/user (password stealing/sniffing)
        [23] Access credentials through Man In the Middle attack
        [24] Remote service password guessing
        [25] Remote service password bruteforce
        [26] Rerouting after attacking the Firewall
        [27] Rerouting after attacking the Router
        [28] DNS attack through social engineering
        [29] DNS attack through cache poisoning
        [30] Not available
        [31] Cross-Site Scripting"""
 
        reasons = """
        [1] Heh...just for fun!
        [2] Revenge against that website
        [3] Political reasons
        [4] As a challenge
        [5] I just want to be the best defacer
        [6] Patriotism
        [7] Not available"""
        
        entrada = raw_input("info hackmodes | info reasons   --- > ")
        if entrada == "hackmodes":
                print hackmodes
        elif entrada == "reasons":
                print reasons
        else:
                print "Error"
                
 
main()

Leer más...

[Python] MP3 Downloader 0.1

d
Nombre: MP3Download.py
Descripción: Script python que nos permite descargar mp3 por media de mp3Skull.
Autor: Doddy



#!usr/bin/python
#MP3 Downloader 0.1
#Coded By Doddy H
 
import sys,urllib,urllib2,re,os,urlparse
 
def toma(web) :
 nave = urllib2.Request(web)
 nave.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5');
 op = urllib2.build_opener()
 return op.open(nave).read()
 
def head():
 print """
 
 @     @  @@@@@   @@@     @@@@     @@@@  @         @ @    @
 @     @  @    @ @   @    @   @   @    @ @         @ @@   @
 @@   @@  @    @     @    @    @  @    @  @   @   @  @@   @
 @@   @@  @    @     @    @    @  @    @  @   @   @  @ @  @
 @ @ @ @  @@@@@    @@     @    @  @    @  @   @   @  @ @  @
 @ @ @ @  @          @    @    @  @    @   @ @ @ @   @  @ @
 @  @  @  @          @    @    @  @    @   @ @ @ @   @   @@
 @  @  @  @      @   @    @   @   @    @    @   @    @   @@
 @     @  @       @@@     @@@@     @@@@     @   @    @    @
 
 
 
                                          
                              Coded By Doddy H
 
                                       
"""
 
def copyright():
 print "\n\n(C) Doddy Hackman 2012\n"
 raw_input()
 sys.exit(1)
 
def proxar(a,b,c):
 sys.stdout.write("\r[+] Status : %s / %s" % (a * b,c))
  
def down(file,filesave):
 print "\n[+] File to download : "+filesave+"\n"
 try:   
  urllib.urlretrieve(file,filesave,reporthook=proxar)
 except:
  print "\n[-] Error\n"
  copyright()
 print "\n\n[+] File Download in "+os.curdir+"/"+filesave
 
def buscar(titulo) : 
 
 songs = []
 datas =[]
 links = []
 datas_back = []
 links_back = []
 
 titulo = re.sub(" ","_",titulo)
 
 print "\n\n[+] Searching ...\n"
 
 code = toma("http://mp3skull.com/mp3/"+titulo+".html")
 
 if not (re.findall("Sorry, no results found for",code)):
 
  songs = re.findall("
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...

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

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

resizer.py

d
Nombre: resizer.py
Autor: @3zcurdia
Descripción: Script que redimensiona todas las imagenes del directorio donde se ejecute
#!/usr/bin/python

__author__="Luis Ezcurdia (3zcurdia)"
__email__="ing.ezcurdia@gmail.com"

from os import walk, getcwd
try:
	from PIL import Image
except:
    print("To run this script you will need  get instaled PIL")
    print("Downolad from: http://www.pythonware.com/products/pil/")

def image_resizer(directory, resolution=(640,480)):
    """Resize all files on directory"""
    for path,dirs,files in walk(directory):
        # get all files on directory
        for File in files:            
            abspath = path+"\\"+File
            #if File.endswith("jpg") or File.endswith("JPG"):
            try:
                im = Image.open(abspath)
                if im.size[0] > im.size[1]:
                    im = im.resize(resolution)
                else:
                    im = im.resize(resolution)
                print File, im.size
                im.save(abspath)
            except:
                continue
                
if __name__=="__main__":
    print("Image Resizer v0.1")
    if len(sys.argv)==2:	
        image_resizer( getcwd(), (int(sys.argv[1]),int(sys.argv[2])) )
        print("Done...")
    else:
        print """Runing mode:
    imageResizer   """

Leer más...

duplicatrix.py

d
Nombre: duplicatrix.py
Autor: @3zcurdia
Descripción: Script busca archivos duplicados del directorio donde se ejecute
#!/usr/bin/python

__author__="Luis Ezcurdia (3zcurdia)"
__email__="ing.ezcurdia@gmail.com"

import os,sys
import hashlib
try:
 import magic
except:
    print("To run this script you will need pymagic")

def search(path):
    print("Searching on route : %s ..." % path)
    hash_dic = {}
    duplicates = {}

    print("This will take a while.. so go and get a coffee.")
    for path,dirs,files in os.walk(path):
        for File in files:
            shafile = None
            shafile = hashlib.sha1()
            shafile.update( open( path+"/"+File, "rb" ).read() )
            key  = str( shafile.hexdigest() )
            if hash_dic.has_key( key ):

                if duplicates.has_key( key ):
                    duplicates[ key ].append( path+"/"+File )
                else:
                    duplicates[ key ] =  [  hash_dic[ key ] , path+"/"+File ]
            else:
                hash_dic[ key ] = path+"/"+File

    print("%d Files found" % len(duplicates))
    return duplicates, len(duplicates)

if __name__=="__main__":
    print("Duplicatrix v0.1")
    magic_square = magic.open(magic.MAGIC_NONE)
    magic_square.load()
    if len(sys.argv)>1:
        os.chdir(sys.argv[1])

    duplex, duplex_count =  search( os.getcwd() )

    if duplex_count>0:
        print("Generating Report: duplicated.txt")
        report = open( "duplicated.txt", "w")
        report.write( "Files duplicated: " + str(duplex_count)+ "\n" )
        for key in duplex:
            report.write( ("="*40)+ "\n"  )
            report.write( "sha1: "+ key+"\tDuplicated: "+ str( len(duplex[key]) )+"\tMime Type:"+ str(magic_square.file( duplex[key][0] )) + "\n"  )
            for item in duplex[key]:
                report.write( item+"\n" )
        report.close()
Leer más...

therminator.py

d
Nombre: therminator.py
Autor:@3zcurdia
Descripción: Script que elimina todos los molestos archivos Thumbs.db del directorio actual
#!/usr/bin/python

__author__="Luis Ezcurdia (3zcurdia)"
__email__="ing.ezcurdia@gmail.com"

from os import walk, remove, getcwd, sep

def thumbs_terminator(directory):
    """Erase all thumbs.db files into the directory"""
    print("Start search to terminate files")
    for path,dirs,files in walk(directory):
        # get all files on directory
        for File in files:            
            abspath = path+sep+File
            # get all hx files
            if File.lower()=="thumbs.db" or File.lower()=="zbthumbnail.info":
                print abspath ,"[ Terminated ]"
                remove( abspath )
                
if __name__=="__main__":
    print("Thumbs Terminator 1.0.1")
    thumbs_terminator( getcwd() )
    print("Hasta la vista baby...")
    
Leer más...

Ruletas Rusas solo para arriesgados

d
Autor: @jorgicio
Descripción: Script para jugar a la ruleta ;)
Nota: No nos hacemos responsable por el uso de los siguientes script, solo los traemos para poder dar a conocer, la ejecución de los mismos es total responsabilidad del que los haga correr.
Verifica si eres root si es asi simplemente reinicia el sistema.

#!/bin/sh
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]; then
    [ $[ $RANDOM % 6 ] == 0 ] && (echo "Moriste xD" && sleep 3 && /sbin/reboot ) || echo "Tu sistema aun vive"
else
    echo "Para jugar a la ruleta rusa debes ser root"
fi
exit 0

Lo mismo borra el directorio raiz (Root)

#!/bin/sh
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]; then
    [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "Tu sistema aun vive"
else
    echo "Para jugar a la ruleta rusa debes ser rooEtiquetast"
fi
exit 0
#!/bin/sh
[ $[ $RANDOM % 6 ] == 0 ] && (echo "moriras muahahahahaha" && :(){ ;|:& };: ) || echo "Todo esta bajo control" 

Ruleta rusa con Fork Bomb pero en Python


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import random
def fork_bomb():
    while True:
        os.fork()
aleatorio = random.randint(0,100000000)
if aleatorio % 6 == 0:
    fork_bomb()
else:
    print "Te salvaste weon xD"
Leer más...

Script para verificar la clave de una DB y verificar si fue crackeada

d
Autor: Desconocido
Descripción: Script en Python para verificar la presencia de la clave en la DB y si fué crackeada.

#! /usr/bin/env python

from hashlib import sha1
import getpass

def get_hash(plaintext, offset=5):
  hashed = sha1(plaintext).hexdigest()
  return '0' * offset + hashed[offset:]

def check_database(database, plaintext):
  uncracked_hash = get_hash(plaintext, 0)
  cracked_hash = get_hash(plaintext)

  database.seek(0);
  line_count = 0

  for line in database:
    line_count += 1
    if uncracked_hash in line:
      print ">Found somethng on line: %d" % line_count
      return ">Warning: Your password hash is in the database but uncracked. :|"
    elif cracked_hash in line:
      print ">Found somethng on line: %d" % line_count
      return ">Warning: Your password hash is in the database and was cracked. :["

  print ">Checked all %d lines" % line_count
  return "All Clear: your password hash isn't in the database! :]"



def main():
  database = open("combo_not.txt")
  while(True):
    password = getpass.getpass("Input a password to check: \n").strip()

    print check_database(database, password) 
    print "\n\n"
    

if __name__ == "__main__":
    main()
Visto en Twitter
Leer más...