Exemple #1
0
    def whois_ip(self):
        handler = ipinfo.getHandler(self.token())
        handler = ipinfo.getHandler(self.token())
        details = handler.getDetails(self.ip)
        x_details = details.all
        for key, value in x_details.items():
            if type(value) is dict:
                for k, v in value.items():
                    print(Fore.GREEN + k + Fore.RED + " : ", Fore.CYAN + v)
                    time.sleep(0.1)
            else:
                print(Fore.GREEN + key + Fore.RED + " : ", Fore.CYAN + value)
                time.sleep(0.1)
        try:
            a = details.latitude
            b = details.longitude
            map_1 = "https://www.google.com/maps/place/" + a + b + "/@" + a + "," + b
        except:
            pass

        count = 0
        your_ip = None
        while count < 12 and not your_ip:
            count += 1
            try:
                r = requests.post("https://cleanuri.com/api/v1/shorten",
                                  data={"url": map_1})
                map = r.json()['result_url']
                print(Fore.GREEN + "Google Map location : " + Fore.CYAN + map)
                break
            except:
                print(Fore.RED +
                      "[*] Not Found Google Map location Pleaas Waiting ")
Exemple #2
0
def weather():
    access_token = #####
    handler = ipinfo.getHandler(access_token)
    details = handler.getDetails()
    location = details.loc
    weather = Analysis.dark_sky_API((location))
    return weather
