jumpserver/apps/audits/utils.py

51 lines
1.4 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
2016-12-29 11:17:00 +00:00
def write_login_log(username, name='', login_type='',
login_ip='', user_agent=''):
2016-11-10 15:54:21 +00:00
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)
2016-12-29 11:17:00 +00:00
LoginLog.objects.create(username=username, name=name, login_type=login_type,
login_ip=login_ip, login_city=login_city, user_agent=user_agent)
2016-11-10 15:54:21 +00:00
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
2016-12-29 11:17:00 +00:00
# Sina ip api: http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=8.8.8.8&format=json
2016-11-10 15:54:21 +00:00
2016-12-29 11:17:00 +00:00
url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=%s&format=json' % ip
try:
r = requests.get(url, timeout=timeout)
except requests.Timeout:
r = None
2016-11-10 15:54:21 +00:00
city = 'Unknown'
2016-12-29 11:17:00 +00:00
if r and r.status_code == 200:
2016-11-10 15:54:21 +00:00
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