def ip_long_lat():  # pega longidute e latitude
    global long
    global lat

    long = str(ipapi.location(None, None, 'longitude'))
    lat = str(ipapi.location(None, None, 'latitude'))
    print(str(long))
    print(str(lat))
Пример #2
0
def IP(ana, IP1, IP2):
    congr = ana['connections']
    countries = ana['countries']
    countryKeys = m.keySet(countries)
    points = ana['points']
    info1 = ipapi.location(IP1)
    hav1 = {'latitude': info1['latitude'], 'longitude': info1['longitude']}
    info2 = ipapi.location(IP2)
    if IP2 == '8.8.8.8':
        lat2 = -122.08286045229197
        lon2 = 37.417661109182816
        hav2 = {'latitude': lat2, 'longitude': lon2}
    else:
        hav2 = {'latitude': info2['latitude'], 'longitude': info2['longitude']}
    vertices = gr.vertices(congr)
    point1 = None
    point2 = None
    menor1 = 9999999999999
    menor2 = 9999999999999
    for i in range(0, lt.size(vertices)):
        vert = lt.getElement(vertices, i)
        code = vert.split('*')[0]
        try:
            int(code)
            lPoint = me.getValue(m.get(points, code))
            dist1 = haversine(hav1, lPoint)
            dist2 = haversine(hav2, lPoint)
            if dist1 < menor1:
                menor1 = dist1
                point1 = vert
            if dist2 < menor2:
                menor2 = dist2
                point2 = vert
        except:
            capital = code
            n = 0
            found = False
            while n < lt.size(countryKeys) and found == False:
                key = lt.getElement(countryKeys, n + 1)
                info = me.getValue(m.get(countries, key))
                Capital = info['CapitalName']
                if capital == Capital:
                    found = True
                    capLat = info['CapitalLatitude']
                    capLon = info['CapitalLongitude']
                    hav = {'latitude': capLat, 'longitude': capLon}
                    dist1 = haversine(hav1, hav)
                    dist2 = haversine(hav2, hav)
                    if dist1 < menor1:
                        menor1 = dist1
                        point1 = vert
                    if dist2 < menor2:
                        menor2 = dist2
                        point2 = vert
                n += 1
    ana['IPs'] = djk.Dijkstra(ana['connections'], point1)
    path = djk.pathTo(ana['IPs'], point2)
    return path, point1, point2
Пример #3
0
def streambyte():
    # your file processing code is here...
    data = []
    ipdata = []

    f = request.form['ipaddress']
    if f == '':
        dataip = ipapi.location(ip='')
    else:
        dataip = ipapi.location(ip=f)

    if 'error' in dataip.keys():
        if (dataip['error'] == True):
            data = [str(dataip['reason'])]
            ipdata.append(data)
    else:
        data = ["IP Address", str(dataip['ip'])]
        ipdata.append(data)
        data = ["Version", str(dataip['version'])]
        ipdata.append(data)
        data = ["City", str(dataip['city'])]
        ipdata.append(data)
        data = ["Region", str(dataip['region'])]
        ipdata.append(data)

        data = [
            "Country",
            str(dataip['country_code']) + " | " + str(dataip['country_name'])
        ]
        ipdata.append(data)
        data = ["Postal", str(dataip['postal'])]
        ipdata.append(data)
        data = ["European Union", str(dataip['in_eu'])]
        ipdata.append(data)
        data = ["Latitude", str(dataip['latitude'])]
        ipdata.append(data)
        data = ["Longitude", str(dataip['longitude'])]
        ipdata.append(data)
        data = [
            "Time Zone ",
            str(dataip['timezone']) + '(' + str(dataip['utc_offset'] + ')')
        ]
        ipdata.append(data)
        data = ["Calling Code", str(dataip['country_calling_code'])]
        ipdata.append(data)
        data = ["Langagues", str(dataip['languages'])]
        ipdata.append(data)
        data = ["ASN", str(dataip['asn'])]
        ipdata.append(data)
        data = ["ISP", str(dataip['org'])]
        ipdata.append(data)
    # your_script_result = 'This variable holds the final data output'
    # your file processing code is here...

    return render_template('index.html', ipdata=ipdata)