Exemple #3
0
def data():
    ip = request.remote_addr
    latencydata = json.loads(request.data)
    access_token = 'cf55ec4dfcbb19'
    handler = ipinfo.getHandler(access_token)
    details = handler.getDetails(ip)
    userdata = details.all
    userdata.update(latencydata)
    userdata['time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(userdata)

    dynamodb = boto3.resource('dynamodb', region_name='ap-southeast-1')
    table = dynamodb.Table('latency')
    response = table.put_item(
        Item={
            'id': str(uuid.uuid1()),
            'ip': userdata['ip'],
            'time': userdata['time'],
            'city': userdata['city'],
            'latencyType': userdata['latencyType'],
            'latency': userdata['latency'],
            'org': userdata['org'],
            'country_name': userdata['country_name'],
            'region': userdata['region']
        })
    return 'send data success'
Exemple #4
0
def get_location():
    global cached_location
    if not (cached_location is None):
        return cached_location
    handler = ipinfo.getHandler(IPINFOIO_ACCESS_TOKEN)
    cached_location = handler.getDetails()
    return cached_location
Exemple #5
0
def page_first():
    st.title("This is my first page")
    # ...

    session_state = get(remote_ip='', favorite_color='black')
    sessions = Server.get_current()._session_info_by_id
    session_id_key = list(sessions.keys())[0]
    session = sessions[session_id_key]

    # Default IP
    ip = '123.59.195.125'
    access_token = '32954095c41f7b'
    handler = ipinfo.getHandler(access_token)
    ip_address = ip
    details = handler.getDetails(ip_address)
    st.write(details.all)

    street = st.sidebar.text_input("Street", '1')
    city = st.sidebar.text_input("City", details.city)
    province = st.sidebar.text_input("Province", details.region)
    country = st.sidebar.text_input("Country", details.country_name)

    lat = float(details.latitude)
    lon = float(details.longitude)

    st.write('lat: ' + str(lat))
    st.write('lon: ' + str(lon))

    map_data = pd.DataFrame({'lat': [lat], 'lon': [lon]})

    # st.map(map_data)
    st.map(map_data, zoom=12)
Exemple #6
0
def ipi():  # Defines ip info command
    keys_file = open("keys.txt")
    read = keys_file.readlines()
    access_token = read[0].rstrip()
    handler = ipinfo.getHandler(access_token)
    ip_address = Console().input("[bold blue]Enter an IP: [/bold blue]")
    details = handler.getDetails(ip_address)
    ip = details.ip
    city = details.city
    region = details.region
    country = details.country_name
    try:
        hn = details.hostname
        org = details.org
    except AttributeError:
        hn = "No Hostname found for requested IP "
        org = "No Organization found for requested IP"
    Console().print("[red3] INFO FOR [/red3]", ip)
    Console().print(
        "[red3] Location :arrow_forward:  :arrow_forward:  :arrow_forward:  :arrow_forward: [/red3] ",
        city +
        "," +
        region +
        country)
    Console().print(
        "[red3] Hostname :arrow_forward:  :arrow_forward:  :arrow_forward:  :arrow_forward: [/red3] ",
        hn)
    Console().print(
        "[red3] Organization :arrow_forward:  :arrow_forward:  :arrow_forward:  :arrow_forward: [/red3] ",
        org)
    Console().print(
        "[red3] Ping :arrow_forward:  :arrow_forward:  :arrow_forward:  :arrow_forward: [/red3] ")
Exemple #7
0
def IP_geo(self):
    import definitico
    file = path.exists('Temporary/results.txt')
    if file == True:
        os.remove('Temporary/results.txt')
    else:
        pass
    try:

        getvar = self.Type_an_IP_Address_radar.text()

        # codice per il servizio di geolocalizzazione IP
        acces_token = '1d920b86e75c6e'

        handler = ipinfo.getHandler(acces_token)  # DATI
        details = handler.getDetails(getvar)  # GEOLOCALIZZAZIONE
        self.details2 = json.dumps(details.all)

        self.output_radar.setText(self.details2)

        f = open("Temporary/results.txt", "a")
        f.write(str(self.details2))

    except requests.exceptions.HTTPError:

        self.output_radar.setText("requests.exceptions.HTTPError:")
        pass
Exemple #8
0
def download(request, slug):

    slices = int(slug[8:])
    type_ = request.GET.get('type')
    status_id = PromotionStatus.objects.get(id=slices)
    status_id.status = "visited"
    status_id.save()
    handler = ipinfo.getHandler(access_token)
    # details = handler.getDetails(request.META.get('REMOTE_ADDR'))
    details = handler.getDetails()

    user = UserStatus(
        promotion=status_id,
        status=status_id.status,
        ip_address=request.META.get('REMOTE_ADDR'),
        user_os=request.META.get('HTTP_USER_AGENT'),
    )
    visited_info = json.dumps(details.all)

    user.visited_info = json.dumps(details.all)

    if type_ == 'web':
        user.request_type = 'web'
        link = status_id.promotion.templates.link
    elif type_ == 'ios':
        user.request_type = 'ios'
        link = status_id.promotion.templates.ios_link
    elif type_ == 'apk':
        user.request_type = 'apk'
        link = status_id.promotion.templates.apk_link
    if "google-proxy" not in visited_info:
        user.save()
    return HttpResponseRedirect(link)
Exemple #9
0
def ipi():  # Defines ip info command
    console = Console()
    keys_file = open("keys.txt")
    read = keys_file.readlines()
    access_token = read[0].rstrip()
    handler = ipinfo.getHandler(access_token)
    ip_address = console.input("[bold blue]Enter an IP: [/bold blue]")
    details = handler.getDetails(ip_address)
    ip = details.ip
    city = details.city
    region = details.region
    country = details.country_name
    ping = subprocess.check_output("ping -c 4 " + ip_address, shell=True)
    ping_out = ping.decode()
    try:
        hn = details.hostname
        org = details.org
    except AttributeError:
        hn = "No Hostname found for requested IP "
        org = "No Organization found for requested IP"

    @render_group()
    def get_panels():
        yield Panel(
            city + "," + region + " " + country,
            style="black on spring_green2",
            title="Location",
        )
        yield Panel(org, style="black on spring_green1", title="Organization")
        yield Panel(hn,
                    style="black on medium_spring_green",
                    title="Hostnmame")
        yield Panel(ping_out, style="black on cyan2", title="Ping")

    rich.print(Panel(get_panels(), title="INFO FOR " + ip))
Exemple #10
0
def fill_location_data(grouped, color):
    data = pd.DataFrame(
        columns=['ip', 'latitude', 'longitude', 'country', 'size', 'color'])
    not_located = list()
    access_token = 'd172b1fedf7feb'  # token used to get access to ipinfo tool
    handler = ipinfo.getHandler(access_token)
    for ip, group in grouped:
        try:
            details = handler.getDetails(ip)
        except:
            not_located.append(ip)
            continue
        location = details.loc.split(',')
        if location[0] or location[1]:
            data = data.append(pd.DataFrame({
                'ip': ip,
                'latitude': [float(location[0])],
                'longitude': [float(location[1])],
                'country': details.country,
                'size': group.shape[0],
                'color': color
            }),
                               ignore_index=True)
        else:
            not_located.append(ip)
    return [data, not_located]
Exemple #11
0
def ip_info_handler(ip_address):
    try:
        api_key = Configuration.objects.get(code_name='ip_info_io').api_key
        return getHandler(api_key).getDetails(ip_address)
    except (HTTPError, Exception) as error:
        logging.error(error)
        raise HTTPError(error)
def selftest_function(opts):
    """
    Placeholder for selftest function. An example use would be to test package api connectivity.
    Suggested return values are be unimplemented, success, or failure.
    """

    options = opts.get("fn_ipinfo", {})

    access_token = get_config_option("ipinfo_access_token", options)

    LOG.info("Gathered IP Info Access token")
    # Setup the IpInfo API Class
    ipinfo_handler = ipinfo.getHandler(access_token)
    details = None
    try:
        LOG.info("Sending query to IpInfo")
        # Submit query for Google DNS as a test
        details = ipinfo_handler.getDetails('8.8.8.8')

    except Exception as e:
        LOG.error(e)
        if '401 ' in e.args[0]:
            return {"state": "failed",
                    "reason": "Got a 401 error"}
        else:
            return {"state": "failed",
                    "reason": "Encountered an exception {0}".format(e.args[0])}

    # Will fail if we didn't get anything from IP Info
    if details:
        # details.all is what is accessed by the function code. A check to ensure it exists also
        if details.all:
            return {"state": "success"}
Exemple #13
0
def surroundCurrent(distance="0.04"):
    """
    This function works a bit differently than the other two crime functions as it uses the users current location
    """
    key = getKey("ipInfo")

    handler = ipinfo.getHandler(key)
    details = handler.getDetails()

    # This block returns returns the current latitude and longitude
    coords = details.loc.split(",")
    lat, lon = coords[0], coords[1]
    CURR_COORDS = (lat, lon)

    # The rest of the function works the same as the other two
    url = f"https://api.spotcrime.com/crimes.json"
    key = getKey("spotCrime")
    params = {"lat": lat,
              "lon": lon,
              "radius": distance,
              "callback": "jQuery213008995550240819228_1593813722897",
              "key": key}

    response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, params=params)
    data = response.text

    p = data.index("(")
    data = data[p + 1:-1]
    d = json.loads(data)

    CURR_COORDS = (lat, lon)

    return d, CURR_COORDS
