2022-05-14 03:18:52 -04:00
|
|
|
import os
|
|
|
|
import time
|
2022-05-20 20:22:00 -04:00
|
|
|
import subprocess
|
2023-06-06 04:48:14 -04:00
|
|
|
from consultas.querys_sqlite import get_geoloc
|
2024-03-05 00:53:17 -03:00
|
|
|
from iplocate import (
|
|
|
|
requests,
|
|
|
|
token,
|
|
|
|
filtro_ip_propia,
|
|
|
|
selfpath,
|
|
|
|
parser,
|
|
|
|
log_usage,
|
|
|
|
valid_ip
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
from json import loads
|
2022-05-14 03:18:52 -04:00
|
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import create_engine
|
2022-05-15 04:06:41 -04:00
|
|
|
from sqlalchemy.orm import relationship, sessionmaker
|
2022-05-14 03:18:52 -04:00
|
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
|
|
from sqlalchemy import Column, Integer, String, Sequence, update
|
2024-03-05 00:53:17 -03:00
|
|
|
# from sqlalchemy.orm.session import Session
|
|
|
|
from sqlalchemy.sql.expression import select # , distinct
|
2022-05-15 04:06:41 -04:00
|
|
|
from sqlalchemy.sql.schema import ForeignKey
|
2022-05-20 20:22:00 -04:00
|
|
|
from rich.progress import Progress, track
|
|
|
|
from rich.console import Console
|
2022-05-26 01:30:51 -04:00
|
|
|
from mapsgen import maps_gen
|
2022-05-14 03:18:52 -04:00
|
|
|
|
2022-05-20 20:22:00 -04:00
|
|
|
logs_dir = parser.get('bash_script', 'destino_log')
|
2022-05-14 03:18:52 -04:00
|
|
|
logs_dir = logs_dir.strip("'")
|
2022-05-20 20:22:00 -04:00
|
|
|
base_de_datos = f'sqlite:////{selfpath}/ipinfo.db'
|
2022-05-14 03:18:52 -04:00
|
|
|
|
2022-05-20 20:22:00 -04:00
|
|
|
console = Console()
|
2022-05-14 03:18:52 -04:00
|
|
|
Base = declarative_base()
|
|
|
|
|
2023-12-26 02:11:15 -03:00
|
|
|
|
2022-05-15 04:06:41 -04:00
|
|
|
# Tabla registro ip info
|
|
|
|
class Registro(Base):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Definición de tabla 'Registro'"""
|
|
|
|
|
2022-05-15 04:06:41 -04:00
|
|
|
__tablename__ = 'registro'
|
2024-03-05 00:53:17 -03:00
|
|
|
ip = Column(String, primary_key=True)
|
|
|
|
hostname = Column(String, nullable=True)
|
|
|
|
anycast = Column(String, nullable=True)
|
|
|
|
cuidad = Column(String, nullable=True)
|
|
|
|
region = Column(String, nullable=True)
|
|
|
|
pais = Column(String, nullable=True)
|
|
|
|
geoloc = Column(String, nullable=True)
|
2022-05-15 04:06:41 -04:00
|
|
|
organizacion = Column(String, nullable=True)
|
2024-03-05 00:53:17 -03:00
|
|
|
fecha_reg = Column(Integer, default=int(time.mktime(time.localtime())))
|
|
|
|
tzone = Column(String, nullable=True)
|
|
|
|
cod_post = Column(String, nullable=True)
|
|
|
|
visitas = relationship(
|
|
|
|
"Visita",
|
|
|
|
order_by="Visita.id",
|
|
|
|
back_populates="visita_ip",
|
|
|
|
cascade="all, delete, delete-orphan"
|
|
|
|
)
|
2022-05-15 04:06:41 -04:00
|
|
|
|
2022-05-16 03:24:08 -04:00
|
|
|
def get_fecha(self):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Convierte fecha 'unix epoch' y devuelve en formato local"""
|
2024-03-05 00:53:17 -03:00
|
|
|
return time.asctime(
|
|
|
|
time.localtime(
|
|
|
|
int(self.fecha_reg.__repr__())
|
|
|
|
)
|
|
|
|
)
|
2022-05-16 03:24:08 -04:00
|
|
|
|
|
|
|
def __repr__(self) -> str:
|
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
rep = f'ip={self.ip};host={self.hostname};' \
|
|
|
|
f'anycast={self.anycast};cuidad={self.cuidad};' \
|
|
|
|
f'region={self.region};pais={self.pais};' \
|
|
|
|
f'geoloc={self.geoloc};organizacion={self.organizacion};' \
|
|
|
|
f'fecha_reg={self.get_fecha()};tzone={self.tzone};' \
|
|
|
|
f'cod_post={self.cod_post}'
|
2022-05-16 03:24:08 -04:00
|
|
|
return rep
|
|
|
|
except Exception as ex:
|
|
|
|
print('Exception :', ex)
|
|
|
|
return "error repr"
|
|
|
|
|
2022-05-15 04:06:41 -04:00
|
|
|
|
2022-05-14 03:18:52 -04:00
|
|
|
class Visita(Base):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Definición de tabla 'Visita'"""
|
2022-05-14 03:18:52 -04:00
|
|
|
__tablename__ = 'visita'
|
2024-03-05 00:53:17 -03:00
|
|
|
id = Column(Integer, Sequence('visita_id_seq'), primary_key=True)
|
|
|
|
ip = Column(String, ForeignKey('registro.ip'))
|
2022-05-18 01:41:55 -04:00
|
|
|
cod_html = Column(Integer)
|
2024-03-05 00:53:17 -03:00
|
|
|
fecha = Column(Integer)
|
|
|
|
metodo = Column(String, default='---')
|
2022-05-18 01:41:55 -04:00
|
|
|
consulta = Column(String, default='---')
|
2023-12-26 02:11:15 -03:00
|
|
|
registro = Column(Integer, default=0)
|
|
|
|
visita_ip = relationship("Registro", back_populates="visitas")
|
2022-05-14 03:18:52 -04:00
|
|
|
|
|
|
|
def get_fecha(self):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Convierte fecha 'unix epoch' y devuelve en formato local"""
|
2024-03-05 00:53:17 -03:00
|
|
|
return time.asctime(
|
|
|
|
time.localtime(
|
|
|
|
int(self.fecha.__repr__())
|
|
|
|
)
|
|
|
|
)
|
2022-05-14 03:18:52 -04:00
|
|
|
|
|
|
|
def consulta_registro(self):
|
|
|
|
return True if self.registro == 1 else False
|
|
|
|
|
|
|
|
def __repr__(self) -> str:
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Representación en cadena de texto del los datos en tabla"""
|
2022-05-16 03:24:08 -04:00
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
rep = f'id={self.id},ip={self.ip},html={self.cod_html},' \
|
|
|
|
f'fecha={self.get_fecha()},metodo={self.metodo}' \
|
|
|
|
f',request={self.consulta}'
|
2022-05-16 03:24:08 -04:00
|
|
|
return rep
|
|
|
|
except Exception as ex:
|
|
|
|
print('Exception :', ex)
|
|
|
|
return "Error repr Visita"
|
2022-05-14 03:18:52 -04:00
|
|
|
|
|
|
|
|
|
|
|
engine = create_engine(base_de_datos)
|
|
|
|
Base.metadata.create_all(engine)
|
|
|
|
Session = sessionmaker(bind=engine)
|
|
|
|
session = Session()
|
|
|
|
|
|
|
|
|
|
|
|
# Formatos fechas logs:
|
|
|
|
"""
|
|
|
|
# access.log == reverse_access.log
|
|
|
|
# error.log == reverse_error.log
|
|
|
|
fecha_error = "2022/05/10 07:11:46"
|
|
|
|
fecha_access = "10/May/2022:11:42:14 -0400".split(' ')[0]
|
|
|
|
"""
|
|
|
|
|
2023-12-26 02:11:15 -03:00
|
|
|
|
2022-05-14 03:18:52 -04:00
|
|
|
def fecha_access_to_epoch(fecha):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Convierte la fecha del formato entregado por access.log
|
2024-03-05 00:53:17 -03:00
|
|
|
y reverse_access.log (nginx) al formato unix epoch.
|
2022-05-14 03:18:52 -04:00
|
|
|
:fecha: str Fecha
|
|
|
|
:returns: int unix epoch fecha (secs)
|
|
|
|
"""
|
|
|
|
fecha = datetime.strptime(fecha, '%d/%b/%Y:%H:%M:%S')
|
|
|
|
fecha_unix = int(time.mktime(fecha.timetuple()))
|
|
|
|
return fecha_unix
|
|
|
|
|
2023-12-26 02:11:15 -03:00
|
|
|
|
2022-05-14 03:18:52 -04:00
|
|
|
def fecha_error_to_epoch(fecha):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Convierte la fecha del formato entregado por error.log
|
2022-05-14 03:18:52 -04:00
|
|
|
y reverse_error.log (nginx) al formato unix epoch.
|
|
|
|
:fecha_local: str Fecha
|
|
|
|
:returns: int unix epoch fecha (secs)
|
|
|
|
"""
|
|
|
|
fecha = datetime.strptime(fecha, '%Y/%m/%d %H:%M:%S')
|
|
|
|
fecha_unix = int(time.mktime(fecha.timetuple()))
|
|
|
|
return fecha_unix
|
|
|
|
|
2023-12-26 02:11:15 -03:00
|
|
|
|
2022-05-14 03:18:52 -04:00
|
|
|
def epoch_to_local(fecha):
|
|
|
|
"""Convierte fecha unix epoch a localtime
|
|
|
|
:fecha: int Fecha (secs)
|
|
|
|
:returns: str Fecha
|
|
|
|
"""
|
|
|
|
return time.asctime(time.localtime(int(fecha)))
|
|
|
|
|
|
|
|
|
|
|
|
def ip_registrada(ip):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Retorna respuesta a consulta valor de columna 'registro'
|
|
|
|
en tabla 'Visita' para ip pasada como argumento.
|
|
|
|
"""
|
2022-05-15 04:06:41 -04:00
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
ip_reg = session.query(Visita).filter(
|
|
|
|
Visita.ip == ip
|
|
|
|
).filter(
|
|
|
|
Visita.registro == 1
|
|
|
|
).first()
|
2022-05-15 04:06:41 -04:00
|
|
|
except Exception as ex:
|
|
|
|
print('Exception', ex)
|
2022-05-16 03:24:08 -04:00
|
|
|
ip_reg = None
|
|
|
|
return 0 if ip_reg is None else ip_reg.registro
|
2022-05-14 03:18:52 -04:00
|
|
|
|
|
|
|
|
|
|
|
def carga_access_log(log):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Procesa logs del tipo access, filtra IPs propias (publica y locales),
|
2024-03-05 00:53:17 -03:00
|
|
|
acorta las peticiones donde es necesario, convierte fechas a formato unix
|
|
|
|
epoch, los añade a la session para la tabla 'Visita'.
|
|
|
|
Finalmente realiza la transaccion utilizando clase Progres() del modulo
|
|
|
|
rich. Borra el log procesado."""
|
2022-05-14 03:18:52 -04:00
|
|
|
if os.path.exists(log):
|
2022-05-20 20:22:00 -04:00
|
|
|
nombre_log = log.split('/')[-1]
|
2024-03-05 00:53:17 -03:00
|
|
|
console.print(
|
|
|
|
f'[yellow]Procesando [[/yellow]{nombre_log}[yellow]][/yellow]'
|
|
|
|
)
|
2022-05-14 03:18:52 -04:00
|
|
|
try:
|
|
|
|
with open(log, 'r') as lista:
|
2022-05-20 20:22:00 -04:00
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
largo = subprocess.run(
|
|
|
|
['wc', '-l', log],
|
|
|
|
capture_output=True,
|
|
|
|
text=True
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
largo = int(largo.stdout.split(' ')[0])
|
2024-03-05 00:53:17 -03:00
|
|
|
for linea in track(
|
|
|
|
lista,
|
|
|
|
total=largo,
|
|
|
|
description='[blue bold]Cargando [/blue bold]'
|
|
|
|
):
|
2022-05-20 20:22:00 -04:00
|
|
|
ip = linea.split(' ')[0]
|
|
|
|
if filtro_ip_propia(ip):
|
|
|
|
try:
|
|
|
|
ip = linea.split(' ')[0]
|
|
|
|
except Exception as ex:
|
|
|
|
ip = None
|
|
|
|
print('Exception split IP', ex)
|
|
|
|
try:
|
|
|
|
metodo = linea.split('"')[1].split(' ')[0]
|
|
|
|
if len(metodo) > 10 or len(metodo) < 2:
|
|
|
|
metodo = '---'
|
2024-03-05 00:53:17 -03:00
|
|
|
except Exception:
|
2022-05-18 01:41:55 -04:00
|
|
|
metodo = '---'
|
2022-05-20 20:22:00 -04:00
|
|
|
try:
|
|
|
|
url = linea.split('"')[1].split(' ')[1]
|
|
|
|
if len(url) > 254:
|
|
|
|
url = url[:252]+'...'
|
2024-03-05 00:53:17 -03:00
|
|
|
except Exception:
|
2022-05-20 20:22:00 -04:00
|
|
|
url = '---'
|
|
|
|
try:
|
|
|
|
codigo = int(linea.split('"')[2].split(' ')[1])
|
|
|
|
if len(str(codigo)) != 3:
|
|
|
|
codigo = 0
|
2024-03-05 00:53:17 -03:00
|
|
|
except Exception:
|
2022-05-18 01:41:55 -04:00
|
|
|
codigo = 0
|
2022-05-20 20:22:00 -04:00
|
|
|
try:
|
|
|
|
fecha = linea.split(' ')[3][1:]
|
|
|
|
fecha = fecha_access_to_epoch(fecha)
|
|
|
|
except Exception as ex:
|
|
|
|
fecha = None
|
|
|
|
print('Exception split Fecha:', ex)
|
|
|
|
if ip_registrada(ip):
|
2024-03-06 02:02:06 -03:00
|
|
|
session.add(
|
|
|
|
Visita(
|
|
|
|
ip=ip,
|
|
|
|
cod_html=codigo,
|
|
|
|
fecha=fecha,
|
|
|
|
metodo=metodo,
|
|
|
|
consulta=url,
|
|
|
|
registro=1
|
|
|
|
)
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
else:
|
2024-03-06 02:02:06 -03:00
|
|
|
session.add(
|
|
|
|
Visita(
|
|
|
|
ip=ip,
|
|
|
|
cod_html=codigo,
|
|
|
|
fecha=fecha,
|
|
|
|
metodo=metodo,
|
|
|
|
consulta=url
|
|
|
|
)
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
except Exception as ex:
|
|
|
|
print('Exception: ', ex)
|
|
|
|
try:
|
|
|
|
with Progress() as prog, session:
|
2024-03-05 00:53:17 -03:00
|
|
|
task1 = prog.add_task(
|
|
|
|
"[yellow bold]Guardando[/yellow bold]",
|
|
|
|
total=len(session.new)
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
session.commit()
|
|
|
|
while not prog.finished:
|
|
|
|
prog.update(task1, advance=0.1)
|
|
|
|
time.sleep(0.05)
|
|
|
|
except Exception as ex:
|
|
|
|
print('Exception Progress: ', ex)
|
2024-03-05 00:53:17 -03:00
|
|
|
console.print(
|
|
|
|
'[magenta] - Carga completa.. borrando log[/magenta]\n'
|
|
|
|
)
|
2022-05-14 03:18:52 -04:00
|
|
|
os.remove(log)
|
|
|
|
return True
|
2024-03-05 00:53:17 -03:00
|
|
|
except Exception:
|
|
|
|
console.print(
|
|
|
|
f'[red]Error al intentar abrir/cargar: [{log}[/red]]\n'
|
|
|
|
)
|
2022-05-14 03:18:52 -04:00
|
|
|
return False
|
|
|
|
else:
|
2024-03-05 00:53:17 -03:00
|
|
|
console.print(
|
|
|
|
f'[bold red]Log: [[/bold red]{log}[bold red]] '
|
|
|
|
'inexistente.[/bold red]\n'
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
return False
|
2022-05-14 03:18:52 -04:00
|
|
|
|
|
|
|
|
|
|
|
def carga_error_logs(log):
|
2024-03-05 00:53:17 -03:00
|
|
|
"""Procesa logs del tipo error, acorta los donde es necesario, convierte
|
|
|
|
fechas a formato unix epoch, filtra IPs propias (publica y locales), los
|
|
|
|
añade a session para tabla 'Visita'.
|
|
|
|
Finalmente realiza la transaccion utilizando clase 'Progress' del modulo
|
|
|
|
rich. Borra el log procesado."""
|
2022-05-14 03:18:52 -04:00
|
|
|
if os.path.exists(log):
|
2022-05-20 20:22:00 -04:00
|
|
|
nombre_log = log.split('/')[-1]
|
2024-03-05 00:53:17 -03:00
|
|
|
console.print(
|
|
|
|
f'[yellow]Procesando [[/yellow]{nombre_log}[yellow]][/yellow]'
|
|
|
|
)
|
2022-05-14 03:18:52 -04:00
|
|
|
try:
|
|
|
|
with open(log, 'r') as lista:
|
2022-11-24 00:40:20 -03:00
|
|
|
ip, fecha, url, metodo = None, None, None, None
|
2022-05-20 20:22:00 -04:00
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
largo = subprocess.run(
|
|
|
|
['wc', '-l', log],
|
|
|
|
capture_output=True,
|
|
|
|
text=True
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
largo = int(largo.stdout.split(' ')[0])
|
2024-03-05 00:53:17 -03:00
|
|
|
for linea in track(
|
|
|
|
lista,
|
|
|
|
total=largo,
|
|
|
|
description='[blue bold]Cargando [/blue bold]'
|
|
|
|
):
|
2022-05-20 20:22:00 -04:00
|
|
|
linea = linea.split('\n')[0]
|
|
|
|
if (linea.rfind('[notice]') > 0 or linea.rfind('[crit]') > 0):
|
|
|
|
if linea.find('[crit]') > 0:
|
|
|
|
try:
|
|
|
|
ip = linea.split('client: ')[1].split(',')[0]
|
|
|
|
except Exception as ex:
|
2024-03-05 00:53:17 -03:00
|
|
|
log_usage(
|
|
|
|
'Exception Ip error_log {crit}',
|
|
|
|
ex
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
ip = None
|
|
|
|
try:
|
|
|
|
fecha = ' '.join(linea.split(' ')[0:2])
|
|
|
|
except Exception:
|
|
|
|
fecha = None
|
|
|
|
try:
|
|
|
|
url = linea.split('"')[1].split(' ')[1]
|
|
|
|
if len(url) > 254:
|
|
|
|
url = url[:252]+'...'
|
|
|
|
except Exception:
|
|
|
|
url = ' '.join(linea.split(' ')[5:])
|
|
|
|
try:
|
|
|
|
metodo = linea.split('"')[1].split(' ')[0]
|
|
|
|
except Exception:
|
|
|
|
metodo = '---'
|
|
|
|
else:
|
2022-05-18 01:41:55 -04:00
|
|
|
try:
|
|
|
|
ip = linea.split('client: ')[1].split(',')[0]
|
|
|
|
except Exception as ex:
|
2024-03-05 00:53:17 -03:00
|
|
|
log_usage(
|
|
|
|
'Exception Ip error_log {notice}',
|
|
|
|
ex
|
|
|
|
)
|
2022-05-18 01:41:55 -04:00
|
|
|
ip = None
|
|
|
|
try:
|
|
|
|
fecha = ' '.join(linea.split(' ')[0:2])
|
|
|
|
except Exception:
|
|
|
|
fecha = None
|
|
|
|
try:
|
2022-05-20 20:22:00 -04:00
|
|
|
metodo = linea.split('request: "')[1].split(' ')[0]
|
2022-05-18 01:41:55 -04:00
|
|
|
except Exception:
|
2022-05-20 20:22:00 -04:00
|
|
|
metodo = '---'
|
2022-05-18 01:41:55 -04:00
|
|
|
try:
|
2022-05-20 20:22:00 -04:00
|
|
|
url = linea.split('"')[1].split(' ')[0]
|
|
|
|
if len(url) > 254:
|
|
|
|
url = url[:252]+'...'
|
2022-05-18 01:41:55 -04:00
|
|
|
except Exception:
|
2022-05-20 20:22:00 -04:00
|
|
|
url = '---'
|
2023-12-26 02:11:15 -03:00
|
|
|
if ip is not None:
|
2022-11-24 00:40:20 -03:00
|
|
|
if filtro_ip_propia(ip):
|
2023-12-26 02:11:15 -03:00
|
|
|
fecha = int(fecha_error_to_epoch(fecha))
|
2022-11-24 00:40:20 -03:00
|
|
|
codigo = 0
|
|
|
|
if ip_registrada(ip):
|
2024-03-05 00:53:17 -03:00
|
|
|
session.add(
|
|
|
|
Visita(
|
|
|
|
ip=ip,
|
|
|
|
cod_html=codigo,
|
|
|
|
fecha=fecha,
|
|
|
|
consulta=url,
|
|
|
|
metodo=metodo,
|
|
|
|
registro=1
|
|
|
|
)
|
|
|
|
)
|
2022-11-24 00:40:20 -03:00
|
|
|
else:
|
2024-03-05 00:53:17 -03:00
|
|
|
session.add(
|
|
|
|
Visita(
|
|
|
|
ip=ip,
|
|
|
|
cod_html=codigo,
|
|
|
|
fecha=fecha,
|
|
|
|
consulta=url,
|
|
|
|
metodo=metodo
|
|
|
|
)
|
|
|
|
)
|
2022-11-24 00:40:20 -03:00
|
|
|
else:
|
|
|
|
log_usage('carga error.log', linea)
|
2022-05-20 20:22:00 -04:00
|
|
|
except Exception as ex:
|
2022-11-24 00:40:20 -03:00
|
|
|
print('[Procesando *Error.log] Exception: ', ex)
|
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
info_error = f'IP:[{ip}] - FECHA:[{fecha}] - ' \
|
|
|
|
f'METODO:[{metodo}] - URL:[{url}]'
|
2022-11-24 00:40:20 -03:00
|
|
|
log_usage('Exception error.log', info_error)
|
2024-03-05 00:53:17 -03:00
|
|
|
except Exception:
|
2022-11-24 00:40:20 -03:00
|
|
|
pass
|
2022-05-20 20:22:00 -04:00
|
|
|
try:
|
|
|
|
with Progress() as prog, session:
|
2024-03-05 00:53:17 -03:00
|
|
|
task1 = prog.add_task(
|
|
|
|
"[yellow bold]Guardando[/yellow bold]",
|
|
|
|
total=len(session.new)
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
session.commit()
|
|
|
|
while not prog.finished:
|
|
|
|
prog.update(task1, advance=0.1)
|
|
|
|
time.sleep(0.05)
|
|
|
|
except Exception as ex:
|
2022-11-24 00:40:20 -03:00
|
|
|
log_usage('Exception error.log - Progress session commit', ex)
|
2024-03-05 00:53:17 -03:00
|
|
|
console.print(
|
|
|
|
'[magenta] - Carga completa.. borrando log[/magenta]\n'
|
|
|
|
)
|
2022-05-14 03:18:52 -04:00
|
|
|
os.remove(log)
|
|
|
|
return True
|
2024-03-05 00:53:17 -03:00
|
|
|
except Exception:
|
|
|
|
console.print(
|
|
|
|
f'[red]Error al intentar abrir/cargar: [{log}[/red]]\n'
|
|
|
|
)
|
|
|
|
log_usage('Error al abrir/cargar', log)
|
2022-05-14 03:18:52 -04:00
|
|
|
return False
|
|
|
|
else:
|
2024-03-05 00:53:17 -03:00
|
|
|
console.print(
|
|
|
|
f'[bold red]Log: [[/bold red]{log}[bold red]]'
|
|
|
|
' inexistente.[/bold red]\n'
|
|
|
|
)
|
|
|
|
log_usage('Log inexistente', log)
|
2022-05-14 03:18:52 -04:00
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def carga_logs():
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Procesa logs existentes en directorio 'logs_dir', según nombre."""
|
2022-05-20 20:22:00 -04:00
|
|
|
logpath = logs_dir+'/access.log'
|
|
|
|
if os.path.exists(logpath):
|
|
|
|
carga_access_log(logpath)
|
|
|
|
logpath = logs_dir+'/reverse-access.log'
|
|
|
|
if os.path.exists(logpath):
|
|
|
|
carga_access_log(logpath)
|
|
|
|
logpath = logs_dir+'/error.log'
|
|
|
|
if os.path.exists(logpath):
|
|
|
|
carga_error_logs(logpath)
|
|
|
|
logpath = logs_dir+'/reverse-error.log'
|
|
|
|
if os.path.exists(logpath):
|
|
|
|
carga_error_logs(logpath)
|
2022-05-14 03:18:52 -04:00
|
|
|
|
|
|
|
|
|
|
|
def carga_registro_ip(ip_info):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Guarda datos del diccionario ip_info en tabla 'Registro',
|
|
|
|
Actualiza columna 'registro' a '1' en la tabla 'Visita'
|
|
|
|
para IPs guardadas en 'Registro' en esta sessión.
|
|
|
|
"""
|
2022-05-14 03:18:52 -04:00
|
|
|
if not ip_registrada(ip_info['ip']):
|
|
|
|
info_dic = {}
|
|
|
|
info_dic['ip'] = ip_info['ip']
|
2023-12-26 02:11:15 -03:00
|
|
|
info_dic['hostname'] = ip_info['hostname'] if 'hostname' in ip_info else None
|
2022-05-14 03:18:52 -04:00
|
|
|
info_dic['anycast'] = ip_info['anycast'] if 'anycast' in ip_info else None
|
|
|
|
info_dic['ciudad'] = ip_info['city'] if 'city' in ip_info else None
|
|
|
|
info_dic['region'] = ip_info['region'] if 'region' in ip_info else None
|
|
|
|
info_dic['pais'] = ip_info['country'] if 'country' in ip_info else None
|
|
|
|
info_dic['geoloc'] = ip_info['loc'] if 'loc' in ip_info else None
|
|
|
|
info_dic['organizacion'] = ip_info['org'] if 'org' in ip_info else None
|
|
|
|
info_dic['tzone'] = ip_info['timezone'] if 'timezone' in ip_info else None
|
|
|
|
info_dic['cod_post'] = ip_info['postal'] if 'postal' in ip_info else None
|
2022-05-15 04:06:41 -04:00
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
session.add(
|
|
|
|
Registro(
|
|
|
|
ip=info_dic['ip'],
|
|
|
|
hostname=info_dic['hostname'],
|
|
|
|
anycast=info_dic['anycast'],
|
|
|
|
cuidad=info_dic['ciudad'],
|
|
|
|
region=info_dic['region'],
|
|
|
|
pais=info_dic['pais'],
|
|
|
|
geoloc=info_dic['geoloc'],
|
|
|
|
organizacion=info_dic['organizacion'],
|
|
|
|
fecha_reg=int(time.mktime(time.localtime())),
|
|
|
|
tzone=info_dic['tzone'],
|
|
|
|
cod_post=info_dic['cod_post'],
|
|
|
|
)
|
|
|
|
)
|
2022-05-15 04:06:41 -04:00
|
|
|
session.commit()
|
|
|
|
except Exception as ex:
|
2022-11-24 00:40:20 -03:00
|
|
|
print('[session.commit(ADD REGISTRO)] Exception: ', ex)
|
|
|
|
print('Datos-Dic: ', info_dic)
|
2024-03-05 00:53:17 -03:00
|
|
|
stmt = update(Visita).where(
|
|
|
|
Visita.ip == ip_info['ip']
|
|
|
|
).values(
|
|
|
|
registro=1
|
|
|
|
).execution_options(synchronize_session="fetch")
|
2022-05-15 04:06:41 -04:00
|
|
|
try:
|
|
|
|
session.execute(stmt)
|
|
|
|
session.commit()
|
|
|
|
except Exception as ex:
|
2022-11-24 00:40:20 -03:00
|
|
|
print('[session.commit(UPDT VISITA)] Exception: ', ex)
|
2022-05-15 04:06:41 -04:00
|
|
|
|
2022-05-20 20:22:00 -04:00
|
|
|
|
|
|
|
def consulta_ip(ip_consulta, tkn=True):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Consulta API o base de datos por la IPs pasada como argumento,
|
|
|
|
filtra IPs validas antes de proceder.
|
|
|
|
"""
|
2024-02-14 01:02:02 -03:00
|
|
|
if valid_ip(ip_consulta):
|
2022-05-20 20:22:00 -04:00
|
|
|
match tkn:
|
|
|
|
case True:
|
|
|
|
consulta = f'https://ipinfo.io/{ip_consulta}{token}'
|
|
|
|
info_ip = requests.get(consulta).text
|
|
|
|
return loads(info_ip)
|
2023-12-26 02:11:15 -03:00
|
|
|
case False:
|
2022-05-20 20:22:00 -04:00
|
|
|
consulta = f'https://ipinfo.io/{ip_consulta}'
|
|
|
|
info_ip = requests.get(consulta).text
|
|
|
|
return loads(info_ip)
|
|
|
|
case None:
|
|
|
|
resp = consulta_db(ip_consulta)
|
2023-12-26 02:11:15 -03:00
|
|
|
return resp
|
|
|
|
|
2022-05-20 20:22:00 -04:00
|
|
|
|
2022-05-16 03:24:08 -04:00
|
|
|
def consulta_db(ip):
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Consulta base de datos por la IPs pasada como argumento.
|
|
|
|
Entrega la información de Registro, seguida por todas las visitas
|
|
|
|
y sus detalles.
|
|
|
|
"""
|
2022-05-16 03:24:08 -04:00
|
|
|
try:
|
2024-03-05 00:53:17 -03:00
|
|
|
statement = session.query(
|
|
|
|
Registro, Visita
|
|
|
|
).join('visitas').filter_by(ip=ip)
|
2022-05-16 03:24:08 -04:00
|
|
|
result = session.execute(statement).all()
|
|
|
|
return result
|
|
|
|
except Exception as ex:
|
|
|
|
print('Exception consulta_db:\n', ex)
|
|
|
|
|
2022-05-15 04:06:41 -04:00
|
|
|
|
2022-05-14 03:18:52 -04:00
|
|
|
def registro_ips():
|
2022-12-11 19:41:25 -03:00
|
|
|
"""Consulta API, obtiene datos de IPs en tabla 'Visita'
|
|
|
|
cuya valor en columna 'registro' sea '0'. Utiliza clase
|
|
|
|
Progress() para mostrar el progreso de la transacción.
|
|
|
|
"""
|
2022-05-20 20:22:00 -04:00
|
|
|
statement = select(Visita).filter_by(registro=0)
|
|
|
|
with Progress() as progress:
|
|
|
|
total = len(session.execute(statement).scalars().all())
|
2024-03-05 00:53:17 -03:00
|
|
|
task1 = progress.add_task(
|
|
|
|
"[bold blue]Cargando [/bold blue]",
|
|
|
|
total=total
|
|
|
|
)
|
2022-05-20 20:22:00 -04:00
|
|
|
total_ant = total
|
|
|
|
while not progress.finished:
|
|
|
|
res = session.execute(statement).scalars().first()
|
|
|
|
total_act = len(session.execute(statement).scalars().all())
|
|
|
|
avance = total_ant - total_act
|
|
|
|
total_ant = total_act
|
|
|
|
if res is None:
|
2023-12-26 02:11:15 -03:00
|
|
|
progress.update(task1, advance=avance)
|
2022-05-21 00:35:14 -04:00
|
|
|
else:
|
2023-12-26 02:11:15 -03:00
|
|
|
ip_actual = res.ip
|
2022-05-21 00:35:14 -04:00
|
|
|
ip_info = consulta_ip(ip_actual, True)
|
|
|
|
carga_registro_ip(ip_info)
|
|
|
|
progress.update(task1, advance=avance)
|
2024-03-05 00:53:17 -03:00
|
|
|
console.print(
|
|
|
|
'\n[bold yellow]Registro en base de datos finalizado.[/bold yellow]'
|
|
|
|
)
|
2022-05-21 00:35:14 -04:00
|
|
|
|
2022-05-26 01:30:51 -04:00
|
|
|
|
|
|
|
def mapsgen():
|
2024-03-05 00:53:17 -03:00
|
|
|
"""Realiza 2 consultas de los datos de columna 'geoloc' de la tabla
|
|
|
|
'Registro' según valor de columna 'cod_html' de la tabla 'Visita',
|
|
|
|
para valores 200 y otros. Llama a función maps_gen con estas listas
|
|
|
|
de valores como argumentos."""
|
2022-05-26 01:30:51 -04:00
|
|
|
try:
|
2023-06-06 04:48:14 -04:00
|
|
|
loc_200 = get_geoloc(200)
|
|
|
|
loc_300 = get_geoloc(300)
|
2023-12-26 02:11:15 -03:00
|
|
|
maps_gen(loc_200, loc_300)
|
2022-05-26 01:30:51 -04:00
|
|
|
except Exception as ex:
|
2023-05-13 19:03:57 -04:00
|
|
|
print('Exception mapsgen: ', ex)
|