示例#1
0
 def _reader(self, folder, lst):
     try:
         for filename in os.listdir(os.getcwd() + "/" + folder):
             try:
                 with open(os.path.join(os.getcwd(), folder, filename),
                           'r') as fh:
                     for line in fh:
                         if self.IP_MATCHER.findall(line):
                             lst.append([
                                 self.IP_MATCHER.search(line).group(1),
                                 self.DATE_MATCHER.search(line).group(1),
                                 DbIpCity.get((
                                     self.IP_MATCHER.search(line).group(1)),
                                              api_key='free').country,
                                 DbIpCity.get((
                                     self.IP_MATCHER.search(line).group(1)),
                                              api_key='free').city
                             ])
                             # DbIpCity.get((self.IP_MATCHER.search(line).group(1)), api_key = 'free').region,
                             # DbIpCity.get((self.IP_MATCHER.search(line).group(1)), api_key = 'free').longitude,
                             # DbIpCity.get((self.IP_MATCHER.search(line).group(1)), api_key = 'free').latitude])
             except IOError:
                 print("File cannot be accessed")
     except IOError:
         print("No such folder directory")
     try:
         lst[0]
     except IndexError:
         print("Couldn't find IP or Date. Please verify log files content.")
     else:
         return lst
示例#2
0
 def getDetailsTarget(self):
     if self.ip is None :
         self.hostname = input('[*] Type your target (ip or hostname): ')
         location =  DbIpCity.get(self.getIPFromHostname(), api_key='free')
     else :
         location =  DbIpCity.get(self.ip, api_key='free')
         
     print('\r\n')
     
     self.country = location.country
     self.city = location.city
     self.region = location.region
     self.lat = location.latitude
     self.lng = location.longitude
     return self.country,self.city,self.region,self.lat,self.lng
示例#3
0
    def currency(ip):
        """
                currency: [{
                'code': 'CAD',
                'name': 'Canadian dollar',
                'symbol': '$'
                }]
                """

        response = DbIpCity.get(ip, api_key='free')
        country = pycountry.countries.get(alpha_2=response.country)
        name = str(country.alpha_3).lower()

        start_time = datetime.now()

        url = "https://restcountries.eu/rest/v2/alpha/%s" % name
        res = requests.get(url)
        con = res.json()

        finish_time = datetime.now()

        time = str(finish_time - start_time)
        money = {
            "currency": con["currencies"],
            "time": {
                "response time": "time",
                "acceptable time": " under 3s"
            }
        }
        return money
示例#4
0
def adminAdd(request):
    form = CreateAdminUserForm(request.POST)
    if request.method == "POST":
        try:
            if form.is_valid():
                user = form.save()

                group = Group.objects.get(name='admin')
                user.groups.add(group)
                ip, is_routable = get_client_ip(request)
                if ip is None:
                    ip = "0.0.0.0"
                try:
                    response = DbIpCity.get(ip, api_key='free')
                    country = response.country + " | " + response.city
                except:
                    country = "Unknown"
                Admins.objects.create(
                    user=user,
                    name=user.username,
                    ip=ip,
                    country=country,
                )
                return redirect('admin_list')

        except:
            messages.info(request, 'Errors found')
    context = {'form': form}
    return render(request, 'back/admin_add.html', context)
示例#5
0
def qa_inference(request):
    if request.method == "POST":
        form = QAForm(request.POST)
        if form.is_valid():
            ip = get_client_ip(request)
            data = DbIpCity.get(str(ip), api_key='free')
            user = str(data.to_json())

            # user='******'
            post = form.save(commit=False)
            post.user = user
            post.published_date = timezone.now()

            para = post.context
            question = post.question
            result = predict_answer_QA(question,para)
            post.answer = result

            post.save()

            start = para.lower().find(result)
            end = start + len(result)
            para1 = para[:start]
            para2 = para[end:]



            return render(request,'qa_result.html', {'para1':para1,'para2':para2,'result':result})
    else:
        form = QAForm()
    return render(request, 'qaForm.html', {'form': form})