def get_country_region(ips):

    print('api call')
    
    for ip in ips:
        retries = 0
        while True:
            try:

                access_token = ipinfo_token
                handler = ipinfo.getHandler(access_token)
                details = handler.getDetails(ip)
                ipDetail = {
                    "country" : details.country,
                    "region" : details.region,
                    "ip" : ip
                }
                return ipDetail

            except AttributeError as e:
                print(f"{serverName} - Export Attribute error : {repr(e)}\nIP : {ip}",alert=True)
                sleep(5)
                break

            except Exception as e:
                if (retries := retries+1) == 4:
                    break

                print('{} - Export Exception : {}'.format(serverName,repr(e)),alert=True)
                sleep(5)
Exemple #15
0
def get_ip_details(ip_address=None):
    """Get location based information from IP Address."""
    ip_info_token = getattr(settings, "IPINFO_TOKEN", None)
    ip_info_settings = getattr(settings, "IPINFO_SETTINGS", {})
    ip_data = ipinfo.getHandler(ip_info_token,
                                **ip_info_settings).getDetails(ip_address)
    return ip_data
Exemple #16
0
    async def ipinfo(self, ctx, IpAddr):

        await self.bot.change_presence(activity=discord.Game(name="IpInfo"))

        if not valid_ip(IpAddr):
            await ctx.send("L'adresse IP n'est pas valid")
        else:
            IPINFO_TOKEN = os.getenv("IPINFO_TOKEN")
            handler = ipinfo.getHandler(access_token=IPINFO_TOKEN)
            details = handler.getDetails(IpAddr)

            ipInfoEmbed = discord.Embed(title="Ip info",
                                        color=0x78a5f9,
                                        description=f"Résultat de la commande IpInfo avec `{IpAddr}`")

            ipInfoEmbed.add_field(name="Hostname : ",
                                  value=details.hostname,
                                  inline=False)

            ipInfoEmbed.add_field(name="Compagnie : ",
                                  value=details.org,
                                  inline=False)

            ipInfoEmbed.add_field(name="Localisation : ",
                                  value=f"Pays : {details.country_name} \n"
                                        f"Region : {details.region} \n"
                                        f"Ville : {details.city} \n"
                                        f"Code postal : {details.postal} \n"
                                        f"Coordonées : {details.latitude}, {details.longitude} \n"
                                        f"Timezone : {details.timezone}")

            await ctx.send(embed=ipInfoEmbed)
