1º Descargar el mapa de Rusia de https://download.geofabrik.de/russia-latest.osm.pbf

2º Tener osmium instalado

3º osmium tags-filter russia-latest.osm.pbf w/landuse=military -o zonas_militares_ru.osm

- Si se abre con josm zonas_militares_ru.osm se puede ver el mapa

"""
MIT License
 
Copyright (c) 2024 foro.acosadores.net
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
 
import osmium
 
class WayHandler(osmium.SimpleHandler):
    def __init__(self):
        super().__init__()
        self.nodes = {}  # Para almacenar nodos (id -> (lat, lon))
        self.results = []  # Para almacenar resultados por polígono
 
    def node(self, n):
        """Guarda las coordenadas de los nodos"""
        self.nodes[n.id] = (n.location.lat, n.location.lon)
 
    def way(self, w):
        """Procesa cada 'way' y calcula coordenadas mínimas/máximas"""
        latitudes = []
        longitudes = []
 
        for node_ref in w.nodes:
            node_id = node_ref.ref
            if node_id in self.nodes:
                lat, lon = self.nodes[node_id]
                latitudes.append(lat)
                longitudes.append(lon)
 
        # Si se han encontrado coordenadas, calcular los límites y el punto central
        if latitudes and longitudes:
            min_lat = min(latitudes)
            max_lat = max(latitudes)
            min_lon = min(longitudes)
            max_lon = max(longitudes)
            central_lat = (min_lat + max_lat) / 2
            central_lon = (min_lon + max_lon) / 2
 
            self.results.append({
                "min_lat": min_lat,
                "max_lat": max_lat,
                "min_lon": min_lon,
                "max_lon": max_lon,
                "central": (central_lat, central_lon),
            })
 
def process_osm_file(filename):
    handler = WayHandler()
    handler.apply_file(filename)
 
 
    """
    for i, result in enumerate(handler.results, start=1):
        print(f"Polígono {i}:")
        print(f"  Latitud mínima: {result['min_lat']}")
        print(f"  Latitud máxima: {result['max_lat']}")
        print(f"  Longitud mínima: {result['min_lon']}")
        print(f"  Longitud máxima: {result['max_lon']}")
        print(f"  Punto central (Lat, Lon): {result['central']}")
        print()
        """
    # Mostrar coordenadas de todos los polígonos
    for i, result in enumerate(handler.results, start=1):
      print(f"{result['min_lat']},{result['max_lat']},{result['min_lon']},{result['max_lon']}")
 
# Procesar archivo OSM
input_file = "zonas_militares_ru.osm"
process_osm_file(input_file)

4º Probar el script

python3 coordenadas_zonas_militares.py (devuelve 5655)

62.3405412,62.3419357,31.0057032,31.008997
61.9025887,61.9029355,30.2988566,30.29966
62.1079319,62.1088278,30.5883622,30.590846
62.0719505,62.074694,30.5629992,30.5678916
61.781464,61.7837366,30.1511192,30.1540697
63.3908346,63.3939676,31.2762523,31.2840199
63.3074205,63.3101578,31.0867703,31.0906112
63.3052372,63.3068662,31.0863519,31.090107

……………

lo sabemos con: python3 coordenadas_zonas_militares.py | wc -l

5º python3 coordenadas_zonas_militares.py > areas_ru.txt

"""
MIT License
 
Copyright (c) 2024 foro.acosadores.net
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
 
import ipaddress
import geoip2.database
 
def load_areas(file_path):
    """Carga las áreas desde un archivo en formato lat_min,lat_max,lon_min,lon_max"""
    areas = []
    with open(file_path, 'r') as f:
        for i, line in enumerate(f):
            coords = line.strip().split(',')
            if len(coords) == 4:
                areas.append({
                    "lat_min": float(coords[0]),
                    "lat_max": float(coords[1]),
                    "lon_min": float(coords[2]),
                    "lon_max": float(coords[3]),
                    "output_file": f"area_{i+1}.txt"  # Genera un nombre de archivo único
                })
    return areas
 
# Cargar las áreas desde el archivo
areas = load_areas("areas_ru.txt")
 
# Ruta a la base de datos GeoLite2
geoip_db_path = 'GeoLite2-City.mmdb'
 
def get_coordinates(ip):
    """Obtiene las coordenadas de una IP usando GeoLite2"""
    try:
        reader = geoip2.database.Reader(geoip_db_path)
        response = reader.city(ip)
        lat = response.location.latitude
        lon = response.location.longitude
        return lat, lon
    except geoip2.errors.AddressNotFoundError:
        print(f"IP {ip} no encontrada en la base de datos GeoLite2.")
        return None, None
    except Exception as e:
        print(f"Error al obtener coordenadas para IP {ip}: {e}")
        return None, None
 
 
def check_area(lat, lon, areas):
    """
    Verifica si las coordenadas están dentro de alguna de las áreas definidas.
    """
    for area in areas:
        if (area["lat_min"] <= lat <= area["lat_max"] and
                area["lon_min"] <= lon <= area["lon_max"]):
            return True, area  # Devuelve True y el área si coincide
    return False, None  # Devuelve False si no coincide con ninguna área
def process_cidr_blocks(ip_blocks_file):
    """Procesa el archivo con bloques CIDR"""
    with open(ip_blocks_file, 'r') as file:
        for line in file:
            cidr = line.strip()
            print(f"Procesando bloque: {cidr}")
            # Procesar cada IP en el bloque CIDR
            network = ipaddress.IPv4Network(cidr)
            for ip in network.hosts():
                lat, lon = get_coordinates(str(ip))
                if lat is not None and lon is not None:
                    is_in_area, area = check_area(lat, lon,areas)
                    if is_in_area:
                        print(f"IP {ip} está dentro del área {area}.")
# Ejecutar el procesamiento de bloques CIDR
process_cidr_blocks('ru-aggregated.zone')

6- wget https://www.ipdeny.com/ipblocks/data/agg...gated.zone

7- python3 geoip_check_with_cidr.py > ips_zonas_militares.txt

Una vez terminado el proceso, que tardará varios días o una semana (adjunto abajo el fichero en el tar.gz) obtenemos el fichero, sabemos que de las 5 mil y pico zonas militares sólo ha encontrado ips de 6 zonas militares mediante éste comando

cat ips_militares.txt | grep -oE 'area.*.txt' | uniq

area_419.txt
area_3239.txt
area_4384.txt
area_3239.txt
area_1031.txt
area_3239.txt

si lo que queremos es hacer un escaner a todas las ips de esas 6 zonas militares primero hay que crear un archivo que contenga únicamente las ips:

cat ips_militares.txt | grep -E 'dentro.*.txt' | grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' > areas_con_ips.txt

ips_zonas_militares_ru.tar.gz