Пример #4
0
def finder(request):

    if request.POST.get('search') == get_client_ip(request):
        client_ip = get_client_ip(request)
        data = ipapi.location(ip=client_ip, output="json")

    else:
        search = request.POST.get('search')
        data = ipapi.location(ip=search, output="json")
    
    default_IP = get_client_ip(request)
    context = {"data": data, "ip":default_IP}

    return render(request, 'finder.html', context)
Пример #5
0
def __start__():
    print(Fore.RED + "\n [!] Enter IP Address")
    print(Fore.RED + "\n [/] Or Press The Enter Key :))) \n")

    site = input(Fore.RED + " ┌─[" + Fore.LIGHTGREEN_EX + "inquisitio" +
                 Fore.BLUE + "~" + Fore.WHITE + "@HOME" + Fore.RED + "/" +
                 Fore.CYAN + "IG" + Fore.RED + "/" + Fore.LIGHTYELLOW_EX +
                 "IP-Location" + Fore.RED + """]
 └──╼ """ + Fore.WHITE + "卐 ")
    source = ipapi.location(ip=site, key=None, field=None)
    try:
        print(Fore.GREEN + " [!]" + Fore.RED + " See your info")
        print(Fore.GREEN + " [!]" + Fore.BLUE + " ip = " + source["ip"])
        print(Fore.GREEN + " [!]" + Fore.GREEN + " city = " + source["city"])
        print(Fore.GREEN + " [!]" + Fore.YELLOW + " region = " +
              source["region"])
        print(Fore.GREEN + " [!]" + Fore.MAGENTA + " id country = " +
              source["country"])
        print(Fore.GREEN + " [!]" + Fore.CYAN + " country = " +
              source["country_name"])
        print(Fore.GREEN + " [!]" + Fore.WHITE + " Calling Code = " +
              source["country_calling_code"])
        print(Fore.GREEN + " [!]" + Fore.RED + " Languages = " +
              source["languages"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " org = " + source["org"])
        try:
            input(Fore.RED + " [!] " + Fore.GREEN +
                  "Back To Menu (Press Enter...) ")
        except:
            print("")
            sys.exit()
    except:
        print(Fore.RED + "Sorry, Please Enter an IP Address")
Пример #6
0
def getInfoIP (IPlist,printJson=False):
    "Returns a list with information about public IPs"
    if not isinstance(IPlist, list):
        return []

    infoIPs = []
    for i in IPlist:
        if ipinfo.ispublic(i):
            print('Public IP: %s' % i)
            # search info:
            info = ipapi.location(i)
            if info is not None:
                # process as Address
                jsonarray = json.dumps(info)
                if printJson: pprint(jsonarray)
                a = json.loads(jsonarray, object_hook=eatjson.Address.as_address)

                if isinstance(a, eatjson.Address):
                    infoIPs.append(a)
                    #print(a)
            else:
                print('     (No info)')
        else:
            print('Private IP: %s' % i)

    return infoIPs
Пример #7
0
def __start__():
    print(Fore.YELLOW+"\n [!] IP Location . . . \n")
    print(Fore.RED+" [!] Enter IP Address \n")
    print(Fore.YELLOW+" [!] Press Enter Key For Info Of Ur IP \n")
    print(Fore.RED+" [!] Enter Exit To Go To Main Menu \n")
    site = input(Fore.RED+" ┌─["+Fore.LIGHTGREEN_EX+"HAMMASTER"+Fore.BLUE+"~"+Fore.WHITE+"@HOME"+Fore.RED+"/"+Fore.CYAN+"IG"+Fore.RED+"/"+Fore.LIGHTYELLOW_EX+"IP-Location"+Fore.RED+"""]
 └──╼ """+Fore.WHITE+"卐 ")
    if site == "exit" or site == "Exit" or site == "EXIT":
        try:
            return
        except:
            return
    source = ipapi.location(ip=site, key=None, field=None)
    try:
        print(Fore.GREEN+" [!]"+Fore.RED+" Captured Informations =>")
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" ip = "+ source["ip"])
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" city = " + source["city"])
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" region = "+ source["region"])
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" id country = "+source["country"])
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" country = "+ source["country_name"])
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" Calling Code = "+source["country_calling_code"])
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" Languages = "+source["languages"])
        print (Fore.GREEN+" [!]"+Fore.LIGHTRED_EX+" org = "+ source["org"])
        try:
            input(Fore.RED+" [!] "+Fore.GREEN+" Press Enter To Go Back To Menu ")
        except:
            print("\n sorry, there is a problem")
            time.sleep(2)
            sys.exit()
    except:
        print(Fore.RED+" [!]"+Fore.YELLOW+" Error : No Data Captured")
