Exemplo n.º 1
0
def get_location_data():
    """
    Gets location data using current IP address from ipdata.

    Parameters:
    -----------
    None

    Returns:
    --------
    dictionary: A dictionary of location data from the ipinfo request. Keys include
        'city', 'country_name', 'latitude', 'longitude', 'postal', 'region', 'timezone', and 'timestamp'.
        Any entry that was not included is replaced with an empty string.
    """
    try:
        public_ip = requests.get("http://ip.42.pl/raw").text
        ipd = ipdata.IPData(config.ipdata_api_key)
        response = ipd.lookup(public_ip)
        keys = [
            "city", "country_name", "latitude", "longitude", "postal", "region"
        ]
        location_data = {}
        for key in keys:
            location_data[key] = response.get(key, "")
        location_data["time zone"] = response["time_zone"]["name"]
        location_data["timestamp"] = response["time_zone"]["current_time"]
        return location_data
    except Exception as e:
        print("Failed to get location:", e)
        return {}
Exemplo n.º 2
0
def whois(event, context):
   
    records = event['Records'] or []
    
    for r in records:
      # ignore all events except insert
      if r.get('eventName') != 'INSERT':
        continue
      
      #format record
      dynamodb = parse_dynamo_item(r['dynamodb']['NewImage']) 
      ip = dynamodb['ip']

      #lookup in ipTable if we already have the data
      ip_data = get_ip(ip)
      
      # fetch from ipdata API if not
      if not ip_data:
        ipdata_client = ipdata.IPData(IPDATA_API_KEY)
        ip_data = ipdata_client.lookup(
            ip, fields=['ip', 'asn', 'country_name', 'city'])
        
        save_ip(ip, ip_data)

      # update tracking event
      name = ip_data['name']
      industry = ip_data['type']
      city = ip_data['city']
      country = ip_data['country']
      update_tracking_event(event=dynamodb, name=name, industry=industry, city=city, country=country)
Exemplo n.º 3
0
    def client(self) -> IPData:
        """
        Return instantiated IP Data client.

        :returns: IPData
        """
        try:
            return ipdata.IPData(self.api_key)
        except APIKeyNotSet as e:
            raise APIKeyNotSet(e)
Exemplo n.º 4
0
def get_location():
    """Function to returns location data using IP."""
    response = None
    try:
        ip = ipdata.IPData(config('IPDATA_KEY'))
        response = ip.lookup(fields=[
            'country_name', 'latitude', 'flag', 'region', 'city', 'longitude'
        ])
    except ConnectionError:
        pass
    return response
Exemplo n.º 5
0
def get_geolocation(client_ip):
    """Getting user geolocation.

    :param client_ip: User ip address.
    :return: User geolocation.
    """
    try:
        ipdata_ = ipdata.IPData(settings.IPDATA_TOKEN)
        geolocation = ipdata_.lookup(
            client_ip,
            fields=['continent_name', 'country_name', 'city', 'region'])
    except:
        response = None
    else:
        response = ', '.join(
            [v for k, v in geolocation.items() if type(v) == str])
    return response
Exemplo n.º 6
0
def fetch_country_by_ip(ip):
    """
    Fetches country code by IP

    Returns empty string if the request fails in non-200 code.

    Uses the ipdata.co service which has the following rules:

    * Max 1500 requests per day

    See: https://ipdata.co/docs.html#python-library
    """
    iplookup = ipdata.IPData()
    data = iplookup.lookup(ip)
    if data.get('status') != 200:
        return ''

    return data.get('response', {}).get('country_code', '')
Exemplo n.º 7
0
    def get_ip_info(self):
        try:
            url = "https://ipapi.co/ip/"
            ip = self.get_global_ip(url)
            #print(ip)
            if ip == "":
                return None
            ipdata1 = ipdata.IPData('test')
            response = ipdata1.lookup(ip,
                                      fields=[
                                          'asn', 'city', 'continent_name',
                                          'country_name', 'latitude',
                                          'longitude', 'organisation',
                                          'postal', 'region', 'carrier'
                                      ])
            #print(response)
            if response['status'] is 200:
                ip_details = Ip_info()
                ip_details.status = internet()
                ip_details.asn = response['asn']
                ip_details.city = response['city']
                ip_details.continent_name = response['continent_name']
                ip_details.country_name = response['country_name']
                ip_details.latitude = response['latitude']
                ip_details.longitude = response['longitude']
                ip_details.organisation = response['organisation']
                ip_details.postal = response['postal']
                ip_details.region = response['region']
                if response['carrier'] is not None:
                    ip_details.carrier_name = response['carrier']['name']
                else:
                    ip_details.carrier_name = 'NA'
                return ip_details

            return None
        except:
            return None