示例#6
0
文件: views.py 项目: aphordit/MySite
def home2(request):
    menu = Menu.objects.all()
    submenu = Submenu.objects.all()
    rand = ''
    for i in range(100):
        rand = rand + random.choice(string.ascii_letters)
    count = News.objects.count()
    randnewsname = News.objects.all()[random.randint(0, count - 1)]
    rand = random.randint(1000000000, 9999999999)
    fill = News.objects.filter(date__gte='1398/01/02', date__lte='1398/07/02')
    tilname = News.objects.filter(news_titel__contains='شی')
    ip, is_routable = get_client_ip(request)
    country = "-"
    try:
        response = DbIpCity.get('5.190.112.0', api_key='free')
        country = response.country + "|" + response.city
    except:
        print('not ssssssssssssssssssssssssssssssssssssssssssssss')
    return render(
        request, 'Front/home2.html', {
            'menu': menu,
            'submenu': submenu,
            'rand': rand,
            'randnewsname': randnewsname,
            'fill': fill,
            'tilname': tilname,
            'ip': ip,
            'is_routable': is_routable,
            'country': country
        })
示例#7
0
def check_user_location(ip_address):

    r = redis.from_url(redis_to_go)
    user = r.get(ip_address)

    if user:

        unpacked_user = json.loads(user)
        return unpacked_user

    else:

        try:
            response = DbIpCity.get(ip_address, api_key='free')
            details = {
                "ip_address": response.ip_address,
                "city": response.city,
                "region": response.region,
                "country": response.country.lower(),
                "latitude": response.latitude,
                "longitude": response.longitude
            }
            cache_details(ip_address, details)
            return details
        except:
            # If something's wrong it returns False
            return False
 def create_session_entry(self, request, user, template):
     """
     Method for to assemble all necessary information to create a
     session entry in the Database. The entry function is called in this
     function.
     :param request: object that contains the view arguments (e.g user-agent or IP)
     :param user: the current user
     :param template: the name of the template that is used in this session
     :return: None
     """
     print("Creating Session Entry")
     ua = request.headers.get('User-Agent')
     ip = request.remote_addr
     language = request.accept_languages[0][0]
     fingerprint = hash(ua + ip + language)
     device = parse(ua).device.family
     try:
         location = DbIpCity.get(ip, api_key='free').country
     except KeyError:
         location = None
     except Exception as e:
         print(f"Internal Exception for calculating the Location: {e}")
         location = None
     website_id = self.get_website_id(template)[0]
     self.insert_session(website_id=website_id,
                         user_id=user,
                         language=language,
                         device=device,
                         location=location,
                         browser_fp=fingerprint,
                         ip_address=ip)
示例#9
0
def Render404(request, exception):
    
    # get, lookup ip address:
    ip_address = request.META['HTTP_X_REMOTE_ADDR']
    ip_lookup = DbIpCity.get(ip_address, api_key='free')
    
    # convert ip_lookup to python dictionary:
    visitor_kwargs = json.loads(ip_lookup.to_json())
    
    # look up, add add country full name:
    visitor_kwargs['country_full_name'] = country_codes[visitor_kwargs['country']]
    
    # add missng elements to visitor object:
    if visitor_kwargs['latitude'] is None:
        
        # check city name:
        if visitor_kwargs['city'] == 'Moscow (Tsentralnyy administrativnyy okrug)':
            visitor_kwargs['latitude'] = 37.613
            visitor_kwargs['longitude'] = 55.767
            
        if visitor_kwargs['city'] == 'Zarvanytsya':
            visitor_kwargs['latitude'] = 49.219
            visitor_kwargs['longitude'] = 25.371
    
    # create visitor object:
    visitor = Visitor.objects.create(**visitor_kwargs)
    visitor.save()
    
    # pack context:
    context = {'status' : 404}
    
    return render(request, '404.html', context=context)
示例#10
0
def get_country_code():
    country_last = "US"
    if "country_last" in settings:
        country_last = settings["country_last"]
    country_last_updated = datetime.fromtimestamp(0)
    if "country_last_updated" in settings:
        country_last_updated = settings["country_last_updated"]

    now = datetime.now()
    delta = now - country_last_updated
    if delta.total_seconds() < 86400:
        return country_last

    try:
        myIp = urllib.request.urlopen('http://icanhazip.com/',
                                      timeout=2).read().strip()
        response = DbIpCity.get(myIp, api_key='free')
        country_last = response.country
    except:
        pass

    settings["country_last_updated"] = now
    settings["country_last"] = country_last
    settings.flush()
    return country_last
