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"<b>Your IP Address: </b> {ip_address}<br> <br><b>Country: </b> {country}<br><br><b>City: </b> {city}<br><br>"
# 获取经纬度
loc = data.get('loc', '')
if loc:
latitude, longitude = loc.split(',')
location += f"<b>LongLat: </b>Longitude: {longitude}, Latitude: {latitude}<br><br>"
# 获取时区和当前时间
timezone = data.get('timezone', '')
current_time = get_current_time_in_timezone(timezone)
location += f"<b>Timezone: </b> {timezone}<br><br><b>IP' current time: </b> {current_time}<br><br>"
# 获取客户端的user-agent信息
user_agent = request.headers.get('User-Agent', '未知')
location += f"<b>User-Agent:</b> {user_agent}"
# 限制页面内容在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:
标签:get,python,ip,current,location,import,timezone,客户端 From: https://www.cnblogs.com/hkgan/p/18167237