AppInitDev
CÓDIGO FUENTE PÚBLICO

AUDITORIA_RASTREO_ONLINE.py

Archivo real del paquete para implementar la función. Descárgalo del ZIP para editarlo; no contiene claves privadas.

#!/usr/bin/env python3
"""Comprobación pública opcional y acotada. NO simula el índice de Google ni la IA.
Consulta robots.txt y un conjunto pequeño de páginas; reportes exclusivamente en la PC.
"""
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import URLError,HTTPError
from urllib.parse import urlsplit
from urllib.request import Request,urlopen
from urllib.robotparser import RobotFileParser
import json,sys,time
MOD=Path(__file__).resolve().parent
BASE='https://appinitdev.com'
PAGES=['/','/ia/','/ia/identidad/','/ia/fuentes-oficiales/','/ia/catalogo/','/mcp/','/mcp/tutoriales/','/sitemap-ia.xml','/datos/apps.json']
AGENTS=['Googlebot','Bingbot','OAI-SearchBot','Claude-SearchBot']

def main():
    print('Solo lectura: robots.txt + 9 URLs. La disponibilidad de cada rastreador se verifica además en el servidor/CDN.')
    text='';rows=[]
    try:
        req=Request(BASE+'/robots.txt',headers={'User-Agent':'AppInitDevSiteQA/4.0'})
        with urlopen(req,timeout=8) as r:text=r.read(100_000).decode('utf8',errors='replace');print('robots.txt HTTP',r.status)
    except (HTTPError,URLError,TimeoutError,OSError) as e:
        print('No fue posible obtener robots.txt:',type(e).__name__)
    rp=RobotFileParser();rp.parse(text.splitlines())
    permissions={agent:{path:rp.can_fetch(agent,BASE+path) if text else 'sin_comprobar' for path in ('/ia/','/mcp/','/ia/fuentes-oficiales/')} for agent in AGENTS}
    for path in PAGES:
        u=BASE+path;row={'url':u,'http':None,'correcto':False}
        try:
            req=Request(u,headers={'User-Agent':'AppInitDevSiteQA/4.0','Accept':'text/html,application/json,application/xml,text/xml'})
            with urlopen(req,timeout=7) as r:
                content_type=r.headers.get('Content-Type','')
                row.update({'http':r.status,'url_final':r.geturl(),'content_type':content_type,
                            'x_robots_tag':r.headers.get('X-Robots-Tag'),
                            'correcto':r.status==200 and urlsplit(r.geturl()).hostname=='appinitdev.com'})
                if content_type.lower().startswith('text/html'):
                    head=r.read(120_000).decode('utf8',errors='replace').lower()
                    row['canonical_detectada']='rel="canonical"' in head or "rel='canonical'" in head
        except (HTTPError,URLError,TimeoutError,OSError) as e:
            row['error']=type(e).__name__;row['http']=getattr(e,'code',None)
        print('OK' if row['correcto'] else 'REVISAR',row['http'],path)
        rows.append(row);time.sleep(.1)
    report={'fecha_utc':datetime.now(timezone.utc).isoformat(),'notas':['Permiso robots.txt no garantiza indexación, acceso de un bot real ni citas en IA.','El User-Agent de diagnóstico no suplanta a los bots externos.','Un HTTP no exitoso puede deberse a conectividad temporal.'],'robots_permisos_teoricos':permissions,'paginas':rows}
    out=MOD/'reportes/auditoria_rastreo_remoto_privada.json';out.parent.mkdir(exist_ok=True)
    out.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf8')
    print('Reporte privado:',out)
    return 0 if all(r['correcto'] for r in rows) else 1
if __name__=='__main__':sys.exit(main())