示例#11
0
def create_peer_map(peer_info):
    
    peer_map = folium.Map(
                    location=[40.710982, 8.799805],
                    zoom_start=3,
                    tiles='Stamen Toner'
                )

    tooltip = 'Click me!'

    for peer_ip, info in peer_info.items():

        try:
            response = DbIpCity.get(peer_ip, api_key='free')
        except KeyError:
            continue

        lat = response.latitude
        lon = response.longitude

        folium.Marker([lat, lon], popup='<i>' + str(info.get('city')) + '</i>', tooltip=tooltip).add_to(peer_map)
    
    peer_map.save('index.html')
    time.sleep(1)
    webbrowser.open('index.html')
示例#12
0
    def choose_location(param_dict, ip, default):
        """
        function to get the location and decide on displaying it based on the given parameters
        :param param_dict: Dictionary with all given parameters
        :param ip: the ip address of the current user
        :param default: default value for the location
        :return: location based on parameters (default = "International")
        """

        if "location" in param_dict:
            location_parameter = param_dict["location"]
        else:
            location_parameter = default

        try:
            ip_location = DbIpCity.get(ip, api_key='free').country
        except errors.InvalidRequestError:
            ip_location = "International"
        except KeyError:
            ip_location = "International"

        if location_parameter == "p":
            location = ip_location
        elif location_parameter == "d":
            location = choice([ip_location, "International"])
        elif location_parameter == "s":
            location = "international"
        else:
            location = location_parameter
        return location
示例#13
0
def try_login():
    get_users()
    global logged_in
    temp_user = User(request.form['user'], request.form['pw'])
    for user_info in users:
        if temp_user == user_info:
            logged_in = True
    if not logged_in:
        global used_before
        used_before = False
        ip = request.environ['REMOTE_ADDR']
        print(ip)
        response = DbIpCity.get(ip, api_key='free')
        location = str(response.latitude) + ', ' + str(response.longitude)
        temp_session = Session(ip, location)
        for session in sessions:
            if session == temp_session:
                session.make_attempt(1)
                used_before = True
                global wait
                wait = analyze_session(session)
        if not used_before:
            sessions.append(Session(ip, location))

    return redirect('/login')
示例#14
0
    def sniff_continuously(self):
        self.capture = pyshark.LiveCapture(self.interface, self.bpf_filter)
        print('Waiting for Slippi game...')

        for packet in self.capture.sniff_continuously():
            try:
                packet_content = binascii.unhexlify(packet.data.data)
            except AttributeError:
                continue

            if b"get-ticket-resp" in packet_content:
                display_name = re.search(self.re_display_name,
                                         str(packet_content)).group(1)
                connect_code = re.search(self.re_connect_code,
                                         str(packet_content)).group(1)
                ip_address = re.search(
                    self.re_address,
                    str(packet_content)).group(1).partition(':')[0]

                # Temporary.
                r = DbIpCity.get(ip_address, api_key='free')
                region = r.region
                country = r.country

                print('Opponent:')
                print('  Display name:  %s' % display_name)
                print('  Connect code:  %s' % connect_code)
                print('  IP-address:    %s' % ip_address)
                print('  From:          %s, %s' % (r.region, r.country))

                self.post_whomst(display_name, connect_code, ip_address,
                                 r.region + ', ' + r.country)
def get_lat_log(ip: str) -> Tuple[str, str]:
    try:
        res = DbIpCity.get(ip, api_key="free")
        lat, lng = str(res.latitude), str(res.longitude)
        return lat, lng
    except:
        return "", ""
def extract_location(attachment_data):
    upload_ip = None
    latitude = None
    longitude = None
    if "media_metadata" in attachment_data['media']:
        if "photo_metadata" in attachment_data['media']['media_metadata']:
            if "upload_ip" in attachment_data['media']['media_metadata'][
                    'photo_metadata']:
                upload_ip = attachment_data['media']['media_metadata'][
                    'photo_metadata']['upload_ip']

        if "video_metadata" in attachment_data['media']['media_metadata']:
            if "upload_ip" in attachment_data['media']['media_metadata'][
                    'video_metadata']:
                upload_ip = attachment_data['media']['media_metadata'][
                    'video_metadata']['upload_ip']

    if upload_ip:
        if upload_ip not in geo_ip_cache:
            try:
                response = DbIpCity.get(upload_ip, api_key='free')
            except KeyError as err:
                logger.error("Error getting location data for %s" % upload_ip)
                response = None
            geo_ip_cache[upload_ip] = response
            pickle.dump(geo_ip_cache, open("geo_ip_cache.pickle", 'wb'))
        else:
            response = geo_ip_cache[upload_ip]
        if response:
            latitude = response.latitude
            longitude = response.longitude

    return latitude, longitude