Exemple #17
0
def maps(request):

    # This will parse the IP to remove the colon and everything after it.
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')

    # Remove everything after colon.
    parsed_ip = ip[:ip.find(":")]

    # Use API with get function.
    #my_ip = get('https://api.ipify.org').text
    access_token = '6d22498aabaf10'
    # Get lat and long.
    handler = ipinfo.getHandler(access_token)
    details = handler.getDetails(parsed_ip)

    # Send to template through context.
    loc_context = {
        "latitude": details.latitude,
        "longitude": details.longitude
    }

    return render(request, 'trackerPage/maps.html', loc_context)
Exemple #18
0
    def has_permission(self, request, view):
        try:
            # If there is no whitelist, skip
            if not CountryWhiteList.objects.count():
                return True

            ip_data = ipinfo.getHandler().getDetails(get_client_ip(request))
            ip_bogon = ip_data.details.get('bogon')

            if ip_bogon:
                return True

            ip_country = ip_data.details.get('country')
            if not ip_country:
                return False

            allowed_countries = [
                country.lower() for country in CountryWhiteList.objects.all().values_list('country', flat=True)
            ]

            if ip_country.lower() in allowed_countries:
                return True

            log = BlockedLog(
                ip=ip_data.details.get('ip'),
                city=ip_data.details.get('city'),
                country=ip_data.details.get('country'),
            )
            log.save()
        except Exception:
            logger.exception("Failed to geolocate IP")

        return False
def sendRequest(constellationSelect, requestHandlerHost):
    returnVal = None
    url = "http://" + requestHandlerHost + "/constellationRequest/"
    print(url)
    handler = ipinfo.getHandler()
    userDetails = handler.getDetails()
    lat = "%s N" % userDetails.latitude
    longitude = "%s W" % userDetails.longitude
    coordinatesSelect = [lat, longitude]

    headers = {'content-type': 'application/json'}
    # send http request with image and receive response
    data = jsonpickle.encode({
        "constellation": constellationSelect,
        "coordinates": coordinatesSelect
    })
    response = requests.post(url, data=data, headers=headers)

    if response.status_code == 200:
        test = json.loads(response.text)
        if test:
            print("There are currently", test["satellite_count"],
                  "satellites of the", constellationSelect,
                  "constellation above the location", coordinatesSelect[0],
                  coordinatesSelect[1])
            print("Overhead Satellites:")
            for satellite in test['satellites']:
                print(satellite)
Exemple #20
0
def IPAddress():
    ipInput = input("Enter IP Address (Ex. 1.1.1.1) > ")
    access_token = # insert your own access token (see ipinfo github)
    handler = ipinfo.getHandler(access_token)
    ip_address = ipInput
    details = handler.getDetails(ip_address)
    pprint(details.all)
Exemple #21
0
def get_ipinfo_data(ips_list, token):
    # this list will store the dictionary for each IP
    ip_info = []
    # this list will store all IPs for which IPinfo does not provide any onfo
    no_info = []

    acc_token = token
    handler = ipinfo.getHandler(token)
    print("[+] Pulling data...")

    for ip in ips_list:
        ip_dictionary = {}

        try:
            details = handler.getDetails(str(ip))
            ip_dictionary['ip'] = ip
            ip_dictionary['hostname'] = details.hostname
            ip_dictionary['city'] = details.city
            ip_dictionary['region'] = details.region
            ip_dictionary['country'] = details.country
            ip_dictionary['location'] = details.loc
            ip_dictionary['organization'] = details.org
            ip_dictionary['postal'] = details.postal
            ip_dictionary['timezone'] = details.timezone
            ip_info.append(ip_dictionary)

        except AttributeError:
            no_info.append(ip)

    print("\n[+] Done!")

    return ip_info, no_info