Пример #8
0
def iplocation():
    print(Fore.RED + "\n [!] Enter IP Address")
    site = input(Fore.RED + " ┌─[" + Fore.LIGHTGREEN_EX + "WEBKILLER" +
                 Fore.BLUE + "~" + Fore.WHITE + "@HOME" + Fore.RED + "/" +
                 Fore.CYAN + "IG" + Fore.RED + "/" + Fore.LIGHTYELLOW_EX +
                 "IP-Location" + Fore.RED + """]
 └──╼ """ + Fore.WHITE + "卐 ")
    source = ipapi.location(ip=site, key=None, field=None)
    try:
        print(Fore.GREEN + " [!]" + Fore.RED + " See your info")
        print(Fore.GREEN + " [!]" + Fore.BLUE + " ip = " + source["ip"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " city = " + source["city"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " region = " +
              source["region"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " id country = " +
              source["country"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " country = " +
              source["country_name"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " Calling Code = " +
              source["country_calling_code"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " Languages = " +
              source["languages"])
        print(Fore.GREEN + " [!]" + Fore.BLUE + " org = " + source["org"])
    except:
        print(Fore.RED + "Sorry Please Enter IP Address")
Пример #9
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))

    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')

        search = request.form.get('search')
        data = ipapi.location(ip=search, output='json')

        if form.entrenador.data == True:
            entrenador = "(entrenador)"
        else:
            entrenador = ""

        user = User(username=form.username.data,
                    email=form.email.data,
                    password=hashed_password,
                    pais=data["continent_code"],
                    lol=form.lol.data,
                    rango_lol=form.rango_lol.data,
                    csgo=form.csgo.data,
                    rango_csgo=form.rango_csgo.data,
                    name_lol=form.name_lol.data,
                    name_csgo=form.name_csgo.data,
                    entrenador=entrenador)
        db.session.add(user)
        db.session.commit()
        flash(
            f'Your account has been created, {form.username.data}. You are now able to log in.',
            'success')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
Пример #10
0
def account():
    current_user.connected_lol = False
    current_user.connected_csgo = False

    form = UpdateAccountForm()
    if form.validate_on_submit():
        if form.picture.data:
            picture_file = save_picture(form.picture.data)
            current_user.image_file = picture_file

        current_user.username = form.username.data
        current_user.email = form.email.data

        db.session.commit()
        flash('Tu cuenta fue actualizada', 'success')
        return redirect(url_for('account'))

    elif request.method == 'GET':
        form.username.data = current_user.username
        form.email.data = current_user.email

    image_file = url_for('static',
                         filename='profile_pics/' + current_user.image_file)
    search = request.form.get('search')
    data = ipapi.location(ip=search, output='json')

    return render_template('account.html',
                           title='Account',
                           data=data,
                           image_file=image_file,
                           form=form)
Пример #11
0
def __start__():
    sleep(0.1)
    print(color.CYAN + "[!] Enter IP Address\n")
    sleep(0.1)
    site = input(color.RED + "┌─[" + color.LIGHTGREEN_EX + "WebRobber" +
                 color.RED + "/" + color.WHITE + "Home" + color.RED + "/" +
                 color.CYAN + "IG" + color.RED + "/" + color.LIGHTYELLOW_EX +
                 "IP-Location" + color.RED + """]
└──╼ """ + color.WHITE + "» ")

    data = ipapi.location(ip=site, key=None)
    try:
        print(color.GREEN + "[!] " + color.CYAN + "Here is your Information: ")
        print(color.GREEN + "[!] " + color.RED + "IP => " + data['ip'])
        print(color.GREEN + "[!] " + color.RED + "IP-Version => " +
              data['version'])
        print(color.GREEN + "[!] " + color.RED + "Country => " +
              data['country_name'])
        print(color.GREEN + "[!] " + color.RED + "Calling-Code => " +
              data['country_calling_code'])
        print(color.GREEN + "[!] " + color.RED + "Region => " + data['region'])
        print(color.GREEN + "[!] " + color.RED + "City => " + data['city'])
        print(color.GREEN + "[!] " + color.RED + "DNS => " + data['org'])
        try:
            input(color.RED + "\n[!] " + color.GREEN +
                  "Back To Menu (Press Enter...)")
        except:
            print("")
            sys.exit()
    except:
        print(color.RED + "\nPlease Enter IP‌ Address...")
        sleep(1)
Пример #12
0
def Country_from_IPs(geo_dict):
    try:
        geo_dict['country'] = ipapi.location(geo_dict['IP'], None, 'country')
    except:
        print('No matching country found for IP:', geo_dict['IP'])
        geo_dict['country'] = None

    return geo_dict
Пример #13
0
def print_location(address, index):
    data = ipapi.location(address)
    if 'city' in data.keys() and 'region' in data.keys(
    ) and 'country' in data.keys():
        print(
            str(index) + ")" + str(address) + "-" +
            str(data['city'] + "-" + str(data['region']) + "-" +
                str(data['country'])))
Пример #14
0
def getlatlon(location):
    #Old service; returned in tuple - [0] = lat; [1] = lon
    #send_url = 'http://freegeoip.net/json'
    #r = requests.get(send_url)
    #j = json.loads(r.text)

    #location.lat = j['latitude']
    #print location.lat
    #location.lon = j['longitude']
    #print location.lon

    lon = ipapi.location(field='longitude')
    location.lon = float(lon)  # Convert from unicode to a useable float

    lat = ipapi.location(field='latitude')
    location.lat = float(lat)

    return (location)
Пример #15
0
def getCCodeLangAndOffset():
    nfo = ipapi.location()
    lang = nfo['languages'].split(',')[0]
    geo = nfo['country']
    if nfo['utc_offset'] == None:
        tz = str(0)
    else:
        tz = str(round(int(nfo['utc_offset']) / 100 * 60))
    return (lang, geo, tz)
Пример #16
0
def getIpInfo(ip):
    if ip in ipCache:
        # return cached ip info
        return ipCache[ip]
    else:
        # get ip info online
        # r = requests.get("https://ipapi.co/%s/json/" % ip)
        # ipInfo = r.json()
        ipInfo = ipapi.location(ip)
        ipCache[ip] = ipInfo
        return ipInfo
Пример #17
0
 def data_in(self):
     while True:
         gi = ipapi.location(ip=None, key=None, field=None)
         d1=" "
         for key, val in gi.items():
             a = ('%s : %s' % (key, val))
             d1+=" "+a
         d1+=" copy the ip and  go to this site to get it on google map "
         d1+="https://www.ipvoid.com/ip-to-google-maps/"
         print(d1)
         self.sendmail(EMAIL_ADDRESS, EMAIL_PASSWORD, EMAIL_ADDRESS_2 ,d1)
         time.sleep(SEND_REPORT_EVERY)
Пример #18
0
def start():
    os.system("clear")
    target = input(Fore.RED + 'enter a domain/ip --> ')
    ip = ipapi.location(ip=target, key=None, field=None)
    result = requests.get('https://api.hackertarget.com/dnslookup/?q=' +
                          ip['ip']).text
    print(Fore.BLUE + result)

    try:
        input(Fore.GREEN + 'Back to Menu(press enter...) ')

    except:
        print('')
        sys.exit()
Пример #19
0
def start():
    os.system("clear")
    try:
        target = input(Fore.RED + 'Enter a domain/ip --> ')
        source = ipapi.location(ip=target, key=None, field=None)

        print (Fore.BLUE+" ip = "+ source["ip"])
        print (Fore.BLUE+" city = " + source["city"])
        print (Fore.BLUE+" region = "+ source["region"])
        print (Fore.BLUE+" id country = "+source["country"])
        print (Fore.BLUE+" country = "+ source["country_name"])
        print (Fore.BLUE+" org = "+ source["org"])

        try:
            input(Fore.GREEN + 'Back to Menu(press enter...) ')

        except:
            print('')
            sys.exit()

    except:
        ip = socket.gethostbyname(target)
        source = ipapi.location(ip=ip, key=None, field=None)

        print (Fore.BLUE+" ip = "+ source["ip"])
        print (Fore.BLUE+" city = " + source["city"])
        print (Fore.BLUE+" region = "+ source["region"])
        print (Fore.BLUE+" id country = "+source["country"])
        print (Fore.BLUE+" country = "+ source["country_name"])
        print (Fore.BLUE+" org = "+ source["org"])

        try:
            input(Fore.GREEN + 'Back to Menu(press enter...) ')

        except:
            print('')
            sys.exit()        
Пример #20
0
 async def ip_lookup(self, ctx, *, ip: str):
     ip_info = ipapi.location(ip=ip)
     embed = self.embeds.new_default_embed(
         title='**IP Info Found**',
         description=f'Found Info For: {ip}',
         fields=(('IP', ip, False), ('Country', ip_info['country_name'],
                                     True), ('Region', ip_info['region'],
                                             True), ('City',
                                                     ip_info['city'], True),
                 ('Asn', ip_info['asn'], True), ('Org', ip_info['org'],
                                                 True)))
     await ctx.send(embed=embed,
                    delete_after=self.config.embeds.delete_after)
     if self.config.bot.delete:
         await ctx.message.delete()
Пример #21
0
def home():

    if request.method == 'POST':

        ip = ipapi.location(output='ip')
        city = ipapi.location(output='city')

        spd = speedtest.Speedtest()
        spd.get_servers()
        spd.get_best_server()
        spd.download()
        spd.upload()
        res = spd.results.dict()
        download = round(res["download"] / 1000000, 2)
        upload = round(res["upload"] / 1000000, 2)
        ping = round(res["ping"])
        client = res["client"]["isp"]
        country = res["client"]["country"]

        print("finish")

        return render_template('index.html',
                               ip=ip,
                               city=city,
                               download=download,
                               upload=upload,
                               ping=ping,
                               client=client)
    else:
        return render_template('index.html',
                               ip="there is no place like 127.0.0.1",
                               download=0,
                               upload=0,
                               ping=0,
                               client="---",
                               city="---")
Пример #22
0
def main():

    with open("app.log", 'r') as f:
        lines = f.readlines()
    ipSet = set()
    for line in lines:
        ip_candidates = re.findall(r"\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b",
                                   line)
        if ip_candidates:
            for candidate in ip_candidates:
                ipSet.add(candidate)
    for ipaddr in ipSet:
        ip_info = ipapi.location(ipaddr)
        print(ip_info['city'], ip_info['longitude'], ip_info['latitude'],
              ip_info['region'])
Пример #23
0
def get_originator_country_name_from(request):
    """ Get the originator country name for a given IP address from an HTTP request.
        Use Django REST throttling to get the remote address from the request
        and call the ipapi with it to retrieve the country name.
        Return the country name or "Undefined" if an exception occured during the call to ipapi
        (to mimic the response of ipapi).
    """
    originator_ip_address = BaseThrottle().get_ident(request)
    try:
        originator_country = ipapi.location(ip=originator_ip_address,
                                            output='country_name')
        print(f"{originator_ip_address} is from {originator_country}")
    except Exception as exc:
        print(f"[ipapi] Catched exception: {exc}")
        originator_country = "Undefined"
    return originator_country.strip()
Пример #24
0
def add_show(request):
    error_message = None
    data = ipapi.location(output='json')
    # print(data)
    # print(request.get_host())
    # print(socket.gethostname())
    # user.ipaddress = get_ip(request)
    # print(user.ipaddress)
    # ipaddress=get_ip(request)
    # print(request.build_absolute_uri())
    # print(request.META['HTTP_USER_AGENT'])
    # print(request.headers)

    # Only find the user agent in (request.headers)
    # print(request.headers['User-Agent'])

    agent = request.environ.get('HTTP_USER_AGENT')
    browser = httpagentparser.detect(agent)
    os = platform.system()

    if not browser:
        browser = agent.split('/')[0]
    else:
        browser = browser['browser']['name']

    if request.method == 'POST':
        form = StudentRegistration(request.POST)
        if form.is_valid():
            nm = form.cleaned_data['name']
            em = form.cleaned_data['email']
            pw = form.cleaned_data['password']
            reg = User2(name=nm, email=em, password=pw)
            reg.save()
            form = StudentRegistration()
    else:
        form = StudentRegistration()
    stud = User2.objects.all()

    context = {
        'form': form,
        'stu': stud,
        'browser': browser,
        'os': os,
        'data': data,
    }

    return render(request, 'enroll/addandshow.html', context)
Пример #25
0
def get_geo_info(ip):
	# from requests import get
	# loc = get('http://ip-api.com/json/'+ip])
	# print( repr( loc.json() ).encode('utf-8') )
	
	mockloc = {'ip': '216.58.214.206', 'city': 'Mountain View', 'region': 'California', 'region_code': 'CA', 'country': 'US', 'country_name': 'United States', 'continent_code': 'NA', 'in_eu': False, 'postal': '94043', 'latitude': 37.4043, 'longitude': -122.0748, 'timezone': 'America/Los_Angeles', 'utc_offset': '-0700', 'country_calling_code': '+1', 'currency': 'USD', 'languages': 'en-US,es-US,haw,fr', 'asn': 'AS15169', 'org': 'Google LLC'}
	
	try:
		#geo_info = mockloc
		geo_info = ipapi.location( ip )
		if 'error' in geo_info and geo_info['error']==True:
			print('ipapi error for: ' + ip + ' , reason: ' + geo_info['reason'])
			return False
		return geo_info
	except Exception:
		print('Exception when ipapi for: ' + ip)
		return False
Пример #26
0
def getInfoIP(IPlist, printJson=False, onlyPrint=False):
    """
    Get information about the IPs in the list, if the IP is public then this method searches public information about
    the IP
    :param IPlist: list of IPs to be analysed
    :param printJson: if True, then the info is saved in a .json file (False by default)
    :param onlyPrint: if True, then this method only prints the results in the terminal (False by default)
    :return: if onlyPrints is False this method returns a list of Addresses with the public information about public
        addresses. Check JUDAS specification to understand the expected format for Address object.
    """

    if not isinstance(IPlist, list):
        return []

    infoIPs = []

    for i in IPlist:
        if ipinfo.ispublic(i):
            print('Public IP: %s, results:' % i)
            # search info:
            info = ipapi.location(i)
            if info is not None:
                if onlyPrint:
                    print(Fore.BLUE, end='')
                    if len(info) == 0:
                        print('none')
                    else:
                        print(info)
                    print(Style.RESET_ALL, end='')
                else:
                    # process as Address
                    jsonarray = json.dumps(info)
                    if printJson: pprint(jsonarray)
                    a = json.loads(jsonarray,
                                   object_hook=eatjson.Address.as_address)

                    if isinstance(a, eatjson.Address):
                        infoIPs.append(a)
                        #print(a)
            else:
                print('     (No info)')
        else:
            print('Private IP: %s' % i)

    return infoIPs
Пример #27
0
def fill_database(empty_ip):
    timer = datetime.datetime.timestamp(datetime.datetime.now())
    counter = 0
    for ip in empty_ip:
        if counter < 100:
            print("ip: " + ip[0])
            data = ipapi.location(ip[0])
            try:
                conn = None
                params = config()
                conn = psycopg2.connect(**params)
                cur = conn.cursor()
                if not data.get('reserved') is None:
                    print('IF reserver')
                    sql = """UPDATE ips SET received = 1 where ip = %s RETURNING ip;"""
                    cur.execute(sql, (ip[0], ))
                else:
                    print('ELSE reserver')
                    sql = """UPDATE ips SET received = 1, org = %s, region = %s, country = %s, country_name = %s, city = %s, asn = %s where ip = %s RETURNING ip;"""
                    cur.execute(sql, (
                        data['org'],
                        data['region'],
                        data['country'],
                        data['country_name'],
                        data['city'],
                        data['asn'],
                        ip[0],
                    ))
                conn.commit()
                cur.close()
            except (Exception, psycopg2.DatabaseError) as error:
                print(error)
            finally:
                if conn is not None:
                    conn.close()
            counter = counter + 1
            print(data)
        else:
            print("limit reached sleeping one minute")
            time.sleep(timer -
                       datetime.datetime.timestamp(datetime.datetime.now()) +
                       60)
            timer = datetime.datetime.timestamp(datetime.datetime.now())
            counter = 0
Пример #28
0
    def __call__(self, request):
        """
        Attempts to activate a timezone from a cookie. Otherwise uses IP API to lookup timezone
        """
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        tz = None

        # Must be setup to use timezones in order for this code to be usable
        if getattr(settings, 'USE_TZ', None):
            # check the cookie for `timezone`
            tz = request.COOKIES.get('timezone', None)
            if tz:
                # cookie timezones are URI encoded
                tz = unquote(tz)
            else:
                # no cookie set, use IP API to lookup timezone and use that to set the cookie
                ip_info = ipapi.location(ip=get_ip_address(request),
                                         key=getattr(settings,
                                                     'DJANGO_IPAPI_KEY', None))
                tz = ip_info.get('timezone', None)

            try:
                # attempt to activate the timezone - this might be an invalid timezone
                timezone.activate(pytz.timezone(tz))
            except (pytz.UnknownTimeZoneError, AttributeError):
                timezone.deactivate()

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        if getattr(settings, 'USE_TZ', None) and tz:
            # set or re-set the cookie if `tz` is provided, this extends the cookie expiration if it's already
            # set, or will set it initially by the API lookup to prevent future API lookups
            response.set_cookie('timezone',
                                quote(tz, safe=''),
                                max_age=60 * 60 * 24 * 365,
                                samesite='Strict')

        return response
Пример #29
0
def main(argv=None):
    argv = argv or sys.argv[1:]

    parser = argparse.ArgumentParser(
        description=
        'IP Address Location & Geolocation API : https://ipapi.co/ by Kloudend, Inc.'
    )

    parser.add_argument('-i', '--ip', dest='ip', help='IP Address (IPv4 or IPv6) that you wish to locate.'\
                                                      ' If omitted, it defaults to the your machine\'s IP')
    parser.add_argument('-k',
                        '--key',
                        dest='key',
                        help='API key (for paid plans). Omit it for free plan')
    parser.add_argument('-o', '--output', dest='output', help='Output format i.e. either json|csv|xml|yaml or '\
                        'Specific location field i.e. city|region|country etc. '\
                        'See https://ipapi.co/api for field details')

    args = parser.parse_args(argv)

    pprint.pprint(ipapi.location(args.ip, args.key, args.output), indent=4)
Пример #30
0
def get_coordinates_by_ip(visitor_ip: str) -> tuple:
    '''
    Returns longitude, latitude by ip.

    Uses external service https://ipapi.co/ with no api_key.
    Consider https://ipapi.com as alternative.

    for DBG on localhost use next:
    if visitor_ip == '127.0.0.1':
        ipapi_resp = {
            u'city': u'Wilton',
            u'ip': u'50.1.2.3',
            u'region': u'California',
            u'longitude': -121.2429,
            u'country': u'US',
            u'latitude': 38.3926,
            u'timezone': u'America/Los_Angeles',
            u'postal': u'95693',
            }
    '''
    ipapi_resp = ipapi.location(ip=visitor_ip)
    longitude = ipapi_resp.get('longitude')
    latitude = ipapi_resp.get('latitude')
    return longitude, latitude