Exemplo n.º 8
0
#!/usr/bin/env python

from ipdata import ipdata
from pprint import pprint

f = open('/home/cam/projects/project_secrets/geo.key', 'r')
#print(f) # debugging#don't print API keys
apiKey = f.readline().strip() # strips away \n at EOL
ipdata = ipdata.IPData(apiKey) # api key goes here

# gonna do this manually to get everything online
ipAsk = input("Enter IP Address: ")
#ipdata = ipdata.IPData('') #api key

response = ipdata.lookup(ipAsk) #ip address - this will be !manual later
#pprint(response)
with open(
Exemplo n.º 9
0
from ipdata import ipdata
from pprint import pprint
#
# Create an instance of an ipdata object. Replace `test` with your API Key
token = 'your token key'
ipdata = ipdata.IPData(token)
ips = [
    '106.13.182.60',
    # '49.234.10.207',
    #   '120.31.138.70',
    #    '112.85.42.185',
    #    '157.230.47.57',
    #    '119.57.120.107',
    #    '113.108.168.215',
    #    '120.98.1.180',
    #    '83.56.44.200',
    #    '119.226.11.100',
    #    '104.248.246.8',
    '37.213.204.135'
]
l = []
for i in ips:

    response = ipdata.lookup(i,
                             fields=[
                                 'ip', 'asn', 'calling_code', 'city',
                                 'continent_code', 'continent_name',
                                 'country_code', 'country_name', 'is_eu',
                                 'latitude', 'longitude', 'postal', 'region',
                                 'region_code', 'status', 'threat'
                             ])
Exemplo n.º 10
0
                st.error("Exceeded daily Limit. please wait 24 hrs or visit emailrep.io/key for an api key")
            elif len(email_input) == 0:
                pass
        except (KeyError,NameError):
            st.error("Invalid Email, Check Email Again")
        except (ConnectionError):
            dv.svg_assets(image="Assets/404.svg")
            dv.page_404()

    # IP 
    if tools_choice == "IP":        
        # IP API endpoint - http://api.cybercure.ai/feed/search?value=
        try:
            ip_input = st.text_input('Input IP Address',)
            # Create an instance of an ipdata object. Replace "config.ip_api_key" with your API Key
            ipdata = ipdata.IPData(ip_secret)
            ip_response = ipdata.lookup("{}".format(ip_input.lstrip()))
            # drawing IP locality map. Append Lat and Lon values to empty list
            geo_loc= [ip_response.get("latitude"),ip_response.get("longitude"),ip_response.get("country_name"),ip_response.get("city")]
            # verify from nested dictionary, to be included in "is_Threat" column in table 
            is_threat = ip_response["threat"]["is_known_attacker"]
            # 0 = Harmless , 1= Harmful        
            if is_threat == 0:
                geo_loc.append("No Threat Detected")
            else:
                geo_loc.append("Threat Detected")
                
            # draw table with column names and values
            ip_map = [geo_loc[0], geo_loc[1], geo_loc[2], geo_loc[3], geo_loc[4]]  
            if len(ip_input) == 0:
                pass 
Exemplo n.º 11
0
#!/usr/bin/env python

from ipdata import ipdata
from pprint import pprint
with open('../../secrets/geo.key') as key:
    key.readline().strip()
    ipdata = ipdata.IPData(key)
    ipinput = raw_input("Enter IP address: ")
    response = ipdata.lookup(ipinput)
Exemplo n.º 12
0
 def client(self) -> IPData:
     try:
         return ipdata.IPData(self.api_key)
     except APIKeyNotSet as e:
         raise APIKeyNotSet(e)
from ipdata import ipdata  # Ipdata api to look up IPGeo Data
from flask import request
import json

# get API keys for twilio from enviorment variable
account_sid = os.environ['twilio_account_sid']
auth_token = os.environ['twilio_auth_token']

# get API key for ipdata from environment variable
ipdata_key = os.environ['ipdata_api_key']

# Create an instance of an twilio client object.
Client = Client(account_sid, auth_token)

# Create an instance of an ipdata object.
ipdata = ipdata.IPData(ipdata_key)


class sendtext(MethodView):
    def post(self, id):
        """
        Accepts POST requests, and processes the form;
        Redirect to index when completed.
        id: Tagid of bag sent from sendText button
        It will lookup Client's IP and tracke GeoIP location, send message to registered user with IP GeoLocationa and TagID.
        """
        # Get Client/visitor's IP.
        if request.headers.getlist("X-Forwarded-For"):
            ip = request.headers.getlist("X-Forwarded-For")[0]
        else:
            ip = request.remote_addr
Exemplo n.º 14
0
async def spy(event):
    "To see details of an ip."
    inpt = event.pattern_match.group(1)
    if not inpt:
        return await edit_delete(event, "**Give an ip address to lookup...**", 20)
    check = "" if inpt == "mine" else inpt
    try:
        pussy = ipdata.IPData(Config.IPDATA_API)
    except APIKeyNotSet:
        return await edit_delete(
            event,
            "**Get an API key from [Ipdata](https://dashboard.ipdata.co/sign-up.html) & set that in heroku var `IPDATA_API`**",
            80,
        )
    r = pussy.lookup(check)
    if r["status"] == 200:
        await edit_or_reply(event, "� **Searching...**")
    else:
        return await edit_delete(event, f"**{r['message']}**", 80)
    ip = r["ip"]
    city = r["city"]
    postal = r["postal"]
    region = r["region"]
    latitude = r["latitude"]
    carrier = r["asn"]["name"]
    longitude = r["longitude"]
    country = r["country_name"]
    carriel = r["asn"]["domain"]
    region_code = r["region_code"]
    continent = r["continent_name"]
    time_z = r["time_zone"]["abbr"]
    currcode = r["currency"]["code"]
    calling_code = r["calling_code"]
    country_code = r["country_code"]
    currency = r["currency"]["name"]
    lang1 = r["languages"][0]["name"]
    time_zone = r["time_zone"]["name"]
    emoji_unicode = r["emoji_unicode"]
    continent_code = r["continent_code"]
    native = r["languages"][0]["native"]
    current_time = r["time_zone"]["current_time"]

    language1 = (
        f"<code>{lang1}</code>"
        if lang1 == native
        else f"<code>{lang1}</code> [<code>{native}</code>]"
    )

    try:
        lang2 = f', <code>{r["languages"][1]["name"]}</code>'
    except:
        lang2 = ""

    b = emoji_unicode.replace("+", "000").replace(" ", "").replace("U", "\\U")
    t = b.encode("ascii", "namereplace")
    emoji = t.decode("unicode-escape")

    string = f"✘ <b>Lookup For Ip : {ip}</b> {emoji}\n\n\
    <b>• City Name :</b>  <code>{city}</code>\n\
    <b>• Region Name :</b>  <code>{region}</code> [<code>{region_code}</code>]\n\
    <b>• Country Name :</b>  <code>{country}</code> [<code>{country_code}</code>]\n\
    <b>• Continent Name :</b>  <code>{continent}</code> [<code>{continent_code}</code>]\n\
    <b>• View on Map :  <a href = https://www.google.com/maps/search/?api=1&query={latitude}%2C{longitude}>Google Map</a></b>\n\
    <b>• Postal Code :</b> <code>{postal}</code>\n\
    <b>• Caller Code :</b>  <code>+{calling_code}</code>\n\
    <b>• Carrier Detail :  <a href = https://www.{carriel}>{' '.join(carrier.split()[:2])}</a></b>\n\
    <b>• Language :</b>  {language1} {lang2}\n\
    <b>• Currency :</b>  <code>{currency}</code> [<code>{currcode}</code>]\n\
    <b>• Time Zone :</b> <code>{time_zone}</code> [<code>{time_z}</code>]\n\
    <b>• Time :</b> <code>{current_time[11:16]}</code>\n\
    <b>• Date :</b> <code>{current_time[:10]}</code>\n\
    <b>• Time Offset :</b> <code>{current_time[-6:]}</code>"
    await edit_or_reply(event, string, parse_mode="html")