Exemple #22
0
    def __init__(self, get_response=None):
        """Initializes class while gettings user settings and creating the cache."""
        self.get_response = get_response
        self.filter = getattr(settings, "IPINFO_FILTER", self.is_bot)

        ipinfo_token = getattr(settings, "IPINFO_TOKEN", None)
        ipinfo_settings = getattr(settings, "IPINFO_SETTINGS", {})
        self.ipinfo = ipinfo.getHandler(ipinfo_token, **ipinfo_settings)
def get_country_ipinfo(ips: List[str]) -> dict:
    with open("ipinfo_auth", "r") as f:
        ips = map(lambda x: x + "/country", ips)
        auth_code = f.read().strip()
        handler: ipinfo.Handler = ipinfo.getHandler(auth_code)
        results: dict = handler.getBatchDetails(ips)
        print(".")
        return results
def getIPDetails(IP, *args, **kwargs):

    if IP:
        handler = ipinfo.getHandler(settings.IPINFO_KEY)
        details = handler.getDetails(IP)
        return details
    else:
        return False
Exemple #25
0
def get_location_data():
    """
    Just a simple, quick call to Ipinfo to see where you're at right now,
    using the official Ipinfo python library.
    Details of what's returned are on https://github.com/ipinfo/python.
    """
    handler = ipinfo.getHandler(IPINFO_API_KEY)
    return handler.getDetails()
Exemple #26
0
def ipinfos(ips):
    """Fetches all ipinfo.io details for the passed IPs."""
    dir = Path(__file__).parent
    with open(dir / Path("ipinfo-api-token")) as f:
        access_token = f.read().strip()

    handler = ipinfo.getHandler(access_token)

    return [handler.getDetails(ip).details for ip in ips]
Exemple #27
0
def asnFind(asp):
    access_token = 'ce25dd1fca9a9b'  #9c47a5274b06eb

    handler = ipinfo.getHandler(access_token)
    details = handler.getDetails(asp)
    x = details.org.split(" ")
    x = x[0][2:]
    print(x)
    return x
Exemple #28
0
def get_location(access_token):
    """
    Function for getting current location
    :return: Current location based on IP address
    """
    handler = ipinfo.getHandler(access_token=access_token)
    details = handler.getDetails()

    return details.city
def getloc(ip):
    access_token = '06fa123306e582'
    handler = ipinfo.getHandler(access_token)
    ip_address = ip
    try:
        details = handler.getDetails(ip_address)
        return details.all
    except:
        return {}
Exemple #30
0
def getIPinfo(ip):
    from CTFd.utils import get_config
    import ipinfo
    if get_config('ipinfo_token'):
        handler = ipinfo.getHandler(get_config('ipinfo_token'))
        details = handler.getDetails(ip)
        return details.country_name
    else:
        return "Missing ipinfo token"
Exemple #31
0
def generate_physical(sitelist, switch, outdir):
    """Generates jsonnet files for sites in given sitelist.

    Given sites should be physical machines. Each site is annotated with
    uplink information from given switch configuration data.

    As well, each site is annotated with ASN data from ipinfo.io.
    """
    info = ipinfo.getHandler()
    for site in sitelist:
        v = {}
        lat = site['location']['latitude']
        lon = site['location']['longitude']
        v4 = site['net']['v4']['prefix']
        if site['net']['v6']:
            v6 = site['net']['v6']['prefix']
        else:
            v6 = None
        city_raw = site['location']['city']
        if '_' in city_raw:
            city, state = city_raw.split('_')
        else:
            city = city_raw
            state = ''

        d = info.getDetails(v4)
        if d.org:
            asn, provider = d.org.split(' ', 1)
        else:
            asn = 'AS-unknown'
            provider = 'unknown'

        v['name'] = site['name']
        v['latitude'] = lat
        v['longitude'] = lon
        v['metro'] = site['name'][0:3]
        v['city'] = city
        v['state'] = state
        v['country'] = d.country
        v['continent'] = continent[d.country]
        v['provider'] = provider
        if v['name'] not in switch:
            print 'skipping', v['name']
            continue
        v['uplink'] = switch[v['name']]['uplink_speed']
        v['asn'] = asn
        v['v4'] = v4 + '/26'
        v['v6'] = '\'' + v6 + '/64\'' if v6 else 'null'

        s = physical % v
        print v['name']
        with open('%s/%s.jsonnet' % (outdir, v['name']), 'w') as output:
            output.write(s)
        time.sleep(.2)