jumpserver/apps/audits/utils.py

48 lines
1.3 KiB
Python
Raw Normal View History

2016-08-09 09:27:37 +00:00
# ~*~ coding: utf-8 ~*~
#
2016-10-26 11:10:14 +00:00
2016-11-10 15:54:21 +00:00
from __future__ import unicode_literals
import requests
import ipaddress
from .models import LoginLog
def validate_ip(ip):
try:
2016-11-14 11:28:21 +00:00
ipaddress.ip_address(ip.decode('utf-8'))
2016-11-10 15:54:21 +00:00
return True
except ValueError:
2016-11-14 11:28:21 +00:00
print('valid error')
2016-11-10 15:54:21 +00:00
return False
def write_login_log(username, name='', login_type='W',
terminal='', login_ip='', user_agent=''):
if not (login_ip and validate_ip(login_ip)):
login_ip = '0.0.0.0'
if not name:
name = username
login_city = get_ip_city(login_ip)
LoginLog.objects.create(username=username, name=name, login_type=login_type, login_ip=login_ip,
terminal=terminal, login_city=login_city, user_agent=user_agent)
2016-11-14 11:28:21 +00:00
def get_ip_city(ip, timeout=10):
2016-11-10 15:54:21 +00:00
# Taobao ip api: http://ip.taobao.com//service/getIpInfo.php?ip=8.8.8.8
# Sina ip api: http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=8.8.8.8&format=js
2016-11-14 11:28:21 +00:00
url = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip
2016-11-10 15:54:21 +00:00
r = requests.get(url, timeout=timeout)
city = 'Unknown'
if r.status_code == 200:
try:
data = r.json()
if data['code'] == 0:
city = data['data']['country'] + data['data']['city']
except ValueError:
pass
return city
2016-10-26 11:10:14 +00:00