python脚本获取当前浏览器客户端的公共ip以及其详细信息

python脚本获取当前客户端的公共ip以及其详细信息

import requests
from flask import Flask, request, make_response, send_from_directory
from datetime import datetime
import asyncio
from hypercorn.asyncio import serve
from hypercorn.config import Config
import os
import pytz

app = Flask(__name__)

def get_current_time_in_timezone(timezone):
    tz = pytz.timezone(timezone)
    current_time = datetime.now(tz)
    return current_time.strftime('%Y-%m-%d %H:%M:%S %Z')

@app.route('/')
def get_ip_location():
    ip_address = request.headers.get('X-Real-IP')
    if not ip_address:
        ip_address = request.headers.get('X-Forwarded-For', '').split(',')[0]
        if not ip_address:
            return "无法获取IP地址", 400

    try:
        # 获取IP地址的地理位置
        response = requests.get(f"http://ipinfo.io/{ip_address}/json")
        data = response.json()
        city = data.get('city', '未知')
        country = data.get('country', '未知')
        location = f"<h3 style='font-family: 华文中宋;'>Your IP Address: </h3><i style='font-family: 华文中宋;'>{ip_address}</i><h3 style='font-family: 华文中宋;'>Country: </h3><i style='font-family: 华文中宋;'>{country}</i> <h3 style='font-family: 华文中宋;'>City: </h3><i style='font-family: 华文中宋;'>{city}</i>"

        # 获取经纬度
        loc = data.get('loc', '')
        if loc:
            latitude, longitude = loc.split(',')
            location += f"<h3 style='font-family: 华文中宋;'>Longitude and latitude: </h3><i style='font-family: 华文中宋;'> Longitude: {longitude}, Latitude: {latitude}</i>"

        # 获取时区和当前时间
        timezone = data.get('timezone', '')
        current_time = get_current_time_in_timezone(timezone)
        location += f"<h3 style='font-family: 华文中宋;'>Timezone: </h3><i style='font-family: 华文中宋;'>{timezone}</i><h3 style='font-family: 华文中宋;'>IP' current time: </h3><i style='font-family: 华文中宋;'>{current_time}</i>"

        # 获取客户端的user-agent信息
        user_agent = request.headers.get('User-Agent', '未知')
        location += f"<h3 style='font-family: 华文中宋;'>User-Agent:</h3><i style='font-family: 华文中宋;'>{user_agent}</i>"

        # 限制页面内容在300字节以内
        location = location.encode('utf-8')
        response = make_response(location)
        response.headers['Content-Length'] = len(location)
        
        return response
    except Exception as e:
        return str(e), 500

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path), 'favicon.ico', mimetype='image/vnd.microsoft.icon')

if __name__ == '__main__':
    config = Config()
    config.bind = ["0.0.0.0:5000"]
    config.http_timeout = 20
    
    asyncio.run(serve(app, config))

* 其中涉及到的包模块,本地没有的,需要自己去pip install一下,这个脚本需要python3去启动

输出信息如下:

Your IP Address: 

Country: 

City: 

LongLat: 

Timezone: 

IP' current time: 

User-Agent:

升级版

import requests
from flask import Flask, request, make_response, send_from_directory
from datetime import datetime
import asyncio
from hypercorn.asyncio import serve
from hypercorn.config import Config
import os
import pytz

app = Flask(__name__)

# Set to store unique IP addresses visited
visited_ips = set()

# Dictionary to store total visit count
visit_counts = 0

def get_current_time_in_timezone(timezone):
    tz = pytz.timezone(timezone)
    current_time = datetime.now(tz)
    return current_time.strftime('%Y-%m-%d %H:%M:%S %Z')

@app.route('/')
def get_ip_location():
    global visited_ips, visit_counts
    ip_address = request.headers.get('X-Real-IP')
    if not ip_address:
        ip_address = request.headers.get('X-Forwarded-For', '').split(',')[0]
        if not ip_address:
            return "无法获取IP地址", 400

    try:
        # Increment visit count for all IP addresses
        visit_counts += 1

        # Add IP address to visited set
        visited_ips.add(ip_address)

        # 获取IP地址的地理位置
        response = requests.get(f"http://ipinfo.io/{ip_address}/json")
        data = response.json()
        city = data.get('city', '未知')
        country = data.get('country', '未知')
        location = f"<h3 style='font-family: 华文中宋;'>Your IP Address: </h3><i style='font-family: 华文中宋;'>{ip_address}</i><h3 style='font-family: 华文中宋;'>Country: </h3><i style='font-family: 华文中宋;'>{country}</i> <h3 style='font-family: 华文中宋;'>City: </h3><i style='font-family: 华文中宋;'>{city}</i>"

        # 获取经纬度
        loc = data.get('loc', '')
        if loc:
            latitude, longitude = loc.split(',')
            location += f"<h3 style='font-family: 华文中宋;'>Loc: </h3><i style='font-family: 华文中宋;'> Longitude: {longitude}, Latitude: {latitude}</i>"

        # 获取时区和当前时间
        timezone = data.get('timezone', '')
        current_time = get_current_time_in_timezone(timezone)
        location += f"<h3 style='font-family: 华文中宋;'>Timezone: </h3><i style='font-family: 华文中宋;'>{timezone}</i><h3 style='font-family: 华文中宋;'>IP current time: </h3><i style='font-family: 华文中宋;'>{current_time}</i>"

        # 获取客户端的user-agent信息
        user_agent = request.headers.get('User-Agent', '未知')
        location += f"<h3 style='font-family: 华文中宋;'>User-Agent:</h3><i style='font-family: 华文中宋;'>{user_agent}</i>"

        # Add total visit count information
        location += f"<h3 style='font-family: 华文中宋;'>Visits count: </h3><i style='font-family: 华文中宋;'>{visit_counts}</i>"

        # 限制页面内容在300字节以内
        location = location.encode('utf-8')
        response = make_response(location)
        response.headers['Content-Length'] = len(location)

        # Save visited IP addresses to a file
        with open("visit_log.txt", "a") as file:
            file.write(ip_address + '\n')

        return response
    except Exception as e:
        return str(e), 500

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path), 'favicon.ico', mimetype='image/vnd.microsoft.icon')

if __name__ == '__main__':
    config = Config()
    config.bind = ["0.0.0.0:5000"]
    config.http_timeout = 20
    
    asyncio.run(serve(app, config))

 

posted @ 2024-04-30 10:06  hkgan  阅读(50)  评论(0编辑  收藏  举报