示例#17
0
def home(request):
    """Displays Home Page"""
    user_ip = get_client_ip(request)
    if user_ip != "24.20.48.43":
        response = DbIpCity.get(user_ip, api_key='free')
        print(user_ip, "in", response.city, ",", response.region, ",", response.country, " visited the home page at ", datetime.now())

    return redirect(all_playlists)
 def getLocation(self):
     try:
         response = DbIpCity.get(self.ip, api_key='free')
         self.location = pycountry.countries.get(
             alpha_2=response.country).name
     except:
         print("Can not get location of:", self.ip)
         self.location = "Unknown"
def get_ip_address(req: request) -> str:
    ip_address = "0.0.0.0"
    try:
        res = DbIpCity.get(req.environ["REMOTE_ADDR"], api_key="free")
        ip_address = res.ip_address
    except:
        pass
    return ip_address
示例#20
0
文件: blue1.py 项目: zoetech410/blue
def geo_tool():
    try:
        print("*** GEOLOCATION INFORMATION ***\n")
        s = socket.gethostbyname(url)
        response = DbIpCity.get(s, api_key='free')
        print(response, "\n")
    except:
        print("GEOLOCATION TOOL IS NOT WORKING")
示例#21
0
def main():
    try:
        print(colorama.Fore.GREEN + '\tДействия:', '\n', colorama.Fore.YELLOW +
              '[', colorama.Fore.RED + '1', colorama.Fore.YELLOW + ']',
              colorama.Fore.GREEN + 'Получить баланс\n', colorama.Fore.YELLOW +
              '[', colorama.Fore.RED + '2', colorama.Fore.YELLOW + ']',
              colorama.Fore.GREEN + 'Перевести деньги на кошелёк QIWI\n',
              colorama.Fore.YELLOW + '[', colorama.Fore.RED + '3',
              colorama.Fore.YELLOW + ']', colorama.Fore.GREEN +
              'Получить данные о профиле\n', colorama.Fore.YELLOW + '[',
              colorama.Fore.RED + '4', colorama.Fore.YELLOW + ']',
              colorama.Fore.GREEN + 'Получить историю транзакций\n',
              colorama.Fore.YELLOW + '[', colorama.Fore.RED + '5',
              colorama.Fore.YELLOW + ']',
              colorama.Fore.GREEN + 'Узнать IP и местоположение\n')
        print(colorama.Fore.GREEN + ">", end='')
        command = int(input())
        if command == 1:
            api = QApi(token=token, phone=phone)
            balance = api.balance
            print(colorama.Fore.GREEN + "Баланс: ", balance)
        elif command == 2:
            print(colorama.Fore.GREEN + "Ваш телефон: ", end='')
            phone1 = input()
            print(colorama.Fore.GREEN + "Телефон получателя: ", end='')
            phone2 = input()
            print(colorama.Fore.GREEN + "Сумма перевода: ", end='')
            amount = input()
            print(colorama.Fore.GREEN + "Комментарий: ", end='')
            comment = input()
            api = QApi(token=token, phone=phone1)
            api.pay(account=phone2, amount=amount, comment=comment)
            print(colorama.Fore.GREEN + "Переведено!")
            sleep(1)
        elif command == 3:
            api = Qiwi(token)
            print(json.dumps(api.get_profile(), indent=1, sort_keys=True))
        elif command == 4:
            api = Qiwi(token)
            print(json.dumps(api.history(), sort_keys=True, indent=1))
        elif command == 5:
            api = Qiwi(token)
            x = api.get_profile()
            ipadress = x['authInfo']['ip']
            print(colorama.Fore.GREEN + '\nIP: ', ipadress)
            response = DbIpCity.get(ipadress, api_key='free')
            print(colorama.Fore.GREEN + "Город: ", response.city)
            print(colorama.Fore.GREEN + "Страна: ", response.country)
            print(colorama.Fore.GREEN + "Широта: ", response.latitude)
            print(colorama.Fore.GREEN + "Долгота: ", response.longitude)
            print(colorama.Fore.GREEN + "Регион: ", response.region)
        else:
            print(colorama.Fore.RED + "Действие не найдено!")
            sleep(2)

    except:
        print(colorama.Fore.RED + "\nОшибка!")
        sleep(1)
示例#22
0
def ip_inf():

        ip = input(str('enter ip address:'))
        response = DbIpCity.get(ip, api_key='free')
        print(f'IP: {ip}')
        print(f'COUNTRY: {response.country}')
        print(f'CITY: {response.city}')
        print(f'LATITUDE: {response.latitude}')
        print(f'LONGTITUDE: {response.longitude}')
示例#23
0
 def getLocation(self):
     if self.country is None:
         location = DbIpCity.get(self.getPublicIp(), api_key='free')
         self.country = location.country
         self.city = location.city
         self.region = location.region
         self.lat = location.latitude
         self.lng = location.longitude
     return self.country, self.city, self.region, self.lat, self.lng
示例#24
0
def myregister(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        uname = request.POST.get('uname')
        email = request.POST.get('email')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        if name == "":
            msg = "Please Input Your Name"
            return render(request, 'front/msgbox.html', {'msg': msg})
        if password1 != password2:
            msg = "Your Password Didn't Match"
            return render(request, 'front/msgbox.html', {'msg': msg})

        count1 = 0
        count2 = 0
        count3 = 0
        for i in password1:
            if "0" < i < "9":
                count1 = 1
            if "A" < i < "Z":
                count2 = 1
            if "a" < i < "z":
                count3 = 1

        if count1 == 0 or count2 == 0 or count3 == 0:
            msg = "Your Password Didn't Strong Enough"
            return render(request, 'front/msgbox.html', {'msg': msg})

        if len(password1) < 8:
            msg = "Your Password Must be Greater Than 8 Characters"
            return render(request, 'front/msgbox.html', {'msg': msg})

        if len(User.objects.filter(username=uname)) == 0 and len(
                User.objects.filter(email=email)) == 0:
            ip, is_routable = get_client_ip(request)
            if ip is None:
                ip = "0.0.0.0"

            try:
                response = DbIpCity.get(ip, api_key='free')
                country = response.country + " | " + response.city

            except:
                country = "Unknown"

            user = User.objects.create_user(username=uname,
                                            email=email,
                                            password=password1)
            b = Manager(name=name,
                        utxt=uname,
                        email=email,
                        ip=ip,
                        country=country)
            b.save()

    return render(request, 'front/login.html')
示例#25
0
def geo_locate_ip(ip):
    """
    @IP: 147.229.2.90
    """
    try:
        response = DbIpCity.get(ip, api_key='free')
    except Exception:
        return None
    else:
        return json.loads(response.to_json())
示例#26
0
def open_goo_map():
    try:
        s = socket.gethostbyname(ip.get())
        response = DbIpCity.get(s, api_key='free')
        gMap = "https://www.google.com/maps/search/?api=1&query=" + str(
            response.latitude) + "," + str(response.longitude)
        webbrowser.open(gMap)  #open google map on your default webbrowser
    except:
        open_goo_err = "GEOLOCATION TOOL IS NOT WORKING"
        commandLine.insert(END, open_goo_err)
示例#27
0
def get_default_country(ip_address: str) -> str:
    """Get the user's default country.

    :param ip_address: the user's ip_address
    :precondition: ip_address is a well formed IP address
    :postcondition: correctly returns the user's country based on their IP address
    :return: the user's default country code as a string
    """
    response = DbIpCity.get(f'{ip_address}', api_key='free')
    return response.country
示例#28
0
def geo_tool():
    try:
        a = "\n\n[+][+][+][+] GEOLOCATION [+][+][+][+]\n\n"
        s = socket.gethostbyname(ip.get())
        response = DbIpCity.get(s, api_key='free')
        commandLine.insert(END, a)
        commandLine.insert(END, response)
    except:
        geo_err = "GEOLOCATION TOOL IS NOT WORKING"
        commandLine.insert(END, geo_err)
示例#29
0
    def getActiveCities(self):
        activecities = {}
        for city in g_cities:
            activecities[city] = 0
        for item in self.logdatalines:
            city1 = DbIpCity.get(item["cip"], api_key='free').city
            for city in g_cities:
                if city1 == city:
                    activecities[city] += 1

        return activecities
示例#30
0
def geo_location(IP):
    '''
    Obtain location information of a specified IP.

    Args:
        IP (str): IP of the domain you want to analyse

    Returns:
        DbIpCity (Object): Location info of the address, IP
    '''
    return DbIpCity.get(IP, api_key='free')